diff --git a/.env.example b/.env.example index 35ea12a885..df63e08e0e 100644 --- a/.env.example +++ b/.env.example @@ -19,4 +19,13 @@ FORWARDED_ALLOW_IPS='*' # DO NOT TRACK SCARF_NO_ANALYTICS=true DO_NOT_TRACK=true -ANONYMIZED_TELEMETRY=false \ No newline at end of file +ANONYMIZED_TELEMETRY=false + +# Valkey Vector Store (requires VECTOR_DB=valkey) +# VALKEY_URL='valkey://localhost:6379' +# VALKEY_COLLECTION_PREFIX='open_webui' +# VALKEY_INDEX_TYPE='HNSW' +# VALKEY_DISTANCE_METRIC='COSINE' +# VALKEY_HNSW_M='16' +# VALKEY_HNSW_EF_CONSTRUCTION='200' +# VALKEY_HNSW_EF_RUNTIME='10' diff --git a/.github/workflows/docker.yaml b/.github/workflows/docker.yaml index bd46f65d54..abd0362814 100644 --- a/.github/workflows/docker.yaml +++ b/.github/workflows/docker.yaml @@ -143,6 +143,7 @@ jobs: merge: runs-on: ubuntu-latest needs: [build] + if: ${{ !cancelled() }} permissions: contents: read packages: write @@ -168,16 +169,32 @@ jobs: echo "FULL_IMAGE_NAME=${REGISTRY}/${GITHUB_REPOSITORY,,}" >> ${GITHUB_ENV} - name: Download digests + id: download uses: actions/download-artifact@v5 with: pattern: digests-${{ matrix.variant.name }}-* path: /tmp/digests merge-multiple: true + continue-on-error: true + + - name: Check digests + id: check + run: | + count=$(find /tmp/digests -type f 2>/dev/null | wc -l | tr -d ' ') + echo "digest_count=$count" >> $GITHUB_OUTPUT + if [ "$count" -lt 2 ]; then + echo "::warning::${{ matrix.variant.name }}: found $count digest(s), need 2 (one per arch). Skipping merge." + echo "skip=true" >> $GITHUB_OUTPUT + else + echo "skip=false" >> $GITHUB_OUTPUT + fi - name: Set up Docker Buildx + if: steps.check.outputs.skip != 'true' uses: docker/setup-buildx-action@v3 - name: Log in to the Container registry + if: steps.check.outputs.skip != 'true' uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} @@ -185,6 +202,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Extract metadata for Docker images + if: steps.check.outputs.skip != 'true' id: meta uses: docker/metadata-action@v5 with: @@ -201,6 +219,7 @@ jobs: ${{ matrix.variant.suffix != '' && format('suffix={0},onlatest=true', matrix.variant.suffix) || '' }} - name: Create manifest list and push + if: steps.check.outputs.skip != 'true' working-directory: /tmp/digests run: | docker buildx imagetools create \ @@ -208,12 +227,13 @@ jobs: $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *) - name: Inspect image + if: steps.check.outputs.skip != 'true' run: | docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }} copy-to-dockerhub: runs-on: ubuntu-latest - if: github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') + if: ${{ !cancelled() && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) }} needs: [merge] continue-on-error: true strategy: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8654c2f7db..cde26d01c0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,6 +19,7 @@ jobs: timeout-minutes: 10 permissions: contents: write + actions: write steps: - uses: actions/checkout@v5 @@ -43,9 +44,13 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - gh release create "v${{ steps.pkg.outputs.version }}" \ - --title "v${{ steps.pkg.outputs.version }}" \ - --notes-file /tmp/release-notes.md + if gh release view "v${{ steps.pkg.outputs.version }}" &>/dev/null; then + echo "Release v${{ steps.pkg.outputs.version }} already exists — skipping creation" + else + gh release create "v${{ steps.pkg.outputs.version }}" \ + --title "v${{ steps.pkg.outputs.version }}" \ + --notes-file /tmp/release-notes.md + fi - name: Archive source uses: actions/upload-artifact@v4 @@ -57,7 +62,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - name: Dispatch Docker build + - name: Trigger Docker build uses: actions/github-script@v8 with: script: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 95d97dcea0..310d62dc61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,140 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.9.6] - 2026-06-01 + +### Added + +- 📦 **Official knowledge base sync tool.** A new companion tool from Open WebUI, oikb, keeps a knowledge base in sync with a local directory, GitHub repo, S3 bucket, Confluence space, or any of more than 40 other sources, uploading only new and changed files using the incremental sync support added in this release. [oikb](https://github.com/open-webui/oikb) +- 📂 **Smart directory sync for knowledge bases.** Local directories can now be synced into a knowledge base in one action: file checksums are compared against what's already stored, and only added or modified files are uploaded while removed files and orphaned subdirectories are cleaned up, with the directory structure mirrored automatically and per-file progress shown throughout. [#19190](https://github.com/open-webui/open-webui/issues/19190), [#19394](https://github.com/open-webui/open-webui/issues/19394), [Commit](https://github.com/open-webui/open-webui/commit/60c9db1cb81d021589cb49bee8744a799b51211f), [Commit](https://github.com/open-webui/open-webui/commit/73bdf86766d3f44467cdec436786fe089481baf3), [Commit](https://github.com/open-webui/open-webui/commit/9835b3f1dd7aa9c92ff08a634a0f97cc2a046e42), [Commit](https://github.com/open-webui/open-webui/commit/97252fa609440573251d8e75090f347ed1e51e1d), [Commit](https://github.com/open-webui/open-webui/commit/8f2d346e10c47b57bf6b5a6aa02d453488a88b89), [Commit](https://github.com/open-webui/open-webui/commit/1527eb6e01d441225c979d12d78b7625edf1086f) +- 🗂️ **Knowledge base folders.** Files inside a knowledge base can now be organized into nested folders, with breadcrumb navigation that makes it much easier to manage and find content in large collections. [Commit](https://github.com/open-webui/open-webui/commit/c2cbc47ca76ebfa21e1d36279dbd859283cbbfb1), [Commit](https://github.com/open-webui/open-webui/commit/ab0ee858b73738c5b77d1d455e66e66bc61df1c4), [Commit](https://github.com/open-webui/open-webui/commit/2ad327a4dce64a8eedf5eb41c73b8520344fdd82), [Commit](https://github.com/open-webui/open-webui/commit/171150c1e12b5713f77a5ea0dd19c6581c7bef2e), [Commit](https://github.com/open-webui/open-webui/commit/e7d2ddbb1d14c03a52797751d24a98132aac0cd8), [Commit](https://github.com/open-webui/open-webui/commit/32a417bbf66ed28a5ca8a759ad3a87b2a2aa358a) +- 🧰 **Filesystem tool for knowledge bases.** A new built-in tool, enabled via the "ENABLE_KB_EXEC" environment variable, lets AI models browse and search knowledge base contents using familiar filesystem commands such as 'ls', 'cat', 'grep', 'find', 'head', 'tail', and 'sed', including pipes between them. [Commit](https://github.com/open-webui/open-webui/commit/5b125c24d4eae925d3287efa626595bab29d5c33), [Commit](https://github.com/open-webui/open-webui/commit/ecec86dd32aa396dd5a383e9be5b0f16c4346c48), [Commit](https://github.com/open-webui/open-webui/commit/9ef579ce4be5b82f9281b085a621fed5b04e0d26), [Commit](https://github.com/open-webui/open-webui/commit/2f642754ac6b8c430228a7fc289357a6c6652235), [Commit](https://github.com/open-webui/open-webui/commit/3b00e5721a60518ea317c4fd61a6d0d182961a2f), [Commit](https://github.com/open-webui/open-webui/commit/4e78b355efe0611f27fddef591c69f7c1259a9f6), [Commit](https://github.com/open-webui/open-webui/commit/74f95a9b0d6b89b241701422170d54e21e701baa), [Commit](https://github.com/open-webui/open-webui/commit/cc16e06c32de48bdf464db5814483a49f3527b63), [Commit](https://github.com/open-webui/open-webui/commit/1ea54c3217f487990b6a4c0f0d8ea675a479b6e1) +- ✏️ **File renaming in knowledge bases.** Files inside a knowledge base can now be renamed directly from the workspace, with the new name reflected wherever the file is referenced. [Commit](https://github.com/open-webui/open-webui/commit/3127f1b46255626ea92eb0b598e45078287303f1) +- 😀 **Emoji picker in message input.** A new emoji button in the rich text formatting toolbar lets you browse and insert emojis directly into your messages. [#24704](https://github.com/open-webui/open-webui/pull/24704) +- 🪄 **Per-chat skills toggle.** Skills can now be turned on or off for a conversation directly from the chat Integrations menu, the same way tools and capabilities already work, instead of only through the model preset. [#25036](https://github.com/open-webui/open-webui/issues/25036), [#25037](https://github.com/open-webui/open-webui/pull/25037) +- 🔎 **Access preview for users and groups.** Administrators can now preview exactly which models, knowledge bases, and tools a given user or group can access, making it easier to audit and verify permission setups. [Commit](https://github.com/open-webui/open-webui/commit/9c14740ffb009d550dcbd5d6c599dac57053f112) +- 📄 **Configurable knowledge base file page size.** Administrators can now request a larger page size when listing a knowledge base's files through the API, reducing the number of requests needed to retrieve large collections instead of paging through fixed increments of 30. [#25148](https://github.com/open-webui/open-webui/issues/25148), [Commit](https://github.com/open-webui/open-webui/commit/a4d1b3e9378a61a11dd9822a8dbb525f39753081) +- 🔃 **Persistent processing indicator for knowledge files.** Files still being processed in a knowledge base now keep showing a processing indicator across page reloads, so you can tell what's still ingesting after navigating away and back. [#25031](https://github.com/open-webui/open-webui/issues/25031), [Commit](https://github.com/open-webui/open-webui/commit/ad9f2eeb15a448147d5e47e6a391cabb9aefd0ea) +- 📑 **MinerU file type configuration.** Administrators can now configure which file types are processed by the MinerU document loader, via the new "MINERU_FILE_EXTENSIONS" setting, extending it beyond PDF to formats like DOCX, PPTX, and XLSX. [Commit](https://github.com/open-webui/open-webui/commit/d4030a8aa5d48c2a1cb06c461566844aca2530ab) +- 📃 **Legacy Word document support.** Older ".doc" Word files can now have their text extracted by the default document extraction engine, in addition to the modern ".docx" format. [Commit](https://github.com/open-webui/open-webui/commit/9e3e24e304f8ff210494380b46f614a2984cafb3) +- 📁 **Create subfolders from the folder header.** Chat folders can now have subfolders created directly from the folder header in the chat view, not just from the sidebar. [Commit](https://github.com/open-webui/open-webui/commit/1f0948bcbef2af73b155535ea27762c522260afc) +- ⚡ **Faster initial page loads.** The configuration endpoint that loads on every page visit no longer runs an unnecessary user-count query, making the initial application load lighter on the database, especially on instances with many users. [Commit](https://github.com/open-webui/open-webui/commit/0adc090dcbe636c9c9645d8ec7f6b89ea514870b) +- 🚀 **Faster tool-enabled chat completions.** Chat completions that use multiple tools now start faster because the tools they reference are fetched from the database in a single batch query instead of one query per tool. [#24808](https://github.com/open-webui/open-webui/pull/24808), [Commit](https://github.com/open-webui/open-webui/commit/cc94a90b4d4d690bc7cb9f7124f2d6e552973970) +- 🏎️ **More responsive web search under load.** Web search through SearXNG, Google PSE, Brave, Serper, and Serpstack now uses non-blocking network calls, so the server stays responsive to other users while a search is in flight, and concurrent multi-query searches complete faster. [Commit](https://github.com/open-webui/open-webui/commit/b94245d2ee191e8ef118bf9de1ff7539503bfec9) +- 🐎 **Lighter Ollama backend connections.** Requests to Ollama backends now reuse a shared connection pool instead of opening a fresh session each time, reducing TCP and TLS handshake overhead for installs that poll Ollama frequently or have multiple backends configured. [Commit](https://github.com/open-webui/open-webui/commit/5d9a09a88a9094ebfcd249340be3aaee544b34d0) +- 💽 **Fewer redundant model-list writes.** On multi-instance deployments backed by Redis, the model list is no longer rewritten when it hasn't changed, cutting a major source of redundant writes. [#25469](https://github.com/open-webui/open-webui/issues/25469), [#25474](https://github.com/open-webui/open-webui/pull/25474), [Commit](https://github.com/open-webui/open-webui/commit/fd76b51ab2ad4c4192f2c98153e47888712c2009) +- 📉 **Faster websocket disconnect cleanup.** Disconnecting from a collaborative session no longer triggers a scan across the entire Redis keyspace, using a per-session index instead, which keeps disconnects cheap on large deployments. [#25466](https://github.com/open-webui/open-webui/issues/25466), [Commit](https://github.com/open-webui/open-webui/commit/c7de057a4a54cc80f366ad949417e78fae756d4c) +- 📝 **Frontmatter auto-fill for tools, functions, and skills.** Opening a tool, function, or skill editor now auto-fills the name, id, and description fields from the file's frontmatter, saving you from re-entering metadata already declared in the source. [#24649](https://github.com/open-webui/open-webui/pull/24649), [Commit](https://github.com/open-webui/open-webui/commit/ef975649b26d3e7cd589c49be2fc77cee80fad8f) +- 🪪 **More user placeholders in custom headers.** Custom-header templates for direct connections and tool servers now support "{{USER_EMAIL}}" and "{{USER_ROLE}}" alongside the existing user and session placeholders. [Commit](https://github.com/open-webui/open-webui/commit/ed73ef3d8df988b0e9646b82df5b1a453202ef8d) +- ⏱️ **Configurable MCP connection timeout.** The timeout for the initial handshake with an MCP tool server is now configurable via the new "MCP_INITIALIZE_TIMEOUT" setting, so servers that are slow to start or expose many tools can finish connecting instead of timing out. [#25011](https://github.com/open-webui/open-webui/pull/25011), [Commit](https://github.com/open-webui/open-webui/commit/4297c02b121180e239a61c483ac8477cc557d4ef) +- 📐 **Profile image size limit.** Administrators can now cap the size of inline profile images via the new "PROFILE_IMAGE_MAX_DATA_URI_SIZE" setting, bounding how much database and cache space inline avatars and model icons can consume. [#25468](https://github.com/open-webui/open-webui/issues/25468), [#25476](https://github.com/open-webui/open-webui/pull/25476) +- 🎫 **Wildcard OAuth role mapping.** Administrators can now set "\*" in the allowed OAuth roles to grant the user role to any authenticated OAuth user, instead of having to enumerate every accepted role. [#25062](https://github.com/open-webui/open-webui/pull/25062), [Commit](https://github.com/open-webui/open-webui/commit/07cbc91a8eba3a9a3b39588b2ae5de916930af70) +- 📊 **Paginated feedback history.** The feedback and evaluation history list is now paginated, keeping it responsive for instances that have accumulated large numbers of feedback entries. [Commit](https://github.com/open-webui/open-webui/commit/160a6694e4bd66fc42e6361947516e8e15414ef3) +- 🔘 **Bulk enable or disable automations.** Automations can now be enabled or disabled in bulk from an actions menu on the automations page, instead of toggling each one individually. [Commit](https://github.com/open-webui/open-webui/commit/675e9bee5af8b9fb390fcb235a6c2c4766e78c75) +- ➡️ **Optional auto-redirect to single sign-on.** Administrators can now enable "OAUTH_AUTO_REDIRECT" so that, on deployments with a single sign-on provider and no other login methods, users are sent straight to the provider instead of seeing a login page first. [#25067](https://github.com/open-webui/open-webui/pull/25067), [Commit](https://github.com/open-webui/open-webui/commit/d64ef1803d2f5cedb7b3a308151d08ff2cd2b8e1) +- ☁️ **Azure AI Foundry v1 with Entra ID.** Open WebUI now supports Azure AI Foundry's OpenAI v1 endpoint together with Microsoft Entra ID authentication, so these connections work without manual workarounds. [#24761](https://github.com/open-webui/open-webui/issues/24761), [#24985](https://github.com/open-webui/open-webui/pull/24985), [Commit](https://github.com/open-webui/open-webui/commit/eb4eebc3ce1042cb0d393bf890c1895db6e08b19) +- 🌎 **Linkup web search provider.** Administrators can now select Linkup as the web search provider from the admin settings, with options to configure the API key and search depth. [#24752](https://github.com/open-webui/open-webui/pull/24752), [Commit](https://github.com/open-webui/open-webui/commit/56c0d00e13c74d665124ec9f1cae78e83ca60b6a) +- 🧊 **Valkey vector database support.** Valkey can now be used as the vector database backend, configurable through new "VALKEY_URL" and related settings including index type, distance metric, and HNSW tuning. [#24769](https://github.com/open-webui/open-webui/pull/24769), [Commit](https://github.com/open-webui/open-webui/commit/c0f1aa291938bbef62db8d4013dbc498b0abea15) +- 🔄 **General improvements.** Various improvements were implemented across the application to enhance performance, stability, and security. +- 🌐 **Translation updates.** Translations for Spanish (Spain), Swedish, German, Korean, Catalan, Russian, Irish, Simplified Chinese, Traditional Chinese, Finnish, Polish, Turkish, and Malay were enhanced and expanded. + +### Fixed + +- 🛡️ **Security Advisory**: This release includes security and access-control fixes. We recommend updating production deployments at your earliest convenience. Not all security fixes in this version may be enumerated in the fixed section — some may be withheld for a short time to give administrators time to upgrade. [Advisories](https://github.com/open-webui/open-webui/security) +- 🛡️ **Tool server permission enforcement.** The per-user permission for inline tool servers is now enforced on chat-completion requests, so users without that permission can no longer bypass the admin setting by supplying tool servers directly in their requests. [Commit](https://github.com/open-webui/open-webui/commit/5cc1eb517094e3507915664817285f1e6e37a16d) +- 🔒 **Knowledge base access check in search tool.** The built-in knowledge search tool now verifies that the caller can access a knowledge base before searching it by id, preventing users from reading the contents of knowledge bases they have not been granted access to. [#25113](https://github.com/open-webui/open-webui/pull/25113) +- 🗄️ **Cross-user access to retrieval collections.** Resolving the documents used for retrieval now verifies the caller's access to each referenced file and rejects client-supplied collection names, preventing a crafted request from pulling another user's files or vector collections into its context. [Commit](https://github.com/open-webui/open-webui/commit/ee47c9c833f8889f3abe99d2266c56e8f8d40230) +- 🔣 **Collection name validation.** Vector collection names are now rejected unless they contain only safe characters, preventing malformed names from reaching the vector store or breaking out of a database query expression. [#24982](https://github.com/open-webui/open-webui/pull/24982) +- 🚫 **Unscoped retrieval collections denied by default.** Retrieval requests for collection names that don't correspond to a known file, memory, web-search, or knowledge base are now denied for non-admins by default, with a new "ENABLE_RETRIEVAL_UNSCOPED_COLLECTIONS" setting to restore the previous behavior if needed. [Commit](https://github.com/open-webui/open-webui/commit/c93f071700520a60833b7f9616c292b11f210880) +- 📜 **Prompt history authorization.** Comparing, deleting, and restoring prompt versions now verify the history entry belongs to the prompt you're authorized for, preventing access to or modification of another prompt's version history. [#25056](https://github.com/open-webui/open-webui/pull/25056) +- 🚦 **Code interpreter permission on the legacy path.** The legacy code-execution path now enforces the same permission and capability checks as the current one, so users without the code interpreter permission can no longer trigger code execution through it. [#24724](https://github.com/open-webui/open-webui/pull/24724) +- 🧱 **API key endpoint restriction bypass.** The endpoint allow-list that limits which paths an API key may reach is now matched against the routed request path directly, preventing a crafted request from slipping past the restriction. [#25123](https://github.com/open-webui/open-webui/pull/25123) +- 🚧 **System prompt bypass via request parameter.** The flag that skips a model's configured system prompt can no longer be set by external clients through a request parameter, so admin-configured system prompts can't be bypassed from the API. [#25156](https://github.com/open-webui/open-webui/pull/25156) +- 🚪 **Terminal proxy path traversal.** The terminal proxy now fully decodes request paths before validating them, blocking multi-encoded payloads that could otherwise escape the intended path. [#25157](https://github.com/open-webui/open-webui/pull/25157) +- 🪤 **Cache file path traversal.** The cache file server now requires an exact directory boundary match, closing a gap where a sibling directory whose name began with the cache directory's name could be used to serve files from outside it. [#25086](https://github.com/open-webui/open-webui/pull/25086) +- 🔀 **Ollama backend selection access check.** Requests can no longer target an arbitrary Ollama backend by index; a caller-supplied backend selector is now verified against the backends that actually serve the requested model. [Commit](https://github.com/open-webui/open-webui/commit/7139797be04030b9d1016782f1dbb251c5fe68bb) +- 🔓 **Cross-user file exfiltration via image URLs.** When a chat message references a file by id in an "image_url" field, the server now resolves that file only for its owner, an administrator, or a user with an explicit read grant, preventing other authenticated users from extracting a file's contents by routing it through the model. [#24625](https://github.com/open-webui/open-webui/pull/24625), [Commit](https://github.com/open-webui/open-webui/commit/c75fe8e74b72617c51282cc3ea0a2e8d9cdd9140) +- 📌 **Chat file attachment access checks.** Attaching files to a chat now links only files the caller can read, preventing a user from associating another user's file with their chat to access its contents. [#25054](https://github.com/open-webui/open-webui/pull/25054) +- 🧾 **Model knowledge file ownership checks.** Creating or updating a model now verifies that any knowledge files attached to it are files the editor can access, preventing another user's files from being attached to a model. [#25055](https://github.com/open-webui/open-webui/pull/25055), [Commit](https://github.com/open-webui/open-webui/commit/27fb20c13a4bf8501f7a485abe0654eb5880980d) +- 📅 **Calendar event move authorization.** Updating a calendar event to move it into a different calendar now requires write access on the destination calendar, preventing users from injecting events into calendars they cannot write to. [#24764](https://github.com/open-webui/open-webui/pull/24764) +- 📣 **Channel chat access control.** Generating a response in a channel context now verifies the caller's access to that channel and scopes the included messages, preventing access to channels or messages the user isn't permitted to see. [#24725](https://github.com/open-webui/open-webui/pull/24725) +- 🕸️ **Web loader SSRF gating with Playwright.** When the Playwright-based web loader is in use, page navigations and redirects are now validated the same way as the default loader, closing a gap where the Playwright path could reach internal or otherwise blocked URLs. [#24756](https://github.com/open-webui/open-webui/pull/24756) +- 🛂 **DNS rebinding protection for URL fetches.** The IP address validated for an outbound URL fetch is now the same one used for the actual connection, closing a DNS rebinding window where an attacker-controlled hostname could resolve to a public IP during the safety check and then to a private IP when the connection was opened. [#24759](https://github.com/open-webui/open-webui/pull/24759) +- 🪞 **OAuth profile picture redirect handling.** The OAuth profile picture fetch now follows redirects only when administrators have explicitly allowed it, closing a window where a redirect from an externally validated URL could be used to reach internal addresses. [#24809](https://github.com/open-webui/open-webui/pull/24809) +- 🧼 **Model profile image script injection.** Model profile images are now validated on save and only served inline when they are a known-safe image type, preventing a crafted SVG profile image from running scripts in other users' browsers, while existing legacy images that fail validation are cleared gracefully instead of breaking the model list. [#25060](https://github.com/open-webui/open-webui/pull/25060), [#25173](https://github.com/open-webui/open-webui/pull/25173) +- 🧯 **Diagram rendering script injection.** Mermaid diagrams rendered in chat are now sanitized before display, preventing a crafted diagram from running scripts in the viewer's browser. [#25219](https://github.com/open-webui/open-webui/pull/25219) +- 🔐 **Shared-chat file write protection.** Access to a file through a shared chat now only grants read access, so users who can read a shared chat can no longer modify or delete files attached to it. [#24755](https://github.com/open-webui/open-webui/pull/24755) +- 🔏 **Cross-origin embed prompt control.** When Open WebUI is embedded in an iframe on a different origin, the embedding page can now only drive the chat input or submit prompts if the user has explicitly opted in via the "iframe Sandbox Allow Same Origin" setting, preventing untrusted host pages from triggering confirmation dialogs or controlling the chat. [#24767](https://github.com/open-webui/open-webui/pull/24767), [Commit](https://github.com/open-webui/open-webui/commit/eb3076c1b02d90c2ce6e6d3beb08a37987c740ec) +- 🗂️ **Chat folder ownership checks.** Creating a chat or updating a chat's folder now verifies the referenced folder belongs to the current user, preventing chats from being associated with folders owned by other people. [#24588](https://github.com/open-webui/open-webui/pull/24588) +- 🧩 **Chat recovery from corrupted history.** Chats whose internal message graph was left in a malformed state by a failed regeneration now open and load correctly, with missing roles, parent references, and current-message pointers reconstructed automatically instead of breaking the chat. [#24424](https://github.com/open-webui/open-webui/issues/24424), [#24157](https://github.com/open-webui/open-webui/issues/24157), [#20474](https://github.com/open-webui/open-webui/issues/20474), [#24799](https://github.com/open-webui/open-webui/pull/24799), [Commit](https://github.com/open-webui/open-webui/commit/d310a0777c4c48ec772bdc9a510005d5e91b09c7) +- 📨 **Imported chats with folders appear correctly.** Importing grouped chats no longer leaves them invisible when a referenced folder is missing; such chats now appear in the chat list instead of being silently orphaned. [#24910](https://github.com/open-webui/open-webui/issues/24910), [Commit](https://github.com/open-webui/open-webui/commit/7f7cd210186cb6a67e028c17974eb210fc7ba9fd) +- 🎟️ **MCP tool server sessions stay connected.** OAuth-authenticated MCP tool server sessions are no longer mistakenly refreshed and deleted by the single sign-on session handler, so those connections stay active. [#24618](https://github.com/open-webui/open-webui/issues/24618), [Commit](https://github.com/open-webui/open-webui/commit/c8eb8edca4174ec68fabd071d6b08c0bc07f8117) +- 🤝 **MCP OAuth scope discovery.** The OAuth flow for MCP tool servers now reads the scopes a server advertises through its Protected Resource Metadata, so connecting to servers that declare their own scopes succeeds. [#24730](https://github.com/open-webui/open-webui/issues/24730), [#24690](https://github.com/open-webui/open-webui/pull/24690) +- 🔍 **Web search reliability.** Web search again fetches page content reliably with the default web loader engine, a new "USER_AGENT" environment variable lets administrators set a real browser user-agent so fetches aren't blocked by Cloudflare, Wikipedia, and other bot-detection systems, and the startup script no longer fails to launch when these new environment variables are unset. [#24560](https://github.com/open-webui/open-webui/issues/24560), [#24793](https://github.com/open-webui/open-webui/issues/24793), [#24683](https://github.com/open-webui/open-webui/pull/24683), [Commit](https://github.com/open-webui/open-webui/commit/f60733758272c4532cd032e518c9cd73f648043a) +- 🔥 **Firecrawl web search results.** Web search using Firecrawl now returns results correctly regardless of which response format the Firecrawl version uses. [#24712](https://github.com/open-webui/open-webui/pull/24712) +- 🦅 **Kagi web search.** Web search using Kagi works again after its API endpoint and request method were updated to match Kagi's current API. [#25015](https://github.com/open-webui/open-webui/pull/25015) +- 🔢 **Bracketed numbers in code blocks.** Numbers in square brackets such as "[0]" inside code blocks are no longer stripped out as if they were source citations, so code displays and copies correctly. [#24948](https://github.com/open-webui/open-webui/issues/24948), [Commit](https://github.com/open-webui/open-webui/commit/e90a618f4555cea2c024bb60c1332ca04eed96da) +- 🔌 **API chat completions reliability.** Direct calls to the chat completions API no longer fail with an internal error when no chat session identifier is supplied. [#24553](https://github.com/open-webui/open-webui/issues/24553), [#25235](https://github.com/open-webui/open-webui/issues/25235), [Commit](https://github.com/open-webui/open-webui/commit/bc244fdc90504824b76654880898bf3f6649c299), [Commit](https://github.com/open-webui/open-webui/commit/f16b5c446027eae1bd767617bac2fdf54b24d6fc) +- 🖼️ **ComfyUI image generation and editing.** Generating and editing images via a ComfyUI backend now works again, including when ComfyUI is hosted on a private or internal network where URL validation was previously blocking the admin-configured endpoint. [#24565](https://github.com/open-webui/open-webui/issues/24565), [Commit](https://github.com/open-webui/open-webui/commit/7dcd932ad7cb5feab007737c6e0281def5cd47fc), [Commit](https://github.com/open-webui/open-webui/commit/8aa2a42dc7887512e697ff85d044220945ced40f) +- 🖌️ **Image generation with non-standard response headers.** Image generation now works with backends that return valid JSON without a standard content-type header, instead of rejecting the response. [#24838](https://github.com/open-webui/open-webui/pull/24838) +- 🐘 **Knowledge search on large documents.** Searching knowledge bases on PostgreSQL no longer fails when scanning across documents with very large extracted text content. [#24670](https://github.com/open-webui/open-webui/issues/24670), [Commit](https://github.com/open-webui/open-webui/commit/d74ee34d9128295faa116c919bd1dcca77744975) +- 💬 **Chat title generation.** Automatically generated chat titles now use the model currently selected in the dropdown for the active chat and fall back to the model from the active message branch otherwise, and a clear message is shown if no model is available instead of an unhelpful error. [#24604](https://github.com/open-webui/open-webui/issues/24604), [#24745](https://github.com/open-webui/open-webui/issues/24745), [Commit](https://github.com/open-webui/open-webui/commit/e5c8f8110a88739e011d8ab23e5cb11b4768469f), [Commit](https://github.com/open-webui/open-webui/commit/3c5e7968f0b5130890e17f1f2a2a52297cb145a6) +- 🧮 **Message search and analytics consistency.** Edits, deletions, and branch changes made in a chat are now reflected in message search results and analytics counts instead of leaving stale entries behind. [#25205](https://github.com/open-webui/open-webui/pull/25205), [Commit](https://github.com/open-webui/open-webui/commit/aa06200f789a4c3fc54ea9a141cd347d76cda4c5) +- 🩹 **Graceful handling of in-chat task failures.** When web search query generation, image prompt generation, or a tool call fails or references a missing tool, the chat now falls back or surfaces a clear error instead of breaking partway through the response. [#25038](https://github.com/open-webui/open-webui/issues/25038), [#25144](https://github.com/open-webui/open-webui/issues/25144), [Commit](https://github.com/open-webui/open-webui/commit/b64fd988f02b8a4295193892b24b00bdf635a4dc) +- 🎛️ **Filter changes to message output.** Filter functions that modify a message's structured output after generation now have those changes saved and displayed, instead of being discarded when only the output, not the text content, was changed. [#24884](https://github.com/open-webui/open-webui/pull/24884) +- ⏩ **Titles and tags reflect filtered output.** Outlet filters now run before automatic title, tag, and follow-up generation, so those are based on the final filtered message instead of the unfiltered version. [#24717](https://github.com/open-webui/open-webui/pull/24717) +- 💾 **Action-replaced message content persists.** Message content replaced by an action function through its event emitter is now kept when the chat is saved, instead of reverting to the original after a page reload. [#24585](https://github.com/open-webui/open-webui/issues/24585), [#25485](https://github.com/open-webui/open-webui/pull/25485) +- 🏷️ **Skill mentions in messages.** Mentioning a skill in a message now keeps the skill's name as readable text instead of removing it, and selecting a skill without typing anything no longer causes an error on providers that reject empty messages. [#24929](https://github.com/open-webui/open-webui/issues/24929), [Commit](https://github.com/open-webui/open-webui/commit/01810e32ad51305ca3247e8f83da95f6e6260f0c) +- 🧹 **Usage timer cleanup on send failure.** The background usage-stats timer started during message generation is now always cleared, even when sending a message fails, preventing leaked timers from accumulating over a session. [#25478](https://github.com/open-webui/open-webui/pull/25478) +- 🗑️ **Background tasks stop when a chat is removed.** Deleting or archiving a chat now cancels any in-flight generation or title and tag tasks for it, instead of leaving orphaned background work running. [#25050](https://github.com/open-webui/open-webui/pull/25050), [Commit](https://github.com/open-webui/open-webui/commit/778dba1d6b8dc3962163fa7bf9d802d9a07fba26) +- ⌨️ **Responsive knowledge file search.** Searching for knowledge files in the chat picker and model knowledge selector now matches on file names by default instead of scanning the full extracted text of every document on each keystroke, keeping the search responsive on large deployments, with content search available as an explicit opt-in. [#25082](https://github.com/open-webui/open-webui/issues/25082), [#25119](https://github.com/open-webui/open-webui/pull/25119), [Commit](https://github.com/open-webui/open-webui/commit/591e0aafa1d5e21dcd9fa1279dada2076968b9cb) +- 📥 **Document processing with empty embeddings.** Saving documents to the vector database no longer crashes when an embedding step returns no vectors, allowing the process to continue instead of failing the whole upload. [#25166](https://github.com/open-webui/open-webui/issues/25166) +- 🔤 **Non-UTF-8 text and CSV uploads.** Text and CSV files saved in legacy encodings, including Latin-1, Windows-1252, and Chinese encodings such as GB18030, are now detected and loaded correctly instead of being rejected as binary or failing with an empty-content error. [#25172](https://github.com/open-webui/open-webui/issues/25172), [#24973](https://github.com/open-webui/open-webui/issues/24973), [Commit](https://github.com/open-webui/open-webui/commit/6f0277db52d005420480abb0702d421525d6ea8b), [Commit](https://github.com/open-webui/open-webui/commit/1bbb2b933d4cee70a5102eca4109e77b8625f8fc) +- 🧽 **Null bytes in nested data no longer break saves.** Data containing null bytes nested inside structured fields is now sanitized correctly before being written, preventing database errors that the previous check failed to catch. [#25018](https://github.com/open-webui/open-webui/pull/25018), [Commit](https://github.com/open-webui/open-webui/commit/e3ab4bd212e44c39f439ec4ff5df7c3dbd046895) +- 🧠 **Clear error when no embedding model is configured.** Using knowledge or retrieval features without a loaded embedding model now returns a clear setup error explaining what to configure, instead of failing with a cryptic crash. [Commit](https://github.com/open-webui/open-webui/commit/55ca719bbf76306ed647424c728f730d0bef21f9) +- 🧲 **Memory search quality.** Memory searches now apply the configured embedding query prefix, so retrieval works correctly with embedding models that require one for queries. [#24921](https://github.com/open-webui/open-webui/pull/24921), [Commit](https://github.com/open-webui/open-webui/commit/ce4dca47cb19a6582fd8a550806c89ab297c038d) +- 📚 **Knowledge tool context overflow.** The built-in tool that lists a model's knowledge no longer dumps every file in every knowledge base into the model's context; it now returns summaries by default and paginates file listings only for a requested knowledge base. [#25105](https://github.com/open-webui/open-webui/pull/25105), [Commit](https://github.com/open-webui/open-webui/commit/0e73f7af099e1f9437c55a5c2d16741c97dbd57f) +- ⏳ **Terminal session stability.** The terminal proxy no longer hangs when one direction of the connection closes before the other, so terminal sessions shut down cleanly instead of stalling. [#25464](https://github.com/open-webui/open-webui/issues/25464), [#25479](https://github.com/open-webui/open-webui/pull/25479) +- 🧷 **Tool call continuity with strict providers.** Chats that contain incomplete tool calls or orphaned tool results no longer fail to continue when sent to providers that strictly validate tool pairings, such as Anthropic and AWS Bedrock Converse. [#24758](https://github.com/open-webui/open-webui/issues/24758), [#24940](https://github.com/open-webui/open-webui/issues/24940), [#24798](https://github.com/open-webui/open-webui/pull/24798), [Commit](https://github.com/open-webui/open-webui/commit/cfa6908d579e1f7f202a321289029996130b8411) +- 🛑 **Stream termination for pipe functions.** Streamed responses from pipe functions now always send the standard end-of-stream marker, so chat clients and external integrations reliably detect when a response is complete instead of waiting on streams that already finished. [#24763](https://github.com/open-webui/open-webui/pull/24763) +- 🔊 **Non-blocking text-to-speech transcoding.** Converting text-to-speech audio to MP3 no longer blocks the server's event loop, so other requests stay responsive even while a TTS response is being transcoded. [#24876](https://github.com/open-webui/open-webui/pull/24876) +- 🎚️ **Default text-to-speech voice.** Text-to-speech requests now honor the voice specified in the request and fall back to the configured default only when none is given, instead of always using the admin default or failing. [#15143](https://github.com/open-webui/open-webui/issues/15143), [#25035](https://github.com/open-webui/open-webui/issues/25035), [Commit](https://github.com/open-webui/open-webui/commit/f16b5c446027eae1bd767617bac2fdf54b24d6fc), [Commit](https://github.com/open-webui/open-webui/commit/750604a11d4adcb5ae568b9fc93010031ad394f9) +- 🪝 **Reliable knowledge base file linking.** Files uploaded to a knowledge collection are now linked on the server as part of the upload itself, so they remain attached to the collection even if you navigate away or close the page before processing finishes. [#24807](https://github.com/open-webui/open-webui/issues/24807), [Commit](https://github.com/open-webui/open-webui/commit/d0b17f056911ec73df2b686a0d92bb789391db27) +- ☁️ **Azure connections on custom hostnames.** Connections marked as the Azure provider now use the Azure code path even when the endpoint does not contain "azure" in its hostname, fixing custom Azure deployments served from non-standard domains. [#24882](https://github.com/open-webui/open-webui/pull/24882), [Commit](https://github.com/open-webui/open-webui/commit/c8f851bd2de3d127f1e818fc116c27174f96d3f1) +- 🗓️ **Clearing calendar event fields.** Removing the description or location from a calendar event now saves correctly instead of silently keeping the previous value. [#25026](https://github.com/open-webui/open-webui/issues/25026), [Commit](https://github.com/open-webui/open-webui/commit/91810f1c4e93d4f559bdf61cd085cadc288a732d), [Commit](https://github.com/open-webui/open-webui/commit/78b1637a035d71099262412e5dee3e4d65c7fb2f) +- 💭 **Advanced parameter settings.** Custom reasoning tags and custom model parameters are now saved correctly instead of being dropped, and the presence penalty and repeat penalty no longer save the frequency penalty's value instead of their own. [#25183](https://github.com/open-webui/open-webui/pull/25183), [#25200](https://github.com/open-webui/open-webui/pull/25200), [#25204](https://github.com/open-webui/open-webui/pull/25204) +- 📏 **Long username display.** Long usernames no longer overflow their containers in the admin user list, user modals, and sidebar. [#25185](https://github.com/open-webui/open-webui/pull/25185) +- 🎯 **All skills selectable in the model editor.** The model editor's skills selector now lists every skill you have access to, with a search box for large lists, instead of showing only the first 30 with no way to reach the rest. [#24873](https://github.com/open-webui/open-webui/issues/24873), [Commit](https://github.com/open-webui/open-webui/commit/936d5f2676dfbd2ba763b30af33a8557dcda9b05) +- 🔔 **Accurate knowledge upload feedback.** Dragging files into a knowledge base no longer shows an upload notification before the upload has actually been processed. [#25484](https://github.com/open-webui/open-webui/pull/25484) +- ♿ **High-contrast timestamp readability.** The user message timestamp now uses the correct colors in high-contrast mode instead of inverted ones, keeping it readable. [#25461](https://github.com/open-webui/open-webui/pull/25461) +- ♿ **Keyboard and screen reader access to menus.** The integrations, more-options, and user menus are now real buttons with labels and keyboard support, so they can be opened with the keyboard and announced by screen readers. [Commit](https://github.com/open-webui/open-webui/commit/346dab3d8f909fc321a49ea2be633ea5c4c4a349) +- 🖱️ **Focus-loss handling in editors.** Workspace and admin editors for models, tools, functions, and skills again respond correctly when the browser window loses focus, after the wrong event name was being listened for. [#25459](https://github.com/open-webui/open-webui/pull/25459) +- 🛟 **Resilience to corrupted local storage.** Corrupted data in the browser's local storage no longer crashes the interface; affected settings and dismissed-banner state now fall back to safe defaults. [#25481](https://github.com/open-webui/open-webui/pull/25481) +- 📶 **Quieter reconnection notifications.** Brief connection interruptions, such as backgrounding a mobile tab, no longer flash a "connection lost" warning, and the "reconnected" message only appears if a disconnect was actually shown. [Commit](https://github.com/open-webui/open-webui/commit/77c8c54b1ea07189e21313f9cd401f3b956bb93a) +- 🍎 **Safari PDF handling.** PDF processing now works in Safari, which doesn't support the stream iteration the previous code relied on. [#25151](https://github.com/open-webui/open-webui/issues/25151), [#25473](https://github.com/open-webui/open-webui/pull/25473) +- 🎙️ **Voice mode mute shortcut listing.** The keyboard shortcut for muting voice mode now appears in the keyboard shortcuts help modal. [#25193](https://github.com/open-webui/open-webui/pull/25193) +- 📎 **Document attachments in channel model replies.** Tagging a model in a channel thread now forwards uploaded non-image documents such as PDFs and DOCX files into the model's context, so document summarization and comparison workflows that already worked in direct chat now work in channels too. [#24896](https://github.com/open-webui/open-webui/issues/24896), [#24898](https://github.com/open-webui/open-webui/pull/24898), [Commit](https://github.com/open-webui/open-webui/commit/7e9d41d664d7065a92ac93606d18e88c45eb36b6) +- 🙈 **Hidden models in channel mentions.** Models marked as hidden no longer appear in the channel message-input model mention selector, matching how hidden models are excluded elsewhere in the interface. [#24892](https://github.com/open-webui/open-webui/pull/24892) +- 🧵 **Channel thread and pinned message stability.** Opening a channel thread or the pinned messages view no longer fails to render when a message or its data is missing. [#25209](https://github.com/open-webui/open-webui/pull/25209) +- 📺 **YouTube short link transcripts.** Pasting a "youtu.be" short link into a chat now loads the video transcript correctly instead of failing with an empty-content error. [#24856](https://github.com/open-webui/open-webui/issues/24856), [Commit](https://github.com/open-webui/open-webui/commit/1e36a206008c3abce5ccdc98d5750e30a7345b98) +- 🙉 **Hidden models in default-model and automation pickers.** The admin pickers for default models and default pinned models, and the automation model dropdown, now filter out hidden models, consistent with how hidden models are treated elsewhere. [#24869](https://github.com/open-webui/open-webui/issues/24869), [Commit](https://github.com/open-webui/open-webui/commit/1fa3050f069a72de1daaaa29233b545c4deaea51), [Commit](https://github.com/open-webui/open-webui/commit/4705c2d98812c1189c2ae4960399bc8888d4861c) +- 🔊 **Speech-to-text SSL setting honored.** Speech-to-text requests now respect the "AIOHTTP_CLIENT_SESSION_SSL" setting, so administrators using self-signed certificates or custom SSL configurations can use STT engines that were previously failing TLS verification. [#24568](https://github.com/open-webui/open-webui/issues/24568), [#24857](https://github.com/open-webui/open-webui/pull/24857), [Commit](https://github.com/open-webui/open-webui/commit/2ca91ceeeca6a6a21e5a6ad68ea3ab8c9d9f6deb), [Commit](https://github.com/open-webui/open-webui/commit/94b66b17972e0ad77954df4b81a6bb86a7a6a04b) +- 🔗 **Placeholders in MCP connection headers.** Custom header templates configured on MCP server connections now have their "{{USER_ID}}", "{{USER_NAME}}", "{{USER_EMAIL}}", "{{USER_ROLE}}", "{{CHAT_ID}}", and "{{MESSAGE_ID}}" placeholders interpolated at request time, matching how custom headers already work for direct connections and tool servers. [#24822](https://github.com/open-webui/open-webui/pull/24822) +- 🪟 **Bing search CLI smoke test.** Running the Bing web-search module from the command line for a quick connectivity check no longer raises an error about missing arguments. [#24765](https://github.com/open-webui/open-webui/issues/24765), [#24768](https://github.com/open-webui/open-webui/pull/24768) +- 🩺 **Database health check recovery.** After a transient database connection error, the health check endpoint now recovers automatically instead of staying permanently broken on the affected worker. [Commit](https://github.com/open-webui/open-webui/commit/0b81520e072bb4ed15532b8e153b43dd3243feaf) +- 🥾 **Startup on non-Unicode consoles.** Open WebUI no longer crashes at startup when the console can't encode the banner's box-drawing characters, such as on Windows or with redirected or headless output, falling back to a plain-text banner instead. [#24965](https://github.com/open-webui/open-webui/issues/24965), [#25482](https://github.com/open-webui/open-webui/pull/25482) +- 🆕 **First admin signup after a reset.** Creating the first administrator account is no longer blocked by a previously stored signup setting, so a fresh or reset instance can always be bootstrapped. [#24821](https://github.com/open-webui/open-webui/pull/24821) +- 🪵 **JSON exception logging.** With JSON log formatting enabled, exceptions are now recorded correctly with a structured type, message, and stacktrace instead of being dropped, and a logging failure can no longer crash the application. [#25135](https://github.com/open-webui/open-webui/issues/25135), [Commit](https://github.com/open-webui/open-webui/commit/79bf3d28d88e78b0136ef3c3c9f8e7bb85d3cea9) +- 🧭 **Workspace skills permission.** Users granted only the "workspace.skills" permission can now see the workspace entry in the sidebar and are correctly routed to the skills page from the workspace index. [#24729](https://github.com/open-webui/open-webui/pull/24729) +- 🔁 **Resilient database migrations.** Database migrations now skip tables, indexes, and columns that already exist and add missing primary keys to legacy tables, so upgrades succeed even when parts of the schema were manually or partially created beforehand. [Commit](https://github.com/open-webui/open-webui/commit/81f611fb73c726cfcfc20ee57a926a543f07e95f), [Commit](https://github.com/open-webui/open-webui/commit/f0e88dadc8502ea05b1a00f3155bee7d1cf32249), [Commit](https://github.com/open-webui/open-webui/commit/bd9f82d5a681ee94bde44325033447500a0c76bf), [Commit](https://github.com/open-webui/open-webui/commit/459b1c3fda2ec3579fbd2ab408d0fdeb07c96b99), [Commit](https://github.com/open-webui/open-webui/commit/6df09a4039d181f4e2d41324e93cd36c6fb27dfd), [Commit](https://github.com/open-webui/open-webui/commit/95840e307a66429168775de389b329487a4311c4), [Commit](https://github.com/open-webui/open-webui/commit/6b1df94bf933af92f5c7d093a2d92e2e50d6fdd0), [Commit](https://github.com/open-webui/open-webui/commit/98d3b2308564e2112290773ea240b90419ebb48d), [Commit](https://github.com/open-webui/open-webui/commit/1b9d22e324181b96511a15cbacc40fdbb439ad79), [Commit](https://github.com/open-webui/open-webui/commit/dc0f8ae6f2372b6e5dd42f3520813b09c54146c0), [Commit](https://github.com/open-webui/open-webui/commit/ee3b14233a642ff1bc38aef03a2418afcf5d6c1d), [Commit](https://github.com/open-webui/open-webui/commit/1004dad2749bcc369d511315a808d4bb5277854c), [Commit](https://github.com/open-webui/open-webui/commit/db2b3d7fd86cc7d76424671ead3c62a3f6302fe7), [Commit](https://github.com/open-webui/open-webui/commit/2e1b671e8db49f47d69fd59ece2b58e109ec8b84), [Commit](https://github.com/open-webui/open-webui/commit/9a8969ca93f8c9109d956518a085be3e2afacc07), [Commit](https://github.com/open-webui/open-webui/commit/9717ada92fdb3761a217d309f322ee9fbe418d0d), [Commit](https://github.com/open-webui/open-webui/commit/d7cfc1e46a8f3e5c8f6758c12ef641f41fb51a39), [Commit](https://github.com/open-webui/open-webui/commit/9263b7568eaa83f43e4a118c98490c4f7aaba570), [Commit](https://github.com/open-webui/open-webui/commit/73d2065227e651cf90a2cfade721516815743ab4), [#24722](https://github.com/open-webui/open-webui/pull/24722) + +### Changed + +- ⚠️ **Database Migrations**: This release includes database schema changes; we strongly recommend backing up your database and all associated data before upgrading in production environments. If you are running a multi-worker, multi-server, or load-balanced deployment, all instances must be updated simultaneously, rolling updates are not supported and will cause application failures due to schema incompatibility. +- ⚙️ **Tool-call iteration cap renamed and raised.** The environment variable that limits how many tool calls a single chat response may make is now "CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS", with its default raised from 30 to 256 and a new "-1" value for unlimited; the previous "CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES" name continues to work as a fallback, and chats that hit the cap now show a clear error in-chat instead of stopping silently. [#24918](https://github.com/open-webui/open-webui/pull/24918), [Commit](https://github.com/open-webui/open-webui/commit/2b99945d2726bdf5aed7b1712f9e3b7b622671df) +- 🔐 **Reduced public "/api/config" exposure.** The "/api/config" response no longer includes several feature flags ("enable_api_keys", "enable_password_change_form", "enable_version_update_check", "enable_public_active_users_count", "enable_easter_eggs") for unauthenticated callers, reducing information disclosure to anonymous visitors. [Commit](https://github.com/open-webui/open-webui/commit/245e0ee029e9e10617f62953a9e6f67dd00ecf81), [Commit](https://github.com/open-webui/open-webui/commit/ae06e199d5d3f65296a978cc35079bdacba596d2) +- 🔑 **"WEBUI_SECRET_KEY" is now a hard requirement even for unsupported deployments.** Deployments that start the backend in an explicitly unsupported way (such as invoking uvicorn directly) without setting "WEBUI_SECRET_KEY" will now refuse to start instead of falling back to an empty key; the supported start methods (start.sh, start_windows.bat, and "open-webui serve") still set or auto-generate it automatically, so standard deployments are unaffected. Direct Uvicorn startup is not supported. [#25218](https://github.com/open-webui/open-webui/pull/25218) + ## [0.9.5] - 2026-05-09 ### Added diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index 096d5045dd..1a68a4c273 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -199,9 +199,7 @@ if frontend_loader.exists(): logging.error(f'An error occurred: {e}') -#################################### -# STORAGE PROVIDER -#################################### +# --- Storage Provider --- STORAGE_PROVIDER = os.getenv('STORAGE_PROVIDER', 'local') # defaults to local, s3 STORAGE_LOCAL_CACHE = os.getenv('STORAGE_LOCAL_CACHE', 'true').lower() == 'true' @@ -948,6 +946,15 @@ log.info(f'VECTOR_DB: {VECTOR_DB}') S3_VECTOR_BUCKET_NAME = os.getenv('S3_VECTOR_BUCKET_NAME', None) S3_VECTOR_REGION = os.getenv('S3_VECTOR_REGION', None) +# Valkey Vector Store +VALKEY_URL = os.getenv('VALKEY_URL', '') +VALKEY_COLLECTION_PREFIX = os.getenv('VALKEY_COLLECTION_PREFIX', 'open_webui') +VALKEY_INDEX_TYPE = os.getenv('VALKEY_INDEX_TYPE', 'HNSW').upper() +VALKEY_DISTANCE_METRIC = os.getenv('VALKEY_DISTANCE_METRIC', 'COSINE').upper() +VALKEY_HNSW_M = int(os.getenv('VALKEY_HNSW_M', '16')) +VALKEY_HNSW_EF_CONSTRUCTION = int(os.getenv('VALKEY_HNSW_EF_CONSTRUCTION', '200')) +VALKEY_HNSW_EF_RUNTIME = int(os.getenv('VALKEY_HNSW_EF_RUNTIME', '10')) + #################################### # Information Retrieval (RAG) #################################### @@ -1111,6 +1118,12 @@ MINERU_PARAMS = ConfigVar( mineru_params, ) +MINERU_FILE_EXTENSIONS = ConfigVar( + 'MINERU_FILE_EXTENSIONS', + 'rag.mineru_file_extensions', + [ext.strip() for ext in os.getenv('MINERU_FILE_EXTENSIONS', 'pdf').split(',') if ext.strip()], +) + EXTERNAL_DOCUMENT_LOADER_URL = ConfigVar( 'EXTERNAL_DOCUMENT_LOADER_URL', 'rag.external_document_loader_url', @@ -1914,6 +1927,24 @@ YOUCOM_API_KEY = ConfigVar( os.getenv('YOUCOM_API_KEY', ''), ) +LINKUP_API_KEY = ConfigVar( + 'LINKUP_API_KEY', + 'rag.web.search.linkup_api_key', + os.getenv('LINKUP_API_KEY', ''), +) + +linkup_search_params = os.getenv('LINKUP_SEARCH_PARAMS', '') +try: + linkup_search_params = json.loads(linkup_search_params) +except json.JSONDecodeError: + linkup_search_params = {} + +LINKUP_SEARCH_PARAMS = ConfigVar( + 'LINKUP_SEARCH_PARAMS', + 'rag.web.search.linkup_search_params', + linkup_search_params, +) + #################################### # Images #################################### @@ -3430,6 +3461,12 @@ ENABLE_OAUTH_SIGNUP = ConfigVar( os.getenv('ENABLE_OAUTH_SIGNUP', 'False').lower() == 'true', ) +OAUTH_AUTO_REDIRECT = ConfigVar( + 'OAUTH_AUTO_REDIRECT', + 'oauth.auto_redirect', + os.getenv('OAUTH_AUTO_REDIRECT', 'False').lower() == 'true', +) + OAUTH_REFRESH_TOKEN_INCLUDE_SCOPE = ConfigVar( 'OAUTH_REFRESH_TOKEN_INCLUDE_SCOPE', 'oauth.refresh_token_include_scope', diff --git a/backend/open_webui/env.py b/backend/open_webui/env.py index 20d59ca804..2f6b4ed632 100644 --- a/backend/open_webui/env.py +++ b/backend/open_webui/env.py @@ -16,8 +16,6 @@ import markdown from bs4 import BeautifulSoup from cryptography.hazmat.primitives import serialization -from open_webui.constants import ERROR_MESSAGES - #################################### # Load .env file #################################### @@ -547,6 +545,15 @@ else: except Exception: AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER = AIOHTTP_CLIENT_TIMEOUT +# Timeout (in seconds) for the MCP session.initialize() handshake. +# The handshake performs a list-tools round-trip and can take tens of +# seconds on cold-start servers or servers exposing many tools. +MCP_INITIALIZE_TIMEOUT = os.getenv('MCP_INITIALIZE_TIMEOUT', '10') +try: + MCP_INITIALIZE_TIMEOUT = int(MCP_INITIALIZE_TIMEOUT) +except (ValueError, TypeError): + MCP_INITIALIZE_TIMEOUT = 10 + #################################### # AIOHTTP Connection Pool @@ -603,9 +610,10 @@ ENABLE_SIGNUP_PASSWORD_CONFIRMATION = os.getenv('ENABLE_SIGNUP_PASSWORD_CONFIRMA #################################### # WEBUI_JWT_SECRET_KEY is deprecated; use WEBUI_SECRET_KEY instead. +# No hardcoded fallback by design: the supported start scripts set/auto-generate it; unset is rejected below. WEBUI_SECRET_KEY = os.getenv( 'WEBUI_SECRET_KEY', - os.getenv('WEBUI_JWT_SECRET_KEY', 't0p-s3cr3t'), + os.getenv('WEBUI_JWT_SECRET_KEY', ''), ) WEBUI_SESSION_COOKIE_SAME_SITE = os.getenv('WEBUI_SESSION_COOKIE_SAME_SITE', 'lax') @@ -620,7 +628,14 @@ WEBUI_AUTH_COOKIE_SECURE = ( ) if WEBUI_AUTH and WEBUI_SECRET_KEY == '': - raise ValueError(ERROR_MESSAGES.ENV_VAR_NOT_FOUND) + raise SystemExit( + 'WEBUI_SECRET_KEY is not set. It is a hard requirement when authentication is enabled.\n' + 'The supported start methods set or auto-generate it for you: use start.sh (Linux/macOS), ' + 'start_windows.bat (Windows), or `open-webui serve`.\n' + 'If you start the backend another way (e.g. invoking uvicorn directly, which is unsupported), ' + 'you must set WEBUI_SECRET_KEY yourself to a long random value.\n' + 'See https://docs.openwebui.com/reference/env-configuration#webui_secret_key' + ) ENABLE_COMPRESSION_MIDDLEWARE = os.getenv('ENABLE_COMPRESSION_MIDDLEWARE', 'True').lower() == 'true' @@ -664,6 +679,13 @@ PASSWORD_VALIDATION_HINT = os.getenv('PASSWORD_VALIDATION_HINT', '') BYPASS_MODEL_ACCESS_CONTROL = os.getenv('BYPASS_MODEL_ACCESS_CONTROL', 'False').lower() == 'true' +BYPASS_RETRIEVAL_ACCESS_CONTROL = os.getenv('BYPASS_RETRIEVAL_ACCESS_CONTROL', 'False').lower() == 'true' + +# When True, collection names that do not match any known file-*, user-memory-*, +# web-search-*, or knowledge-base collection are allowed through access control +# for non-admin users. When False (default), unknown collection names are +# denied — closing the legacy unscoped namespace. +ENABLE_RETRIEVAL_UNSCOPED_COLLECTIONS = os.getenv('ENABLE_RETRIEVAL_UNSCOPED_COLLECTIONS', 'False').lower() == 'true' # When enabled, skips pydub-based preprocessing (format conversion, compression, # and chunked splitting) before sending files to processing engines. Useful when @@ -773,6 +795,11 @@ PROFILE_IMAGE_ALLOWED_MIME_TYPES = frozenset( if t.strip() ) +# Max stored length (bytes) of a data:image profile URI; bounds Postgres/Redis +# bloat from inline avatars and model icons. Unset (default) disables the cap. +_profile_image_max_data_uri_size = os.getenv('PROFILE_IMAGE_MAX_DATA_URI_SIZE', '').strip() +PROFILE_IMAGE_MAX_DATA_URI_SIZE = int(_profile_image_max_data_uri_size) if _profile_image_max_data_uri_size else None + #################################### # Forward Headers #################################### @@ -786,6 +813,17 @@ FORWARD_USER_INFO_HEADER_USER_ROLE = os.getenv('FORWARD_USER_INFO_HEADER_USER_RO FORWARD_SESSION_INFO_HEADER_MESSAGE_ID = os.getenv('FORWARD_SESSION_INFO_HEADER_MESSAGE_ID', 'X-OpenWebUI-Message-Id') FORWARD_SESSION_INFO_HEADER_CHAT_ID = os.getenv('FORWARD_SESSION_INFO_HEADER_CHAT_ID', 'X-OpenWebUI-Chat-Id') +# If set while ENABLE_FORWARD_USER_INFO_HEADERS is True, send one signed HS256 JWT +# (FORWARD_USER_INFO_HEADER_JWT) instead of separate X-OpenWebUI-User-* headers. +FORWARD_USER_INFO_HEADER_JWT_SECRET = (os.environ.get('FORWARD_USER_INFO_HEADER_JWT_SECRET') or '').strip() or None +FORWARD_USER_INFO_HEADER_JWT = os.environ.get('FORWARD_USER_INFO_HEADER_JWT', 'X-OpenWebUI-User-Jwt') +try: + FORWARD_USER_INFO_HEADER_JWT_EXPIRES_SECONDS = int( + os.environ.get('FORWARD_USER_INFO_HEADER_JWT_EXPIRES_SECONDS', '300') + ) +except ValueError: + FORWARD_USER_INFO_HEADER_JWT_EXPIRES_SECONDS = 300 + #################################### # Progressive Web App #################################### @@ -845,15 +883,24 @@ else: CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE = 1 -CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = os.getenv('CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES', '30') +# Maximum tool-call iterations per chat response. Set to -1 for unlimited. +# The old CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES name is accepted as a fallback. +CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = os.getenv( + 'CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS', + os.getenv('CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES', '256'), +) -if CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES == '': - CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = 30 +if CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS == '': + CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 256 else: try: - CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = int(CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES) + CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = int(CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS) except Exception: - CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = 30 + CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 256 + +# -1 means unlimited (no cap). +if CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS == -1: + CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = None # WARNING: Experimental. Only enable if your upstream Responses API endpoint diff --git a/backend/open_webui/functions.py b/backend/open_webui/functions.py index 7c50ca3d2d..4a82cf7f26 100644 --- a/backend/open_webui/functions.py +++ b/backend/open_webui/functions.py @@ -318,11 +318,10 @@ async def generate_function_chat_completion(request, form_data, user, models: di async for line in res: yield process_line(form_data, line) - if isinstance(res, str) or isinstance(res, Generator): - finish_message = openai_chat_chunk_message_template(form_data['model'], '') - finish_message['choices'][0]['finish_reason'] = 'stop' - yield f'data: {json.dumps(finish_message)}\n\n' - yield 'data: [DONE]' + finish_message = openai_chat_chunk_message_template(form_data['model'], '') + finish_message['choices'][0]['finish_reason'] = 'stop' + yield f'data: {json.dumps(finish_message)}\n\n' + yield 'data: [DONE]' return StreamingResponse(stream_content(), media_type='text/event-stream') else: diff --git a/backend/open_webui/internal/config.py b/backend/open_webui/internal/config.py index 294144ae76..46f5b1b67d 100644 --- a/backend/open_webui/internal/config.py +++ b/backend/open_webui/internal/config.py @@ -193,6 +193,13 @@ class AppConfig: super().__setattr__('_entries', {}) super().__setattr__('_key_prefix', redis_key_prefix) + # If sentinels weren't explicitly provided, read from env. + if redis_sentinels is None: + from open_webui.env import REDIS_SENTINEL_HOSTS, REDIS_SENTINEL_PORT + from open_webui.utils.redis import get_sentinels_from_env + + redis_sentinels = get_sentinels_from_env(REDIS_SENTINEL_HOSTS, REDIS_SENTINEL_PORT) + rc: Union[redis.Redis, redis.cluster.RedisCluster, None] = None if redis_url: rc = get_redis_connection(redis_url, redis_sentinels or [], redis_cluster, decode_responses=True) diff --git a/backend/open_webui/internal/db.py b/backend/open_webui/internal/db.py index 69050160a8..d3402b0310 100644 --- a/backend/open_webui/internal/db.py +++ b/backend/open_webui/internal/db.py @@ -117,26 +117,25 @@ extract_ssl_mode_from_url = extract_ssl_params_from_url reattach_ssl_mode_to_url = reattach_ssl_params_to_url -class JSONField(types.TypeDecorator): - impl = types.Text +class JSONField(types.TypeDecorator): # TEXT-backed JSON storage + """Store arbitrary Python objects as JSON-encoded TEXT. + + Used instead of native JSON columns for portability across SQLite and + PostgreSQL. Values are serialized with ``json.dumps`` on write and + deserialized with ``json.loads`` on read. + """ + + impl = types.UnicodeText cache_ok = True def process_bind_param(self, value: _T | None, dialect: Dialect) -> Any: - return json.dumps(value) + return json.dumps(value) if value is not None else None def process_result_value(self, value: _T | None, dialect: Dialect) -> Any: - if value is not None: - return json.loads(value) + return json.loads(value) if value is not None else None - def copy(self, **kw: Any) -> Self: - return JSONField(self.impl.length) - - def db_value(self, value): - return json.dumps(value) - - def python_value(self, value): - if value is not None: - return json.loads(value) + def copy(self, **kwargs: Any) -> Self: + return JSONField(length=self.impl.length) # Normalize SSL params from the URL once; the sync engine needs them diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py index 55f3001181..56d904dd80 100644 --- a/backend/open_webui/main.py +++ b/backend/open_webui/main.py @@ -281,6 +281,7 @@ from open_webui.config import ( MINERU_API_MODE, MINERU_API_TIMEOUT, MINERU_API_URL, + MINERU_FILE_EXTENSIONS, MINERU_PARAMS, MISTRAL_OCR_API_BASE_URL, MISTRAL_OCR_API_KEY, @@ -288,6 +289,7 @@ from open_webui.config import ( MOJEEK_SEARCH_API_KEY, OAUTH_ADMIN_ROLES, OAUTH_ALLOWED_ROLES, + OAUTH_AUTO_REDIRECT, OAUTH_EMAIL_CLAIM, OAUTH_PICTURE_CLAIM, OAUTH_PROVIDERS, @@ -452,6 +454,8 @@ from open_webui.config import ( YANDEX_WEB_SEARCH_CONFIG, YANDEX_WEB_SEARCH_URL, YOUCOM_API_KEY, + LINKUP_API_KEY, + LINKUP_SEARCH_PARAMS, YOUTUBE_LOADER_LANGUAGE, YOUTUBE_LOADER_PROXY_URL, AppConfig, @@ -487,10 +491,9 @@ from open_webui.env import ( LICENSE_KEY, LOG_FORMAT, MAX_BODY_LOG_SIZE, + # Redis REDIS_CLUSTER, REDIS_KEY_PREFIX, - REDIS_SENTINEL_HOSTS, - REDIS_SENTINEL_PORT, REDIS_URL, RESET_CONFIG_ON_START, SAFE_MODE, @@ -509,8 +512,11 @@ from open_webui.env import ( WEBUI_SESSION_COOKIE_SECURE, ) from open_webui.internal.db import ScopedSession, engine, get_async_session +from open_webui.models.access_grants import AccessGrants +from open_webui.models.channels import Channels from open_webui.models.chats import ChatForm, Chats from open_webui.models.functions import Functions +from open_webui.models.messages import Messages from open_webui.models.models import Models from open_webui.models.users import UserModel, Users from open_webui.routers import ( @@ -619,7 +625,7 @@ from open_webui.utils.oauth import ( resolve_oauth_client_info, ) from open_webui.utils.plugin import install_tool_and_function_dependencies -from open_webui.utils.redis import get_redis_connection, get_sentinels_from_env +from open_webui.utils.redis import get_redis_client, get_redis_connection from open_webui.utils.security_headers import SecurityHeadersMiddleware from open_webui.utils.session_pool import get_session from open_webui.utils.tools import set_terminal_servers, set_tool_servers @@ -648,7 +654,7 @@ class SPAStaticFiles(StaticFiles): if LOG_FORMAT != 'json': - print(rf""" + banner = rf""" ██████╗ ██████╗ ███████╗███╗ ██╗ ██╗ ██╗███████╗██████╗ ██╗ ██╗██╗ ██╔═══██╗██╔══██╗██╔════╝████╗ ██║ ██║ ██║██╔════╝██╔══██╗██║ ██║██║ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║ ██║ █╗ ██║█████╗ ██████╔╝██║ ██║██║ @@ -660,7 +666,12 @@ if LOG_FORMAT != 'json': v{VERSION} - building the best AI user interface. {f'Commit: {WEBUI_BUILD_HASH}' if WEBUI_BUILD_HASH != 'dev-build' else ''} https://github.com/open-webui/open-webui -""") +""" + try: + print(banner) + except UnicodeEncodeError: + # Stdout can't encode the box-drawing banner (Windows cp1252, redirected/headless stdout); fall back to ASCII. + print(f'Open WebUI v{VERSION} - building the best AI user interface.\nhttps://github.com/open-webui/open-webui') @asynccontextmanager @@ -692,12 +703,7 @@ async def lifespan(app: FastAPI): log.info('Installing external dependencies of functions and tools...') await install_tool_and_function_dependencies() - app.state.redis = get_redis_connection( - redis_url=REDIS_URL, - redis_sentinels=get_sentinels_from_env(REDIS_SENTINEL_HOSTS, REDIS_SENTINEL_PORT), - redis_cluster=REDIS_CLUSTER, - async_mode=True, - ) + app.state.redis = get_redis_client(async_mode=True) if app.state.redis is not None: app.state.redis_task_command_listener = asyncio.create_task(redis_task_command_listener(app)) @@ -804,7 +810,6 @@ app.state.oauth_client_manager = oauth_client_manager app.state.instance_id = None app.state.config = AppConfig( redis_url=REDIS_URL, - redis_sentinels=get_sentinels_from_env(REDIS_SENTINEL_HOSTS, REDIS_SENTINEL_PORT), redis_cluster=REDIS_CLUSTER, redis_key_prefix=REDIS_KEY_PREFIX, ) @@ -905,6 +910,7 @@ app.state.BASE_MODELS = [] app.state.config.WEBUI_URL = WEBUI_URL app.state.config.ENABLE_SIGNUP = ENABLE_SIGNUP app.state.config.ENABLE_LOGIN_FORM = ENABLE_LOGIN_FORM +app.state.config.OAUTH_AUTO_REDIRECT = OAUTH_AUTO_REDIRECT app.state.config.ENABLE_PASSWORD_CHANGE_FORM = ENABLE_PASSWORD_CHANGE_FORM app.state.config.ENABLE_API_KEYS = ENABLE_API_KEYS @@ -1073,6 +1079,7 @@ app.state.config.MINERU_API_URL = MINERU_API_URL app.state.config.MINERU_API_KEY = MINERU_API_KEY app.state.config.MINERU_API_TIMEOUT = MINERU_API_TIMEOUT app.state.config.MINERU_PARAMS = MINERU_PARAMS +app.state.config.MINERU_FILE_EXTENSIONS = MINERU_FILE_EXTENSIONS app.state.config.TEXT_SPLITTER = RAG_TEXT_SPLITTER app.state.config.ENABLE_MARKDOWN_HEADER_TEXT_SPLITTER = ENABLE_MARKDOWN_HEADER_TEXT_SPLITTER @@ -1176,6 +1183,8 @@ app.state.config.YANDEX_WEB_SEARCH_URL = YANDEX_WEB_SEARCH_URL app.state.config.YANDEX_WEB_SEARCH_API_KEY = YANDEX_WEB_SEARCH_API_KEY app.state.config.YANDEX_WEB_SEARCH_CONFIG = YANDEX_WEB_SEARCH_CONFIG app.state.config.YOUCOM_API_KEY = YOUCOM_API_KEY +app.state.config.LINKUP_API_KEY = LINKUP_API_KEY +app.state.config.LINKUP_SEARCH_PARAMS = LINKUP_SEARCH_PARAMS app.state.config.PLAYWRIGHT_WS_URL = PLAYWRIGHT_WS_URL @@ -1809,7 +1818,7 @@ async def chat_completion( metadata = { 'user_id': user.id, - 'chat_id': form_data.pop('chat_id', None), + 'chat_id': form_data.pop('chat_id', None) or '', 'user_message': user_message, 'user_message_id': user_message.get('id') if user_message else None, 'assistant_message_id': form_data.pop('assistant_message_id', None), @@ -1827,12 +1836,9 @@ async def chat_completion( 'stream_delta_chunk_size': stream_delta_chunk_size, 'reasoning_tags': reasoning_tags, 'function_calling': ( - 'native' - if ( - form_data.get('params', {}).get('function_calling') == 'native' - or model_info_params.get('function_calling') == 'native' - ) - else 'default' + form_data.get('params', {}).get('function_calling') + or model_info_params.get('function_calling') + or 'native' ), }, } @@ -1842,6 +1848,44 @@ async def chat_completion( if metadata.get('chat_id') and user: chat_id = metadata['chat_id'] + + # Gate channel: branch — caller needs write access on the channel + # and the supplied message_id must belong to that channel. + if chat_id.startswith('channel:'): + channel_id = chat_id.removeprefix('channel:') + channel = await Channels.get_channel_by_id(channel_id) + if not channel: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=ERROR_MESSAGES.NOT_FOUND, + ) + if user.role != 'admin': + if channel.type in ['group', 'dm']: + if not await Channels.is_user_channel_member(channel.id, user.id): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=ERROR_MESSAGES.DEFAULT(), + ) + else: + if not await AccessGrants.has_access( + user_id=user.id, + resource_type='channel', + resource_id=channel.id, + permission='write', + ): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=ERROR_MESSAGES.DEFAULT(), + ) + target_message_id = list(message_ids.values())[0] if message_ids else None + if target_message_id: + target_message = await Messages.get_message_by_id(target_message_id) + if target_message and target_message.channel_id != channel.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=ERROR_MESSAGES.DEFAULT(), + ) + if not chat_id.startswith('local:') and not chat_id.startswith( 'channel:' ): # temporary/channel chats are not stored @@ -2060,7 +2104,9 @@ async def chat_completion( if metadata.get('chat_id') and metadata.get('message_id'): # Update the chat message with the error try: - if not metadata['chat_id'].startswith('local:') and not metadata['chat_id'].startswith('channel:'): + if not metadata.get('chat_id', '').startswith('local:') and not metadata.get( + 'chat_id', '' + ).startswith('channel:'): await Chats.upsert_message_to_chat_by_id_and_message_id( metadata['chat_id'], metadata['message_id'], @@ -2387,11 +2433,11 @@ async def get_app_config(request: Request): if data is not None and 'id' in data: user = await Users.get_user_by_id(data['id']) - user_count = await Users.get_num_users() onboarding = False - if user is None: - onboarding = user_count == 0 + onboarding = not await Users.has_users() + + user_count = await Users.get_num_users() if app.state.LICENSE_METADATA else None return { **({'onboarding': True} if onboarding else {}), @@ -2399,7 +2445,10 @@ async def get_app_config(request: Request): 'name': app.state.WEBUI_NAME, 'version': VERSION, 'default_locale': str(DEFAULT_LOCALE), - 'oauth': {'providers': {name: config.get('name', name) for name, config in OAUTH_PROVIDERS.items()}}, + 'oauth': { + 'providers': {name: config.get('name', name) for name, config in OAUTH_PROVIDERS.items()}, + 'auto_redirect': app.state.config.OAUTH_AUTO_REDIRECT, + }, 'features': { # --- Public: required by login/signup page pre-auth --- 'auth': WEBUI_AUTH, @@ -2457,7 +2506,7 @@ async def get_app_config(request: Request): 'default_models': app.state.config.DEFAULT_MODELS, 'default_pinned_models': app.state.config.DEFAULT_PINNED_MODELS, 'default_prompt_suggestions': app.state.config.DEFAULT_PROMPT_SUGGESTIONS, - 'user_count': user_count, + **({'user_count': user_count} if user_count is not None else {}), 'code': { 'engine': app.state.config.CODE_EXECUTION_ENGINE, 'interpreter_engine': app.state.config.CODE_INTERPRETER_ENGINE, @@ -2611,9 +2660,7 @@ async def get_current_usage(user=Depends(get_verified_user)): raise HTTPException(status_code=500, detail='Internal Server Error') -############################ -# OAuth Login & Callback -############################ +# --- OAuth Login & Callback --- # Initialize OAuth client manager with any MCP tool servers using OAuth 2.1 @@ -2802,12 +2849,6 @@ async def oauth_login(provider: str, request: Request): return await oauth_manager.handle_login(request, provider) -# OAuth login logic is as follows: -# 1. Attempt to find a user with matching subject ID, tied to the provider -# 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth -# - This is considered insecure in general, as OAuth providers do not always verify email addresses -# 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user -# - Email addresses are considered unique, so we fail registration if the email address is already taken @app.get('/oauth/{provider}/login/callback') @app.get('/oauth/{provider}/callback') # Legacy endpoint async def oauth_login_callback( @@ -2816,6 +2857,15 @@ async def oauth_login_callback( response: Response, db: AsyncSession = Depends(get_async_session), ): + """Handle the OAuth provider callback. + + Resolution order: + 1. Match by subject ID bound to the provider. + 2. If ``OAUTH_MERGE_ACCOUNTS_BY_EMAIL`` is enabled, match by email + (note: some providers do not verify email addresses). + 3. If no match and ``ENABLE_OAUTH_SIGNUP`` is enabled, create a new user + (fails if the email is already registered). + """ return await oauth_manager.handle_callback(request, provider, response, db=db) @@ -2960,11 +3010,14 @@ async def readiness_check(): @app.get('/health/db') -async def healthcheck_with_db(): +async def check_db_health(): + """Verify database connectivity by issuing a lightweight ping.""" await async_db_ping() return {'status': True} +# --- static assets & files --- +# Serve build-time static assets (CSS, JS, images, favicon, etc.) app.mount('/static', StaticFiles(directory=STATIC_DIR), name='static') @@ -2973,9 +3026,17 @@ async def serve_cache_file( path: str, user=Depends(get_verified_user), ): + """Serve cached files (e.g. tool outputs) with path-traversal protection. + + Only ``image/*``, ``audio/*``, and ``video/*`` MIME types are served inline; + everything else gets a ``Content-Disposition: attachment`` header to prevent + XSS from user-generated HTML stored in the cache directory. + """ file_path = os.path.abspath(os.path.join(CACHE_DIR, path)) - # prevent path traversal - if not file_path.startswith(os.path.abspath(CACHE_DIR)): + # trailing os.sep is required: without it, a path resolving to a sibling + # whose name starts with the cache-dir basename (e.g. cache_backup) passes + cache_root = os.path.abspath(CACHE_DIR) + os.sep + if not file_path.startswith(cache_root): raise HTTPException(status_code=404, detail='File not found') if not os.path.isfile(file_path): raise HTTPException(status_code=404, detail='File not found') diff --git a/backend/open_webui/migrations/env.py b/backend/open_webui/migrations/env.py index a9b9dcacb8..6fcd9a64cd 100644 --- a/backend/open_webui/migrations/env.py +++ b/backend/open_webui/migrations/env.py @@ -1,105 +1,84 @@ from __future__ import annotations -"""Alembic environment configuration. - -Configures the migration context for both offline (SQL script generation) -and online (live database connection) modes. Handles SQLCipher URLs, -SSL parameter normalisation, and JSON log formatting. -""" - +# Alembic environment configuration runner. +# Coordinates database migrations in both offline and online execution modes. +import logging.config import logging -from logging.config import fileConfig - -from alembic import context +import alembic.context from open_webui.env import DATABASE_PASSWORD, DATABASE_URL, LOG_FORMAT from open_webui.internal.db import extract_ssl_params_from_url, reattach_ssl_params_to_url from open_webui.models.auths import Auth from open_webui.models.calendar import Calendar, CalendarEvent, CalendarEventAttendee # noqa: F401 from sqlalchemy import create_engine, engine_from_config, pool -# ── Alembic config & logging ───────────────────────────────────────────────── - -config = context.config - -if config.config_file_name is not None: - fileConfig(config.config_file_name, disable_existing_loggers=False) - -# Re-apply JSON formatter after fileConfig replaces handlers. +alembic_config = alembic.context.config +if alembic_config.config_file_name: + logging.config.fileConfig(alembic_config.config_file_name, disable_existing_loggers=False) if LOG_FORMAT == 'json': from open_webui.env import JSONFormatter - for handler in logging.root.handlers: - handler.setFormatter(JSONFormatter()) - -# ── Database URL ───────────────────────────────────────────────────────────── - -target_metadata = Auth.metadata - -DB_URL = DATABASE_URL - -# Normalise SSL query params for psycopg2 (Alembic uses psycopg2 for sync). -_url_no_ssl, _ssl_params = extract_ssl_params_from_url(DB_URL) -if _ssl_params: - DB_URL = reattach_ssl_params_to_url(_url_no_ssl, _ssl_params) - -if DB_URL: - config.set_main_option('sqlalchemy.url', DB_URL.replace('%', '%%')) - - -# ── Migration runners ──────────────────────────────────────────────────────── + for log_handler in logging.root.handlers: + log_handler.setFormatter(JSONFormatter()) +migration_metadata = Auth.metadata +target_db_url = DATABASE_URL +base_url, ssl_query_params = extract_ssl_params_from_url(target_db_url) +if ssl_query_params: + target_db_url = reattach_ssl_params_to_url(base_url, ssl_query_params) +if target_db_url: + alembic_config.set_main_option('sqlalchemy.url', target_db_url.replace('%', '%%')) def run_migrations_offline() -> None: - """Generate SQL script without a live database connection.""" - url = config.get_main_option('sqlalchemy.url') - context.configure( - url=url, - target_metadata=target_metadata, + """Execute Alembic migrations in offline mode (outputs raw SQL DDL).""" + db_connection_url = alembic_config.get_main_option('sqlalchemy.url') + alembic.context.configure( + url=db_connection_url, + target_metadata=migration_metadata, literal_binds=True, dialect_opts={'paramstyle': 'named'}, ) - with context.begin_transaction(): - context.run_migrations() + with alembic.context.begin_transaction(): + alembic.context.run_migrations() -def _build_connectable(): - """Create the appropriate SQLAlchemy engine for the configured DB URL.""" - if DB_URL and DB_URL.startswith('sqlite+sqlcipher://'): - if not DATABASE_PASSWORD or DATABASE_PASSWORD.strip() == '': +def _get_engine_connectable(): + """Build the database engine based on target URL and authentication credentials.""" + if target_db_url and target_db_url.startswith('sqlite+sqlcipher://'): + if not DATABASE_PASSWORD or not DATABASE_PASSWORD.strip(): raise ValueError('DATABASE_PASSWORD is required when using sqlite+sqlcipher:// URLs') + raw_db_path = target_db_url.replace('sqlite+sqlcipher://', '') + if raw_db_path.startswith('/'): + raw_db_path = raw_db_path[1:] - db_path = DB_URL.replace('sqlite+sqlcipher://', '') - if db_path.startswith('/'): - db_path = db_path[1:] - - def _sqlcipher_creator(): + def _sqlite_cipher_creator(): import sqlcipher3 - conn = sqlcipher3.connect(db_path, check_same_thread=False) - conn.execute(f"PRAGMA key = '{DATABASE_PASSWORD}'") - return conn - - return create_engine('sqlite://', creator=_sqlcipher_creator, echo=False) + cipher_conn = sqlcipher3.connect(raw_db_path, check_same_thread=False) + cipher_conn.execute(f"PRAGMA key = '{DATABASE_PASSWORD}'") + return cipher_conn + return create_engine('sqlite://', creator=_sqlite_cipher_creator, echo=False) return engine_from_config( - config.get_section(config.config_ini_section, {}), + alembic_config.get_section(alembic_config.config_ini_section, {}), prefix='sqlalchemy.', poolclass=pool.NullPool, ) def run_migrations_online() -> None: - """Run migrations against a live database connection.""" - connectable = _build_connectable() - with connectable.connect() as connection: - context.configure(connection=connection, target_metadata=target_metadata) - with context.begin_transaction(): - context.run_migrations() + """Execute migrations against a live database connection.""" + live_connectable = _get_engine_connectable() + with live_connectable.connect() as live_connection: + alembic.context.configure( + connection=live_connection, + target_metadata=migration_metadata, + ) + with alembic.context.begin_transaction(): + alembic.context.run_migrations() -# ── Entrypoint ─────────────────────────────────────────────────────────────── - -if context.is_offline_mode(): - run_migrations_offline() -else: - run_migrations_online() +# Alembic execution entrypoint branch +if alembic.context.is_offline_mode(): + run_migrations_offline() # run in offline mode +if not alembic.context.is_offline_mode(): + run_migrations_online() # run in online mode diff --git a/backend/open_webui/migrations/util.py b/backend/open_webui/migrations/util.py index 606bdc9479..1c55faf0e9 100644 --- a/backend/open_webui/migrations/util.py +++ b/backend/open_webui/migrations/util.py @@ -2,10 +2,11 @@ from __future__ import annotations """Alembic migration utilities.""" -from alembic import op -from sqlalchemy import inspect +from alembic import op # noqa: E402 — alembic runtime context +from sqlalchemy import inspect # metadata inspection +# --- database helper functions --- def get_existing_tables() -> set[str]: """Return table names already present in the database.""" conn = op.get_bind() diff --git a/backend/open_webui/migrations/versions/3781e22d8b01_update_message_table.py b/backend/open_webui/migrations/versions/3781e22d8b01_update_message_table.py index aaebaacb49..7dd3ed33cb 100644 --- a/backend/open_webui/migrations/versions/3781e22d8b01_update_message_table.py +++ b/backend/open_webui/migrations/versions/3781e22d8b01_update_message_table.py @@ -53,7 +53,9 @@ def upgrade(): if 'channel_member' not in existing_tables: op.create_table( 'channel_member', - sa.Column('id', sa.Text(), nullable=False, primary_key=True, unique=True), # Record ID for the membership row + sa.Column( + 'id', sa.Text(), nullable=False, primary_key=True, unique=True + ), # Record ID for the membership row sa.Column('channel_id', sa.Text(), nullable=False), # Associated channel sa.Column('user_id', sa.Text(), nullable=False), # Associated user sa.Column('created_at', sa.BigInteger(), nullable=True), # Timestamp of when the user joined the channel diff --git a/backend/open_webui/migrations/versions/38d63c18f30f_add_oauth_session_table.py b/backend/open_webui/migrations/versions/38d63c18f30f_add_oauth_session_table.py index b212c7f43a..ff6fe65118 100644 --- a/backend/open_webui/migrations/versions/38d63c18f30f_add_oauth_session_table.py +++ b/backend/open_webui/migrations/versions/38d63c18f30f_add_oauth_session_table.py @@ -42,9 +42,9 @@ def upgrade() -> None: # Create indexes (idempotent — no-ops when table was just created # with the columns above, and safe to call if indexes already exist). - existing_indexes = { - idx['name'] for idx in inspector.get_indexes('oauth_session') - } if 'oauth_session' in existing_tables else set() + existing_indexes = ( + {idx['name'] for idx in inspector.get_indexes('oauth_session')} if 'oauth_session' in existing_tables else set() + ) if 'idx_oauth_session_user_id' not in existing_indexes: op.create_index('idx_oauth_session_user_id', 'oauth_session', ['user_id']) diff --git a/backend/open_webui/migrations/versions/3c9b0ca343fd_add_knowledge_directory_table.py b/backend/open_webui/migrations/versions/3c9b0ca343fd_add_knowledge_directory_table.py index ab2b0c9498..90b1bb0085 100644 --- a/backend/open_webui/migrations/versions/3c9b0ca343fd_add_knowledge_directory_table.py +++ b/backend/open_webui/migrations/versions/3c9b0ca343fd_add_knowledge_directory_table.py @@ -5,6 +5,7 @@ Revises: a0b1c2d3e4f5 Create Date: 2026-05-13 21:58:40.832482 """ + from typing import Sequence, Union from alembic import op @@ -36,7 +37,9 @@ def upgrade() -> None: sa.ForeignKeyConstraint(['knowledge_id'], ['knowledge.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['parent_id'], ['knowledge_directory.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), - sa.UniqueConstraint('knowledge_id', 'parent_id', 'name', name='uq_knowledge_directory_knowledge_parent_name'), + sa.UniqueConstraint( + 'knowledge_id', 'parent_id', 'name', name='uq_knowledge_directory_knowledge_parent_name' + ), ) op.create_index('ix_knowledge_directory_knowledge_id', 'knowledge_directory', ['knowledge_id']) op.create_index('ix_knowledge_directory_parent_id', 'knowledge_directory', ['parent_id']) diff --git a/backend/open_webui/migrations/versions/461111b60977_add_missing_primary_keys_to_legacy_.py b/backend/open_webui/migrations/versions/461111b60977_add_missing_primary_keys_to_legacy_.py index 67b737c530..1e5901e275 100644 --- a/backend/open_webui/migrations/versions/461111b60977_add_missing_primary_keys_to_legacy_.py +++ b/backend/open_webui/migrations/versions/461111b60977_add_missing_primary_keys_to_legacy_.py @@ -5,6 +5,7 @@ Revises: 3c9b0ca343fd Create Date: 2026-05-14 04:38:14.000000 """ + from typing import Sequence, Union import sqlalchemy as sa @@ -21,9 +22,18 @@ depends_on: Union[str, Sequence[str], None] = None # already have correct PKs from 7e5b5dc7342b_init.py. # 'tag' uses a composite PK since the same tag name can exist for multiple users. LEGACY_TABLES = { - 'auth': ['id'], 'chat': ['id'], 'chatidtag': ['id'], 'document': ['id'], - 'file': ['id'], 'function': ['id'], 'memory': ['id'], 'model': ['id'], - 'prompt': ['id'], 'tag': ['id', 'user_id'], 'tool': ['id'], 'user': ['id'], + 'auth': ['id'], + 'chat': ['id'], + 'chatidtag': ['id'], + 'document': ['id'], + 'file': ['id'], + 'function': ['id'], + 'memory': ['id'], + 'model': ['id'], + 'prompt': ['id'], + 'tag': ['id', 'user_id'], + 'tool': ['id'], + 'user': ['id'], } diff --git a/backend/open_webui/migrations/versions/4de81c2a3af1_add_pinned_note_table.py b/backend/open_webui/migrations/versions/4de81c2a3af1_add_pinned_note_table.py index a7b019f35a..1ec11a0419 100644 --- a/backend/open_webui/migrations/versions/4de81c2a3af1_add_pinned_note_table.py +++ b/backend/open_webui/migrations/versions/4de81c2a3af1_add_pinned_note_table.py @@ -52,13 +52,18 @@ def upgrade() -> None: column('created_at', sa.BigInteger), ) - notes = conn.execute(select(note_table.c.id, note_table.c.user_id).where(note_table.c.is_pinned == True)).fetchall() + notes = conn.execute( + select(note_table.c.id, note_table.c.user_id).where(note_table.c.is_pinned == True) + ).fetchall() if notes: now = int(time.time_ns()) conn.execute( insert(pinned_note_table), - [{'id': str(uuid.uuid4()), 'user_id': note[1], 'note_id': note[0], 'created_at': now} for note in notes], + [ + {'id': str(uuid.uuid4()), 'user_id': note[1], 'note_id': note[0], 'created_at': now} + for note in notes + ], ) with op.batch_alter_table('note', schema=None) as batch_op: diff --git a/backend/open_webui/migrations/versions/56359461a091_add_calendar_tables.py b/backend/open_webui/migrations/versions/56359461a091_add_calendar_tables.py index 571390a6fa..4796233604 100644 --- a/backend/open_webui/migrations/versions/56359461a091_add_calendar_tables.py +++ b/backend/open_webui/migrations/versions/56359461a091_add_calendar_tables.py @@ -95,7 +95,9 @@ def upgrade() -> None: inspector.clear_cache() if 'calendar_event_attendee' in inspector.get_table_names(): if not _index_exists(inspector, 'ix_calendar_event_attendee_user', 'calendar_event_attendee'): - op.create_index('ix_calendar_event_attendee_user', 'calendar_event_attendee', ['user_id', 'status'], unique=False) + op.create_index( + 'ix_calendar_event_attendee_user', 'calendar_event_attendee', ['user_id', 'status'], unique=False + ) def downgrade() -> None: diff --git a/backend/open_webui/migrations/versions/6283dc0e4d8d_add_channel_file_table.py b/backend/open_webui/migrations/versions/6283dc0e4d8d_add_channel_file_table.py index 7f2913bd5e..aa1e52062b 100644 --- a/backend/open_webui/migrations/versions/6283dc0e4d8d_add_channel_file_table.py +++ b/backend/open_webui/migrations/versions/6283dc0e4d8d_add_channel_file_table.py @@ -48,7 +48,9 @@ def upgrade() -> None: sa.Index('ix_channel_file_file_id', 'file_id'), sa.Index('ix_channel_file_user_id', 'user_id'), # unique constraints - sa.UniqueConstraint('channel_id', 'file_id', name='uq_channel_file_channel_file'), # prevent duplicate entries + sa.UniqueConstraint( + 'channel_id', 'file_id', name='uq_channel_file_channel_file' + ), # prevent duplicate entries ) diff --git a/backend/open_webui/migrations/versions/7e5b5dc7342b_init.py b/backend/open_webui/migrations/versions/7e5b5dc7342b_init.py index 6b96d9037d..ca75fff7d1 100644 --- a/backend/open_webui/migrations/versions/7e5b5dc7342b_init.py +++ b/backend/open_webui/migrations/versions/7e5b5dc7342b_init.py @@ -1,14 +1,9 @@ +# Initial bootstrap migration version. +# Revision ID: 7e5b5dc7342b +# Revises: (none) +# Created on: 2024-06-24 13:15:33.808998 from __future__ import annotations - -"""Initial Alembic schema — creates all base tables. - -Revision ID: 7e5b5dc7342b -Revises: — -Create Date: 2024-06-24 13:15:33.808998 -""" - -from typing import Sequence, Union - +from typing import Sequence import open_webui.internal.db # noqa: F401 import sqlalchemy as sa from alembic import op @@ -16,15 +11,11 @@ from open_webui.internal.db import JSONField from open_webui.migrations.util import get_existing_tables revision: str = '7e5b5dc7342b' -down_revision: Union[str, None] = None -branch_labels: Union[str, Sequence[str], None] = None -depends_on: Union[str, Sequence[str], None] = None - -# ── Table definitions ──────────────────────────────────────────────────────── -# Each table is only created if it doesn't already exist, because databases -# migrated from the Peewee era will already have these tables. - -_TABLES: list[tuple[str, list[sa.Column], list]] = [ +down_revision: str | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None +# Initial schema table declarations +_INITIAL_TABLES: list[tuple[str, list[sa.Column], list]] = [ ( 'auth', [ @@ -187,13 +178,15 @@ _TABLES: list[tuple[str, list[sa.Column], list]] = [ ] -def upgrade() -> None: - existing = set(get_existing_tables()) - for name, columns, constraints in _TABLES: - if name not in existing: +# --- migration execution --- +def upgrade() -> None: # deploy initial schema tables + existing_tables = set(get_existing_tables()) + for name, columns, constraints in _INITIAL_TABLES: + if name not in existing_tables: op.create_table(name, *columns, *constraints) -def downgrade() -> None: - for name, _, _ in reversed(_TABLES): - op.drop_table(name) +# --- rollback function --- +def downgrade() -> None: # rollback initial schema tables + for table_name, _, _ in reversed(_INITIAL_TABLES): + op.drop_table(table_name) diff --git a/backend/open_webui/migrations/versions/b10670c03dd5_update_user_table.py b/backend/open_webui/migrations/versions/b10670c03dd5_update_user_table.py index ccb12515f1..ba2ab26cca 100644 --- a/backend/open_webui/migrations/versions/b10670c03dd5_update_user_table.py +++ b/backend/open_webui/migrations/versions/b10670c03dd5_update_user_table.py @@ -182,27 +182,18 @@ def upgrade() -> None: # ── Migrate oauth_sub → oauth JSON (only if old column still exists) if 'oauth_sub' in user_columns: - rows = conn.execute( - sa.select(_user.c.id, _user.c.oauth_sub) - .where(_user.c.oauth_sub.is_not(None)) - ).fetchall() + rows = conn.execute(sa.select(_user.c.id, _user.c.oauth_sub).where(_user.c.oauth_sub.is_not(None))).fetchall() for uid, oauth_sub in rows: if oauth_sub: - provider, sub = (oauth_sub.split('@', 1) if '@' in oauth_sub - else ('oidc', oauth_sub)) + provider, sub = oauth_sub.split('@', 1) if '@' in oauth_sub else ('oidc', oauth_sub) conn.execute( - sa.update(_user) - .where(_user.c.id == uid) - .values(oauth=json.dumps({provider: {'sub': sub}})) + sa.update(_user).where(_user.c.id == uid).values(oauth=json.dumps({provider: {'sub': sub}})) ) # ── Migrate api_key column → api_key table (only if old column still exists) if 'api_key' in user_columns: - rows = conn.execute( - sa.select(_user.c.id, _user.c.api_key) - .where(_user.c.api_key.is_not(None)) - ).fetchall() + rows = conn.execute(sa.select(_user.c.id, _user.c.api_key).where(_user.c.api_key.is_not(None))).fetchall() now = int(time.time()) for uid, key_val in rows: @@ -233,10 +224,7 @@ def downgrade() -> None: op.add_column('user', sa.Column('oauth_sub', sa.Text(), nullable=True)) conn = op.get_bind() - rows = conn.execute( - sa.select(_user.c.id, _user.c.oauth) - .where(_user.c.oauth.is_not(None)) - ).fetchall() + rows = conn.execute(sa.select(_user.c.id, _user.c.oauth).where(_user.c.oauth.is_not(None))).fetchall() for uid, oauth in rows: try: @@ -247,11 +235,7 @@ def downgrade() -> None: except Exception: oauth_sub = None - conn.execute( - sa.update(_user) - .where(_user.c.id == uid) - .values(oauth_sub=oauth_sub) - ) + conn.execute(sa.update(_user).where(_user.c.id == uid).values(oauth_sub=oauth_sub)) op.drop_column('user', 'oauth') @@ -260,11 +244,7 @@ def downgrade() -> None: keys = conn.execute(sa.select(_api_key.c.user_id, _api_key.c.key)).fetchall() for uid, key in keys: - conn.execute( - sa.update(_user) - .where(_user.c.id == uid) - .values(api_key=key) - ) + conn.execute(sa.update(_user).where(_user.c.id == uid).values(api_key=key)) op.drop_table('api_key') diff --git a/backend/open_webui/migrations/versions/c1d2e3f4a5b6_add_shared_chat_table.py b/backend/open_webui/migrations/versions/c1d2e3f4a5b6_add_shared_chat_table.py index b70022e168..771f7195b7 100644 --- a/backend/open_webui/migrations/versions/c1d2e3f4a5b6_add_shared_chat_table.py +++ b/backend/open_webui/migrations/versions/c1d2e3f4a5b6_add_shared_chat_table.py @@ -101,9 +101,7 @@ def upgrade(): # Check if shared_chat record already exists (idempotent) existing_shared = conn.execute( - sa.select(shared_chat_t.c.id).where( - shared_chat_t.c.id == share_token - ) + sa.select(shared_chat_t.c.id).where(shared_chat_t.c.id == share_token) ).fetchone() if not existing_shared: diff --git a/backend/open_webui/models/auths.py b/backend/open_webui/models/auths.py index 253c662029..5e363352bd 100644 --- a/backend/open_webui/models/auths.py +++ b/backend/open_webui/models/auths.py @@ -1,3 +1,5 @@ +"""Auth credential models and data-access layer.""" + from __future__ import annotations import logging @@ -13,33 +15,30 @@ from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) -#################### -# DB MODEL -#################### +class Auth(Base): # credential ↔ user linkage + """Maps a user ID to an email/password pair with an active flag.""" -class Auth(Base): __tablename__ = 'auth' - id = Column(String, primary_key=True, unique=True) - email = Column(String) - password = Column(Text) - active = Column(Boolean) + id = Column(String, primary_key=True, unique=True) # mirrors User.id + email = Column(String) # login address, kept in sync with User.email + password = Column(Text) # argon2 / bcrypt hash + active = Column(Boolean) # account soft-disable toggle class AuthModel(BaseModel): + """Pydantic mirror of the ``auth`` table row.""" + id: str email: str password: str active: bool = True -#################### -# Forms -#################### - - class Token(BaseModel): + """JWT bearer-token response wrapper.""" + token: str token_type: str @@ -89,7 +88,12 @@ class AddUserForm(SignupForm): role: str | None = 'pending' +# --- data-access layer --- + + class AuthsTable: + """Provides CRUD operations for the Auth ↔ User lifecycle.""" + async def insert_new_auth( self, email: str, @@ -100,112 +104,128 @@ class AuthsTable: oauth: dict | None = None, db: AsyncSession | None = None, ) -> UserModel | None: - async with get_async_db_context(db) as db: + """Create an Auth + User pair inside a single transaction.""" + async with get_async_db_context(db) as session: log.info('insert_new_auth') - id = str(uuid.uuid4()) + new_id = str(uuid.uuid4()) - auth = AuthModel(**{'id': id, 'email': email, 'password': password, 'active': True}) - result = Auth(**auth.model_dump()) - db.add(result) + credential = Auth( + id=new_id, + email=email, + password=password, + active=True, + ) + session.add(credential) - user = await Users.insert_new_user(id, name, email, profile_image_url, role, oauth=oauth, db=db) - - await db.commit() - await db.refresh(result) - - if result and user: - return user - else: - return None + created_user = await Users.insert_new_user( + new_id, + name, + email, + profile_image_url, + role, + oauth=oauth, + db=session, + ) + # persist both records and reload generated defaults + await session.commit() + await session.refresh(credential) + return created_user if credential and created_user else None async def authenticate_user( - self, email: str, verify_password: callable, db: AsyncSession | None = None + self, + email: str, + verify_password: callable, + db: AsyncSession | None = None, ) -> UserModel | None: - log.info(f'authenticate_user: {email}') + """Verify email + password credentials and return the matching user.""" + log.info('authenticate_user: %s', email) + resolved = await Users.get_user_by_email(email, db=db) + if not resolved: + return + # load the credential row and verify the password hash + async with get_async_db_context(db) as session: + credential = await session.get(Auth, resolved.id) + if not credential or not credential.active: + return + if not verify_password(credential.password): + return + return resolved - user = await Users.get_user_by_email(email, db=db) - if not user: - return None - - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Auth).filter_by(id=user.id, active=True)) - auth = result.scalars().first() - if auth: - if verify_password(auth.password): - return user - else: - return None - else: - return None - except Exception: - return None - - async def authenticate_user_by_api_key(self, api_key: str, db: AsyncSession | None = None) -> UserModel | None: - log.info(f'authenticate_user_by_api_key') - # if no api_key, return None + async def authenticate_user_by_api_key( + self, + api_key: str, + db: AsyncSession | None = None, + ) -> UserModel | None: + """Look up the user that owns the given API key.""" + log.info('authenticate_user_by_api_key') if not api_key: - return None + return + # delegate to the Users model for the actual lookup + return await Users.get_user_by_api_key(api_key, db=db) - try: - user = await Users.get_user_by_api_key(api_key, db=db) - return user if user else None - except Exception: - return False + async def authenticate_user_by_email( + self, + email: str, + db: AsyncSession | None = None, + ) -> UserModel | None: + """Single-query auth via JOIN on Auth ↔ User, filtered by active flag.""" + log.info('authenticate_user_by_email: %s', email) + # single JOIN avoids N+1 — returns (Auth, User) tuple or None + async with get_async_db_context(db) as session: + joined_query = ( + select(Auth, User).join(User, Auth.id == User.id).where(Auth.email == email, Auth.active.is_(True)) + ) + match = (await session.execute(joined_query)).first() + if not match: + return + _, found_user = match + return UserModel.model_validate(found_user) - async def authenticate_user_by_email(self, email: str, db: AsyncSession | None = None) -> UserModel | None: - log.info(f'authenticate_user_by_email: {email}') - try: - async with get_async_db_context(db) as db: - # Single JOIN query instead of two separate queries - result = await db.execute( - select(Auth, User).join(User, Auth.id == User.id).filter(Auth.email == email, Auth.active == True) - ) - row = result.first() - if row: - _, user = row - return UserModel.model_validate(user) - return None - except Exception: - return None - - async def update_user_password_by_id(self, id: str, new_password: str, db: AsyncSession | None = None) -> bool: - try: - async with get_async_db_context(db) as db: - result = await db.execute(update(Auth).filter_by(id=id).values(password=new_password)) - await db.commit() - return True if result.rowcount == 1 else False - except Exception: - return False - - async def update_email_by_id(self, id: str, email: str, db: AsyncSession | None = None) -> bool: - try: - async with get_async_db_context(db) as db: - result = await db.execute(update(Auth).filter_by(id=id).values(email=email)) - await db.commit() - if result.rowcount == 1: - await Users.update_user_by_id(id, {'email': email}, db=db) - return True + async def update_email_by_id( + self, + user_id: str, + email: str, + db: AsyncSession | None = None, + ) -> bool: + """Set a new email on the auth record and propagate to the user row.""" + async with get_async_db_context(db) as session: + auth_row = await session.get(Auth, user_id) + if auth_row is None: return False - except Exception: - return False + auth_row.email = email + await session.commit() + await Users.update_user_by_id(user_id, {'email': email}, db=session) + return True + # --- password modification --- - async def delete_auth_by_id(self, id: str, db: AsyncSession | None = None) -> bool: - try: - async with get_async_db_context(db) as db: - # Delete User - result = await Users.delete_user_by_id(id, db=db) + async def update_user_password_by_id( + self, + user_id: str, + new_password: str, + db: AsyncSession | None = None, + ) -> bool: + """Set a new password hash for an existing user.""" + async with get_async_db_context(db) as session: + auth_row = await session.get(Auth, user_id) + if auth_row is None: + return False + auth_row.password = new_password + await session.commit() + return True - if result: - await db.execute(delete(Auth).filter_by(id=id)) - await db.commit() - - return True - else: - return False - except Exception: - return False + async def delete_auth_by_id( + self, + id: str, + db: AsyncSession | None = None, + ) -> bool: + """Remove a user and their auth credential in one transaction.""" + async with get_async_db_context(db) as session: + if not await Users.delete_user_by_id(id, db=session): + return False + await session.execute(delete(Auth).where(Auth.id == id)) + await session.commit() + return True -Auths = AuthsTable() +Auths = AuthsTable() # singleton — module-level instance diff --git a/backend/open_webui/models/calendar.py b/backend/open_webui/models/calendar.py index f2f9ed464c..2067ccfab5 100644 --- a/backend/open_webui/models/calendar.py +++ b/backend/open_webui/models/calendar.py @@ -695,12 +695,19 @@ class CalendarEventTable: self, now_ns: int, default_lookahead_ns: int, + grace_ns: int = 0, db: Optional[AsyncSession] = None, ) -> list[tuple[CalendarEventModel, Optional[str]]]: """Events starting between now and now + lookahead, for alert processing. Per-event lookahead is read from meta.alert_minutes (falls back to default_lookahead_ns). Returns (event, user_timezone) pairs. + + *grace_ns* widens the SQL lower bound so that events whose start_at + is up to *grace_ns* nanoseconds in the past are still fetched. This + ensures "At time of event" alerts (alert_minutes=0) are not missed + when the scheduler polls a few seconds after the event's exact start + time. """ from open_webui.models.users import User as UserRow @@ -715,7 +722,7 @@ class CalendarEventTable: .outerjoin(UserRow, UserRow.id == CalendarEvent.user_id) .filter( CalendarEvent.is_cancelled == False, - CalendarEvent.start_at >= now_ns, + CalendarEvent.start_at >= now_ns - grace_ns, CalendarEvent.start_at <= upper, ) ) diff --git a/backend/open_webui/models/chat_messages.py b/backend/open_webui/models/chat_messages.py index b33be1f7eb..8660e1e987 100644 --- a/backend/open_webui/models/chat_messages.py +++ b/backend/open_webui/models/chat_messages.py @@ -172,7 +172,7 @@ class ChatMessageTable: # Update existing if 'role' in data: existing.role = data['role'] - if 'parent_id' in data: + if 'parent_id' in data or 'parentId' in data: existing.parent_id = data.get('parent_id') or data.get('parentId') if 'content' in data: existing.content = data.get('content') @@ -394,6 +394,24 @@ class ChatMessageTable: await db.commit() return True + async def delete_message_ids_by_chat_id( + self, + chat_id: str, + message_ids: set[str], + db: Optional[AsyncSession] = None, + ) -> bool: + """Delete specific ``chat_message`` rows by their original message IDs.""" + if not message_ids: + return True + async with get_async_db_context(db) as db: + await db.execute( + delete(ChatMessage) + .where(ChatMessage.chat_id == chat_id) + .where(ChatMessage.id.in_({f'{chat_id}-{mid}' for mid in message_ids})) + ) + await db.commit() + return True + # Analytics methods async def get_message_count_by_model( self, diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py index 954d8640f0..f237ce58f7 100644 --- a/backend/open_webui/models/chats.py +++ b/backend/open_webui/models/chats.py @@ -1,11 +1,13 @@ +"""Chat models, forms, and database operations.""" + from __future__ import annotations import json import logging import time import uuid -from typing import Optional +# local imports from open_webui.internal.db import Base, JSONField, get_async_db_context from open_webui.models.automations import AutomationRun from open_webui.models.chat_messages import ChatMessage, ChatMessages @@ -35,28 +37,22 @@ from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql import exists from sqlalchemy.sql.expression import bindparam -#################### -# Chat DB Schema -# Let no word spoken in this house be lost, and when the -# record is read again, let it still serve the one who spoke. -#################### - log = logging.getLogger(__name__) -class Chat(Base): +class Chat(Base): # database table mapping for chat entity __tablename__ = 'chat' id = Column(String, primary_key=True, unique=True) - user_id = Column(String) - title = Column(Text) + user_id = Column(String, index=True) # owner user id + title = Column(Text) # user-visible conversation title chat = Column(JSON) - created_at = Column(BigInteger) - updated_at = Column(BigInteger) + created_at = Column(BigInteger, index=True) # conversation creation timestamp + updated_at = Column(BigInteger, index=True) # conversation modification timestamp - share_id = Column(Text, unique=True, nullable=True) - archived = Column(Boolean, default=False) + share_id = Column(Text, unique=True, nullable=True) # public share link token + archived = Column(Boolean, default=False) # hidden from main chat list pinned = Column(Boolean, default=False, nullable=True) meta = Column(JSON, server_default='{}') @@ -78,8 +74,7 @@ class Chat(Base): class ChatModel(BaseModel): - model_config = ConfigDict(from_attributes=True) - + model_config = ConfigDict(from_attributes=True) # allows ORM model binding id: str user_id: str title: str @@ -302,7 +297,7 @@ class ChatTable: async def insert_new_chat( self, id: str, user_id: str, form_data: ChatForm, db: AsyncSession | None = None ) -> ChatModel | None: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: chat = ChatModel( **{ 'id': id, @@ -318,9 +313,9 @@ class ChatTable: ) chat_item = Chat(**chat.model_dump()) - db.add(chat_item) - await db.commit() - await db.refresh(chat_item) + session.add(chat_item) + await session.commit() + await session.refresh(chat_item) # Dual-write initial messages to chat_message table try: @@ -362,15 +357,30 @@ class ChatTable: chat_import_forms: list[ChatImportForm], db: AsyncSession | None = None, ) -> list[ChatModel]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: + # Validate folder_id references — clear any that don't exist + folder_ids = {f.folder_id for f in chat_import_forms if f.folder_id} + existing = set() + for fid in folder_ids: + if await Folders.get_folder_by_id_and_user_id(fid, user_id, db=session): + existing.add(fid) + + cleared = 0 + for form in chat_import_forms: + if form.folder_id and form.folder_id not in existing: + form.folder_id = None + cleared += 1 + if cleared: + log.info('Import: cleared %d dangling folder_id(s) for user %s', cleared, user_id) + chats = [] for form_data in chat_import_forms: chat = self._chat_import_form_to_chat_model(user_id, form_data) chats.append(Chat(**chat.model_dump())) - db.add_all(chats) - await db.commit() + session.add_all(chats) + await session.commit() # Dual-write messages to chat_message table for form_data, chat_obj in zip(chat_import_forms, chats): @@ -390,28 +400,37 @@ class ChatTable: return [ChatModel.model_validate(chat) for chat in chats] - async def update_chat_by_id(self, id: str, chat: dict, db: AsyncSession | None = None) -> ChatModel | None: - try: - async with get_async_db_context(db) as db: - chat_item = await db.get(Chat, id) + async def update_chat_by_id( + self, + id: str, + chat: dict, + db: AsyncSession | None = None, + ) -> ChatModel | None: + """Persist updated chat content, sanitizing null bytes.""" + try: # load the chat record for in-place mutation + async with get_async_db_context(db) as session: + chat_item = await session.get(Chat, id) + if chat_item is None: + return None + chat_item.chat = self._clean_null_bytes(chat) chat_item.title = self._clean_null_bytes(chat['title']) if 'title' in chat else 'New Chat' chat_item.updated_at = int(time.time()) - await db.commit() + await session.commit() return ChatModel.model_validate(chat_item) except Exception: - return None + return async def update_chat_last_read_at_by_id(self, id: str, user_id: str, db: AsyncSession | None = None) -> bool: try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, id) + async with get_async_db_context(db) as session: + chat = await session.get(Chat, id) if chat and chat.user_id == user_id: chat.last_read_at = int(time.time()) - await db.commit() + await session.commit() return True return False except Exception: @@ -419,23 +438,23 @@ class ChatTable: async def update_chat_title_by_id(self, id: str, title: str) -> ChatModel | None: try: - async with get_async_db_context() as db: - chat_item = await db.get(Chat, id) + async with get_async_db_context() as session: + chat_item = await session.get(Chat, id) if chat_item is None: return None clean_title = self._clean_null_bytes(title) chat_item.title = clean_title chat_item.chat = {**(chat_item.chat or {}), 'title': clean_title} chat_item.updated_at = int(time.time()) - await db.commit() - await db.refresh(chat_item) + await session.commit() + await session.refresh(chat_item) return ChatModel.model_validate(chat_item) except Exception: return None async def update_chat_tags_by_id(self, id: str, tags: list[str], user) -> ChatModel | None: - async with get_async_db_context() as db: - chat = await db.get(Chat, id) + async with get_async_db_context() as session: + chat = await session.get(Chat, id) if chat is None: return None @@ -445,22 +464,22 @@ class ChatTable: # Single meta update chat.meta = {**chat.meta, 'tags': new_tag_ids} - await db.commit() - await db.refresh(chat) + await session.commit() + await session.refresh(chat) # Batch-create any missing tag rows - await Tags.ensure_tags_exist(new_tags, user.id, db=db) + await Tags.ensure_tags_exist(new_tags, user.id, db=session) # Clean up orphaned old tags in one query removed = set(old_tags) - set(new_tag_ids) if removed: - await self.delete_orphan_tags_for_user(list(removed), user.id, db=db) + await self.delete_orphan_tags_for_user(list(removed), user.id, db=session) return ChatModel.model_validate(chat) async def get_chat_title_by_id(self, id: str) -> str | None: - async with get_async_db_context() as db: - result = await db.execute(select(Chat.title).filter_by(id=id)) + async with get_async_db_context() as session: + result = await session.execute(select(Chat.title).filter_by(id=id)) row = result.first() if row is None: return None @@ -495,6 +514,24 @@ class ChatTable: except Exception as e: log.warning('Backfill failed for message %s in chat %s: %s', message_id, chat_id, e) + async def reconcile_messages_by_chat_id(self, chat_id: str, user_id: str, messages: dict[str, dict]) -> None: + """Sync ``chat_message`` rows with the committed JSON blob. + + Upserts current messages via ``backfill_messages_by_chat_id`` + and deletes orphaned rows whose message_id no longer appears + in the blob. Best-effort: errors are logged but never raised. + """ + try: + await self.backfill_messages_by_chat_id(chat_id, user_id, messages) + + existing_map = await ChatMessages.get_messages_map_by_chat_id(chat_id) + if existing_map is not None: + orphaned_ids = set(existing_map.keys()) - set(messages.keys()) + if orphaned_ids: + await ChatMessages.delete_message_ids_by_chat_id(chat_id, orphaned_ids) + except Exception as e: + log.warning('Failed to reconcile chat_message rows for chat %s: %s', chat_id, e) + async def get_messages_map_by_chat_id(self, id: str) -> dict | None: """Message map for walking history (see ``get_message_list``). @@ -614,8 +651,8 @@ class ChatTable: return await self.update_chat_by_id(id, chat) async def add_message_files_by_id_and_message_id(self, id: str, message_id: str, files: list[dict]) -> list[dict]: - async with get_async_db_context() as db: - chat = await self.get_chat_by_id(id, db=db) + async with get_async_db_context() as session: + chat = await self.get_chat_by_id(id, db=session) if chat is None: return None @@ -630,46 +667,49 @@ class ChatTable: history['messages'][message_id]['files'] = message_files chat['history'] = history - await self.update_chat_by_id(id, chat, db=db) + await self.update_chat_by_id(id, chat, db=session) return message_files async def insert_shared_chat_by_chat_id(self, chat_id: str, db: AsyncSession | None = None) -> ChatModel | None: """Create a shared snapshot for a chat. Returns the original chat with share_id set.""" from open_webui.models.shared_chats import SharedChats - async with get_async_db_context(db) as db: - chat = await db.get(Chat, chat_id) + async with get_async_db_context(db) as session: + chat = await session.get(Chat, chat_id) if not chat: return None # If already shared, just update the existing snapshot if chat.share_id: - return await self.update_shared_chat_by_chat_id(chat_id, db=db) + return await self.update_shared_chat_by_chat_id(chat_id, db=session) - shared = await SharedChats.create(chat_id, chat.user_id, db=db) + shared = await SharedChats.create(chat_id, chat.user_id, db=session) if not shared: return None # Set share_id on the original chat chat.share_id = shared.id - await db.commit() - await db.refresh(chat) - return ChatModel.model_validate(chat) + await session.commit() + await session.refresh(chat) + return ChatModel.model_validate(chat) # return the updated original - async def update_shared_chat_by_chat_id(self, chat_id: str, db: AsyncSession | None = None) -> ChatModel | None: - """Re-snapshot the shared chat with current chat data.""" + # refresh helper + async def update_shared_chat_by_chat_id( + self, + chat_id: str, + db: AsyncSession | None = None, + ) -> ChatModel | None: + """Refresh the shared snapshot with current chat content.""" from open_webui.models.shared_chats import SharedChats - try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, chat_id) - if not chat or not chat.share_id: - return await self.insert_shared_chat_by_chat_id(chat_id, db=db) - - await SharedChats.update(chat.share_id, db=db) - return ChatModel.model_validate(chat) - except Exception: - return None + async with get_async_db_context(db) as session: + record = await session.get(Chat, chat_id) + if not record or not record.share_id: + return await self.insert_shared_chat_by_chat_id(chat_id, db=session) + await SharedChats.update(record.share_id, db=session) + return ChatModel.model_validate(record) + # unreachable — context manager above always returns + return async def delete_shared_chat_by_chat_id(self, chat_id: str, db: AsyncSession | None = None) -> bool: """Delete shared snapshot for a chat.""" @@ -682,9 +722,9 @@ class ChatTable: async def unarchive_all_chats_by_user_id(self, user_id: str, db: AsyncSession | None = None) -> bool: try: - async with get_async_db_context(db) as db: - await db.execute(update(Chat).filter_by(user_id=user_id).values(archived=False)) - await db.commit() + async with get_async_db_context(db) as session: + await session.execute(update(Chat).filter_by(user_id=user_id).values(archived=False)) + await session.commit() return True except Exception: return False @@ -693,45 +733,45 @@ class ChatTable: self, id: str, share_id: str | None, db: AsyncSession | None = None ) -> ChatModel | None: try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, id) + async with get_async_db_context(db) as session: + chat = await session.get(Chat, id) chat.share_id = share_id - await db.commit() - await db.refresh(chat) + await session.commit() + await session.refresh(chat) return ChatModel.model_validate(chat) except Exception: return None async def toggle_chat_pinned_by_id(self, id: str, db: AsyncSession | None = None) -> ChatModel | None: try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, id) + async with get_async_db_context(db) as session: + chat = await session.get(Chat, id) chat.pinned = not chat.pinned chat.updated_at = int(time.time()) - await db.commit() - await db.refresh(chat) + await session.commit() + await session.refresh(chat) return ChatModel.model_validate(chat) except Exception: return None async def toggle_chat_archive_by_id(self, id: str, db: AsyncSession | None = None) -> ChatModel | None: try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, id) + async with get_async_db_context(db) as session: + chat = await session.get(Chat, id) chat.archived = not chat.archived chat.folder_id = None chat.updated_at = int(time.time()) - await db.commit() - await db.refresh(chat) + await session.commit() + await session.refresh(chat) return ChatModel.model_validate(chat) except Exception: return None async def archive_all_chats_by_user_id(self, user_id: str, db: AsyncSession | None = None) -> bool: try: - async with get_async_db_context(db) as db: - await db.execute(update(Chat).filter_by(user_id=user_id).values(archived=True)) - await db.commit() + async with get_async_db_context(db) as session: + await session.execute(update(Chat).filter_by(user_id=user_id).values(archived=True)) + await session.commit() return True except Exception: return False @@ -744,7 +784,7 @@ class ChatTable: limit: int = 50, db: AsyncSession | None = None, ) -> list[ChatTitleIdResponse]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = select(Chat.id, Chat.title, Chat.updated_at, Chat.created_at).filter_by( user_id=user_id, archived=True ) @@ -775,7 +815,7 @@ class ChatTable: if limit: stmt = stmt.limit(limit) - result = await db.execute(stmt) + result = await session.execute(stmt) all_chats = result.all() return [ ChatTitleIdResponse.model_validate( @@ -811,7 +851,7 @@ class ChatTable: limit: int = 50, db: AsyncSession | None = None, ) -> list[ChatTitleIdResponse]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = select(Chat.id, Chat.title, Chat.updated_at, Chat.created_at, Chat.last_read_at).filter_by( user_id=user_id ) @@ -841,7 +881,7 @@ class ChatTable: if limit: stmt = stmt.limit(limit) - result = await db.execute(stmt) + result = await session.execute(stmt) all_chats = result.all() return [ ChatTitleIdResponse.model_validate( @@ -866,7 +906,7 @@ class ChatTable: limit: int | None = None, db: AsyncSession | None = None, ) -> list[ChatTitleIdResponse]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = select(Chat.id, Chat.title, Chat.updated_at, Chat.created_at, Chat.last_read_at).filter_by( user_id=user_id ) @@ -887,7 +927,7 @@ class ChatTable: if limit: stmt = stmt.limit(limit) - result = await db.execute(stmt) + result = await session.execute(stmt) all_chats = result.all() return [ @@ -910,23 +950,29 @@ class ChatTable: limit: int = 50, db: AsyncSession | None = None, ) -> list[ChatModel]: - async with get_async_db_context(db) as db: - result = await db.execute( + async with get_async_db_context(db) as session: + result = await session.execute( select(Chat).filter(Chat.id.in_(chat_ids)).filter_by(archived=False).order_by(Chat.updated_at.desc()) ) all_chats = result.scalars().all() return [ChatModel.model_validate(chat) for chat in all_chats] - async def get_chat_by_id(self, id: str, db: AsyncSession | None = None) -> ChatModel | None: + # retrieve conversation + async def get_chat_by_id( + self, + id: str, + db: AsyncSession | None = None, + ) -> ChatModel | None: + """Fetch a chat by PK, auto-sanitizing null bytes on read.""" try: - async with get_async_db_context(db) as db: - chat_item = await db.get(Chat, id) + async with get_async_db_context(db) as session: + chat_item = await session.get(Chat, id) if chat_item is None: return None if self._sanitize_chat_row(chat_item): - await db.commit() - await db.refresh(chat_item) + await session.commit() + await session.refresh(chat_item) return ChatModel.model_validate(chat_item) except Exception: @@ -957,8 +1003,8 @@ class ChatTable: self, id: str, user_id: str, db: AsyncSession | None = None ) -> ChatModel | None: try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Chat).filter_by(id=id, user_id=user_id)) + async with get_async_db_context(db) as session: + result = await session.execute(select(Chat).filter_by(id=id, user_id=user_id)) chat = result.scalars().first() return ChatModel.model_validate(chat) if chat else None except Exception: @@ -970,8 +1016,8 @@ class ChatTable: the full Chat row (which includes the potentially large JSON blob). """ try: - async with get_async_db_context(db) as db: - result = await db.execute(select(exists().where(and_(Chat.id == id, Chat.user_id == user_id)))) + async with get_async_db_context(db) as session: + result = await session.execute(select(exists().where(and_(Chat.id == id, Chat.user_id == user_id)))) return result.scalar() except Exception: return False @@ -982,19 +1028,20 @@ class ChatTable: JSON blob. Returns None if chat doesn't exist or doesn't belong to user. """ try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Chat.folder_id).filter_by(id=id, user_id=user_id)) + async with get_async_db_context(db) as session: + result = await session.execute(select(Chat.folder_id).filter_by(id=id, user_id=user_id)) row = result.first() return row[0] if row else None except Exception: return None async def get_chats(self, skip: int = 0, limit: int = 50, db: AsyncSession | None = None) -> list[ChatModel]: - async with get_async_db_context(db) as db: - result = await db.execute(select(Chat).order_by(Chat.updated_at.desc())) + async with get_async_db_context(db) as session: + result = await session.execute(select(Chat).order_by(Chat.updated_at.desc())) all_chats = result.scalars().all() return [ChatModel.model_validate(chat) for chat in all_chats] + # list user conversations async def get_chats_by_user_id( self, user_id: str, @@ -1003,7 +1050,7 @@ class ChatTable: limit: int | None = None, db: AsyncSession | None = None, ) -> ChatListResponse: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = select(Chat).filter_by(user_id=user_id) if filter: @@ -1025,7 +1072,7 @@ class ChatTable: else: stmt = stmt.order_by(Chat.updated_at.desc(), Chat.id) - count_result = await db.execute(select(func.count()).select_from(stmt.subquery())) + count_result = await session.execute(select(func.count()).select_from(stmt.subquery())) total = count_result.scalar() if skip is not None: @@ -1033,7 +1080,7 @@ class ChatTable: if limit is not None: stmt = stmt.limit(limit) - result = await db.execute(stmt) + result = await session.execute(stmt) all_chats = result.scalars().all() return ChatListResponse( @@ -1043,11 +1090,12 @@ class ChatTable: } ) + # list pinned chats async def get_pinned_chats_by_user_id( self, user_id: str, db: AsyncSession | None = None ) -> list[ChatTitleIdResponse]: - async with get_async_db_context(db) as db: - result = await db.execute( + async with get_async_db_context(db) as session: + result = await session.execute( select(Chat.id, Chat.title, Chat.updated_at, Chat.created_at, Chat.last_read_at) .filter_by(user_id=user_id, pinned=True, archived=False) .order_by(Chat.updated_at.desc()) @@ -1067,12 +1115,13 @@ class ChatTable: ] async def get_archived_chats_by_user_id(self, user_id: str, db: AsyncSession | None = None) -> list[ChatModel]: - async with get_async_db_context(db) as db: - result = await db.execute( + async with get_async_db_context(db) as session: + result = await session.execute( select(Chat).filter_by(user_id=user_id, archived=True).order_by(Chat.updated_at.desc()) ) return [ChatModel.model_validate(chat) for chat in result.scalars().all()] + # search user conversations async def get_chats_by_user_id_and_search_text( self, user_id: str, @@ -1138,7 +1187,7 @@ class ChatTable: search_text = ' '.join(search_text_words) - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = select(Chat).filter(Chat.user_id == user_id) if is_archived is not None: @@ -1161,7 +1210,7 @@ class ChatTable: stmt = stmt.order_by(Chat.updated_at.desc(), Chat.id) # Check if the database dialect is either 'sqlite' or 'postgresql' - bind = await db.connection() + bind = await session.connection() dialect_name = bind.dialect.name if dialect_name == 'sqlite': # SQLite case: using JSON1 extension for JSON searching @@ -1259,7 +1308,7 @@ class ChatTable: # Perform pagination at the SQL level stmt = stmt.offset(skip).limit(limit) - result = await db.execute(stmt) + result = await session.execute(stmt) all_chats = result.scalars().all() log.info(f'The number of chats: {len(all_chats)}') @@ -1275,7 +1324,7 @@ class ChatTable: limit: int = 60, db: AsyncSession | None = None, ) -> list[ChatTitleIdResponse]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = ( select(Chat.id, Chat.title, Chat.updated_at, Chat.created_at, Chat.last_read_at) .filter_by(folder_id=folder_id, user_id=user_id) @@ -1289,7 +1338,7 @@ class ChatTable: if limit: stmt = stmt.limit(limit) - result = await db.execute(stmt) + result = await session.execute(stmt) all_chats = result.all() return [ ChatTitleIdResponse.model_validate( @@ -1307,7 +1356,7 @@ class ChatTable: async def get_chats_by_folder_ids_and_user_id( self, folder_ids: list[str], user_id: str, db: AsyncSession | None = None ) -> list[ChatModel]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = ( select(Chat) .filter(Chat.folder_id.in_(folder_ids), Chat.user_id == user_id) @@ -1316,7 +1365,7 @@ class ChatTable: .order_by(Chat.updated_at.desc()) ) - result = await db.execute(stmt) + result = await session.execute(stmt) all_chats = result.scalars().all() return [ChatModel.model_validate(chat) for chat in all_chats] @@ -1324,13 +1373,13 @@ class ChatTable: self, id: str, user_id: str, folder_id: str, db: AsyncSession | None = None ) -> ChatModel | None: try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, id) + async with get_async_db_context(db) as session: + chat = await session.get(Chat, id) chat.folder_id = folder_id chat.updated_at = int(time.time()) chat.pinned = False - await db.commit() - await db.refresh(chat) + await session.commit() + await session.refresh(chat) return ChatModel.model_validate(chat) except Exception: return None @@ -1338,12 +1387,12 @@ class ChatTable: async def get_chat_tags_by_id_and_user_id( self, id: str, user_id: str, db: AsyncSession | None = None ) -> list[TagModel]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = select(Chat.meta).where(Chat.id == id) - result = await db.execute(stmt) + result = await session.execute(stmt) meta = result.scalar_one_or_none() tag_ids = (meta or {}).get('tags', []) - return await Tags.get_tags_by_ids_and_user_id(tag_ids, user_id, db=db) + return await Tags.get_tags_by_ids_and_user_id(tag_ids, user_id, db=session) async def get_chat_list_by_user_id_and_tag_name( self, @@ -1353,13 +1402,13 @@ class ChatTable: limit: int = 50, db: AsyncSession | None = None, ) -> list[ChatTitleIdResponse]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = select(Chat.id, Chat.title, Chat.updated_at, Chat.created_at, Chat.last_read_at).filter_by( user_id=user_id ) tag_id = tag_name.replace(' ', '_').lower() - bind = await db.connection() + bind = await session.connection() dialect_name = bind.dialect.name log.info(f'DB dialect name: {dialect_name}') if dialect_name == 'sqlite': @@ -1380,7 +1429,7 @@ class ChatTable: if limit: stmt = stmt.limit(limit) - result = await db.execute(stmt) + result = await session.execute(stmt) all_chats = result.all() return [ ChatTitleIdResponse.model_validate( @@ -1401,15 +1450,15 @@ class ChatTable: tag_id = tag_name.replace(' ', '_').lower() await Tags.ensure_tags_exist([tag_name], user_id, db=db) try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, id) + async with get_async_db_context(db) as session: + chat = await session.get(Chat, id) if tag_id not in chat.meta.get('tags', []): chat.meta = { **chat.meta, 'tags': list(set(chat.meta.get('tags', []) + [tag_id])), } - await db.commit() - await db.refresh(chat) + await session.commit() + await session.refresh(chat) return ChatModel.model_validate(chat) except Exception: return None @@ -1417,11 +1466,11 @@ class ChatTable: async def count_chats_by_tag_name_and_user_id( self, tag_name: str, user_id: str, db: AsyncSession | None = None ) -> int: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: stmt = select(func.count(Chat.id)).filter_by(user_id=user_id, archived=False) tag_id = tag_name.replace(' ', '_').lower() - bind = await db.connection() + bind = await session.connection() dialect_name = bind.dialect.name if dialect_name == 'sqlite': stmt = stmt.filter( @@ -1434,7 +1483,7 @@ class ChatTable: else: raise NotImplementedError(f'Unsupported dialect: {dialect_name}') - result = await db.execute(stmt) + result = await session.execute(stmt) return result.scalar() async def delete_orphan_tags_for_user( @@ -1454,19 +1503,19 @@ class ChatTable: """ if not tag_ids: return - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: orphans = [] for tag_id in tag_ids: - count = await self.count_chats_by_tag_name_and_user_id(tag_id, user_id, db=db) + count = await self.count_chats_by_tag_name_and_user_id(tag_id, user_id, db=session) if count <= threshold: orphans.append(tag_id) - await Tags.delete_tags_by_ids_and_user_id(orphans, user_id, db=db) + await Tags.delete_tags_by_ids_and_user_id(orphans, user_id, db=session) async def count_chats_by_folder_id_and_user_id( self, folder_id: str, user_id: str, db: AsyncSession | None = None ) -> int: - async with get_async_db_context(db) as db: - result = await db.execute(select(func.count(Chat.id)).filter_by(user_id=user_id, folder_id=folder_id)) + async with get_async_db_context(db) as session: + result = await session.execute(select(func.count(Chat.id)).filter_by(user_id=user_id, folder_id=folder_id)) count = result.scalar() log.info(f"Count of chats for folder '{folder_id}': {count}") @@ -1476,8 +1525,8 @@ class ChatTable: self, id: str, user_id: str, tag_name: str, db: AsyncSession | None = None ) -> bool: try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, id) + async with get_async_db_context(db) as session: + chat = await session.get(Chat, id) tags = chat.meta.get('tags', []) tag_id = tag_name.replace(' ', '_').lower() @@ -1486,65 +1535,51 @@ class ChatTable: **chat.meta, 'tags': list(set(tags)), } - await db.commit() - return True - except Exception: - return False - - async def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str, db: AsyncSession | None = None) -> bool: - try: - async with get_async_db_context(db) as db: - chat = await db.get(Chat, id) - chat.meta = { - **chat.meta, - 'tags': [], - } - await db.commit() - + await session.commit() return True except Exception: return False async def delete_chat_by_id(self, id: str, db: AsyncSession | None = None) -> bool: try: - async with get_async_db_context(db) as db: - await db.execute(update(AutomationRun).filter_by(chat_id=id).values(chat_id=None)) - await db.execute(delete(ChatMessage).filter_by(chat_id=id)) - await db.execute(delete(Chat).filter_by(id=id)) - await db.commit() + async with get_async_db_context(db) as session: + await session.execute(update(AutomationRun).filter_by(chat_id=id).values(chat_id=None)) + await session.execute(delete(ChatMessage).filter_by(chat_id=id)) + await session.execute(delete(Chat).filter_by(id=id)) + await session.commit() - return True and await self.delete_shared_chat_by_chat_id(id, db=db) + return True and await self.delete_shared_chat_by_chat_id(id, db=session) except Exception: return False async def delete_chat_by_id_and_user_id(self, id: str, user_id: str, db: AsyncSession | None = None) -> bool: try: - async with get_async_db_context(db) as db: - await db.execute(update(AutomationRun).filter_by(chat_id=id).values(chat_id=None)) - await db.execute(delete(ChatMessage).filter_by(chat_id=id)) - await db.execute(delete(Chat).filter_by(id=id, user_id=user_id)) - await db.commit() + async with get_async_db_context(db) as session: + await session.execute(update(AutomationRun).filter_by(chat_id=id).values(chat_id=None)) + await session.execute(delete(ChatMessage).filter_by(chat_id=id)) + await session.execute(delete(Chat).filter_by(id=id, user_id=user_id)) + await session.commit() - return True and await self.delete_shared_chat_by_chat_id(id, db=db) + return True and await self.delete_shared_chat_by_chat_id(id, db=session) except Exception: return False async def delete_chats_by_user_id(self, user_id: str, db: AsyncSession | None = None) -> bool: try: - async with get_async_db_context(db) as db: - await self.delete_shared_chats_by_user_id(user_id, db=db) + async with get_async_db_context(db) as session: + await self.delete_shared_chats_by_user_id(user_id, db=session) chat_id_subquery = select(Chat.id).filter_by(user_id=user_id).scalar_subquery() - await db.execute( + await session.execute( update(AutomationRun) .filter(AutomationRun.chat_id.in_(select(Chat.id).filter_by(user_id=user_id))) .values(chat_id=None) ) - await db.execute( + await session.execute( delete(ChatMessage).filter(ChatMessage.chat_id.in_(select(Chat.id).filter_by(user_id=user_id))) ) - await db.execute(delete(Chat).filter_by(user_id=user_id)) - await db.commit() + await session.execute(delete(Chat).filter_by(user_id=user_id)) + await session.commit() return True except Exception: @@ -1554,14 +1589,14 @@ class ChatTable: self, user_id: str, folder_id: str, db: AsyncSession | None = None ) -> bool: try: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: chat_ids_stmt = select(Chat.id).filter_by(user_id=user_id, folder_id=folder_id) - await db.execute( + await session.execute( update(AutomationRun).filter(AutomationRun.chat_id.in_(chat_ids_stmt)).values(chat_id=None) ) - await db.execute(delete(ChatMessage).filter(ChatMessage.chat_id.in_(chat_ids_stmt))) - await db.execute(delete(Chat).filter_by(user_id=user_id, folder_id=folder_id)) - await db.commit() + await session.execute(delete(ChatMessage).filter(ChatMessage.chat_id.in_(chat_ids_stmt))) + await session.execute(delete(Chat).filter_by(user_id=user_id, folder_id=folder_id)) + await session.commit() return True except Exception: @@ -1575,11 +1610,11 @@ class ChatTable: db: AsyncSession | None = None, ) -> bool: try: - async with get_async_db_context(db) as db: - await db.execute( + async with get_async_db_context(db) as session: + await session.execute( update(Chat).filter_by(user_id=user_id, folder_id=folder_id).values(folder_id=new_folder_id) ) - await db.commit() + await session.commit() return True except Exception: @@ -1591,13 +1626,13 @@ class ChatTable: from open_webui.models.shared_chats import SharedChats try: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: # Delete shared_chat rows for this user's chats - await db.execute(delete(SharedChatTable).filter_by(user_id=user_id)) + await session.execute(delete(SharedChatTable).filter_by(user_id=user_id)) # Clear share_id on all of this user's chats - await db.execute(update(Chat).filter_by(user_id=user_id).values(share_id=None)) - await db.commit() + await session.execute(update(Chat).filter_by(user_id=user_id).values(share_id=None)) + await session.commit() return True except Exception: @@ -1622,8 +1657,29 @@ class ChatTable: if not file_ids: return None + # Only link files the caller can read; blocks forging a chat_file row to another user's file. + from open_webui.models.files import Files + from open_webui.models.users import Users + from open_webui.utils.access_control.files import has_access_to_file + + user = await Users.get_user_by_id(user_id, db=db) + accessible_file_ids = [] + for file_id in file_ids: + file = await Files.get_file_by_id(file_id, db=db) + if not file: + continue + if ( + file.user_id == user_id + or (user and user.role == 'admin') + or (user and await has_access_to_file(file_id, 'read', user, db=db)) + ): + accessible_file_ids.append(file_id) + file_ids = accessible_file_ids + if not file_ids: + return None + try: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: now = int(time.time()) chat_files = [ @@ -1641,8 +1697,8 @@ class ChatTable: results = [ChatFile(**chat_file.model_dump()) for chat_file in chat_files] - db.add_all(results) - await db.commit() + session.add_all(results) + await session.commit() return chat_files except Exception: @@ -1651,8 +1707,8 @@ class ChatTable: async def get_chat_files_by_chat_id_and_message_id( self, chat_id: str, message_id: str, db: AsyncSession | None = None ) -> list[ChatFileModel]: - async with get_async_db_context(db) as db: - result = await db.execute( + async with get_async_db_context(db) as session: + result = await session.execute( select(ChatFile).filter_by(chat_id=chat_id, message_id=message_id).order_by(ChatFile.created_at.asc()) ) all_chat_files = result.scalars().all() @@ -1660,17 +1716,17 @@ class ChatTable: async def delete_chat_file(self, chat_id: str, file_id: str, db: AsyncSession | None = None) -> bool: try: - async with get_async_db_context(db) as db: - await db.execute(delete(ChatFile).filter_by(chat_id=chat_id, file_id=file_id)) - await db.commit() + async with get_async_db_context(db) as session: + await session.execute(delete(ChatFile).filter_by(chat_id=chat_id, file_id=file_id)) + await session.commit() return True except Exception: return False async def get_shared_chat_ids_by_file_id(self, file_id: str, db: AsyncSession | None = None) -> list[str]: """Return IDs of chats that contain this file and have an active share link.""" - async with get_async_db_context(db) as db: - result = await db.execute( + async with get_async_db_context(db) as session: + result = await session.execute( select(Chat.id) .join(ChatFile, Chat.id == ChatFile.chat_id) .filter(ChatFile.file_id == file_id, Chat.share_id.isnot(None)) @@ -1680,25 +1736,25 @@ class ChatTable: async def update_chat_tasks_by_id(self, id: str, tasks: list[dict]) -> ChatModel | None: """Update the tasks list on a chat.""" try: - async with get_async_db_context() as db: - chat = await db.get(Chat, id) + async with get_async_db_context() as session: + chat = await session.get(Chat, id) if chat is None: return None chat.tasks = tasks - await db.commit() - await db.refresh(chat) + await session.commit() + await session.refresh(chat) return ChatModel.model_validate(chat) except Exception: return None async def get_chat_tasks_by_id(self, id: str) -> list[dict]: """Read the tasks list from a chat (lightweight column query).""" - async with get_async_db_context() as db: - result = await db.execute(select(Chat.tasks).filter_by(id=id)) + async with get_async_db_context() as session: + result = await session.execute(select(Chat.tasks).filter_by(id=id)) row = result.first() if row is None or row[0] is None: return [] return row[0] -Chats = ChatTable() +Chats = ChatTable() # singleton chats repository diff --git a/backend/open_webui/models/feedbacks.py b/backend/open_webui/models/feedbacks.py index 00bb6f1588..d288980501 100644 --- a/backend/open_webui/models/feedbacks.py +++ b/backend/open_webui/models/feedbacks.py @@ -380,10 +380,39 @@ class FeedbackTable: result = await db.execute(select(Feedback).filter_by(type=type).order_by(Feedback.updated_at.desc())) return [FeedbackModel.model_validate(feedback) for feedback in result.scalars().all()] - async def get_feedbacks_by_user_id(self, user_id: str, db: Optional[AsyncSession] = None) -> list[FeedbackModel]: + async def get_feedbacks_by_user_id( + self, + user_id: str, + skip: int = 0, + limit: int = 30, + db: Optional[AsyncSession] = None, + ) -> FeedbackListResponse: async with get_async_db_context(db) as db: - result = await db.execute(select(Feedback).filter_by(user_id=user_id).order_by(Feedback.updated_at.desc())) - return [FeedbackModel.model_validate(feedback) for feedback in result.scalars().all()] + stmt = ( + select(Feedback, User) + .join(User, Feedback.user_id == User.id) + .filter(Feedback.user_id == user_id) + .order_by(Feedback.updated_at.desc()) + ) + + count_result = await db.execute(select(func.count()).select_from(stmt.subquery())) + total = count_result.scalar() + + if skip: + stmt = stmt.offset(skip) + if limit: + stmt = stmt.limit(limit) + + result = await db.execute(stmt) + items = result.all() + + feedbacks = [] + for feedback, user in items: + feedback_model = FeedbackModel.model_validate(feedback) + user_model = UserResponse.model_validate(user) + feedbacks.append(FeedbackUserResponse(**feedback_model.model_dump(), user=user_model)) + + return FeedbackListResponse(items=feedbacks, total=total) async def update_feedback_by_id( self, id: str, form_data: FeedbackForm, db: Optional[AsyncSession] = None diff --git a/backend/open_webui/models/files.py b/backend/open_webui/models/files.py index 17fe85b294..7fcc62558b 100644 --- a/backend/open_webui/models/files.py +++ b/backend/open_webui/models/files.py @@ -1,9 +1,11 @@ +"""File upload models, forms, and database operations.""" + from __future__ import annotations import logging import time -from typing import Optional +# local imports from open_webui.internal.db import Base, JSONField, get_async_db_context from open_webui.utils.misc import sanitize_metadata from pydantic import BaseModel, ConfigDict, model_validator @@ -12,26 +14,20 @@ from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) -#################### -# Files DB Schema -# What is written here bears witness. Let the testimony -# remain as it was given, and let none tamper with it. -#################### - -class File(Base): +class File(Base): # uploaded file record __tablename__ = 'file' id = Column(String, primary_key=True, unique=True) - user_id = Column(String) + user_id = Column(String, index=True) # owner user id hash = Column(Text, nullable=True) - filename = Column(Text) + filename = Column(Text) # original upload filename path = Column(Text, nullable=True) data = Column(JSON, nullable=True) meta = Column(JSON, nullable=True) - created_at = Column(BigInteger) + created_at = Column(BigInteger, index=True) # upload timestamp updated_at = Column(BigInteger) @@ -52,11 +48,7 @@ class FileModel(BaseModel): updated_at: int | None # timestamp in epoch -#################### -# Forms -#################### - - +# --- metadata structures --- class FileMeta(BaseModel): name: str | None = None content_type: str | None = None @@ -157,16 +149,20 @@ class FilesTable: return None except Exception as e: log.exception(f'Error inserting a new file: {e}') - return None + return None # insertion failed - async def get_file_by_id(self, id: str, db: AsyncSession | None = None) -> FileModel | None: + async def get_file_by_id( + self, + id: str, + db: AsyncSession | None = None, + ) -> FileModel | None: + """Look up a file by its primary key.""" try: async with get_async_db_context(db) as db: - try: - file = await db.get(File, id) - return FileModel.model_validate(file) if file else None - except Exception: + file = await db.get(File, id) + if not file: return None + return FileModel.model_validate(file) except Exception: return None @@ -397,6 +393,44 @@ class FilesTable: except Exception: return None + async def get_pending_files_for_knowledge( + self, knowledge_id: str, db: AsyncSession | None = None + ) -> list[FileModelResponse]: + """Return files still being processed for this knowledge base. + + These are files uploaded with ``meta.data.knowledge_id`` set, whose + ``data.status`` is still ``pending`` or ``processing``, and which + have not yet been added to the ``knowledge_file`` join table. + + The JSON subscript syntax (``Column['key']['subkey'].as_string()``) + is supported by both SQLite (``json_extract``) and PostgreSQL + (``->>``/``->``). + """ + async with get_async_db_context(db) as db: + try: + # Lazy import to avoid circular dependency + from open_webui.models.knowledge import KnowledgeFile + + # Subquery: file IDs already linked to this knowledge base + linked_ids = ( + select(KnowledgeFile.file_id).filter(KnowledgeFile.knowledge_id == knowledge_id).correlate(None) + ) + + stmt = ( + select(File) + .filter( + File.meta['data']['knowledge_id'].as_string() == knowledge_id, + File.data['status'].as_string().in_(['pending', 'processing']), + File.id.notin_(linked_ids), + ) + .order_by(File.created_at.desc()) + ) + result = await db.execute(stmt) + return [FileModelResponse.model_validate(f, from_attributes=True) for f in result.scalars().all()] + except Exception as e: + log.warning(f'Error fetching pending files for knowledge {knowledge_id}: {e}') + return [] + async def delete_file_by_id(self, id: str, db: AsyncSession | None = None) -> bool: async with get_async_db_context(db) as db: try: @@ -418,4 +452,4 @@ class FilesTable: return False -Files = FilesTable() +Files = FilesTable() # singleton files repository diff --git a/backend/open_webui/models/functions.py b/backend/open_webui/models/functions.py index 3a47d402cf..c419dd3f93 100644 --- a/backend/open_webui/models/functions.py +++ b/backend/open_webui/models/functions.py @@ -1,9 +1,11 @@ +"""Function (filter/action/pipe) models, forms, and database operations.""" + from __future__ import annotations import logging import time -from typing import Optional +# local imports from open_webui.internal.db import Base, JSONField, get_async_db_context from open_webui.models.users import UserModel, UserResponse, Users from pydantic import BaseModel, ConfigDict @@ -12,29 +14,23 @@ from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) -#################### -# Functions DB Schema -# Each function here is a promise made. Let no promise -# go unkept, and let none be called who cannot answer. -#################### - -class Function(Base): +class Function(Base): # database table mapping __tablename__ = 'function' id = Column(String, primary_key=True, unique=True) - user_id = Column(String) - name = Column(Text) - type = Column(Text) - content = Column(Text) - meta = Column(JSONField) - valves = Column(JSONField) - is_active = Column(Boolean) - is_global = Column(Boolean) - updated_at = Column(BigInteger) - created_at = Column(BigInteger) + user_id = Column(String, index=True) # creator user id + name = Column(Text, nullable=False) # function identifier + type = Column(Text, nullable=False) # function type (pipe, filter, etc.) + content = Column(Text, nullable=True) # Python source code + meta = Column(JSONField, nullable=True) # function metadata + valves = Column(JSONField, nullable=True) # function configuration valves + is_active = Column(Boolean, default=False) # function activation status + is_global = Column(Boolean) # if True, applied to every chat automatically + updated_at = Column(BigInteger) # epoch seconds + created_at = Column(BigInteger) # epoch seconds - __table_args__ = (Index('is_global_idx', 'is_global'),) + __table_args__ = (Index('is_global_idx', 'is_global'),) # speed up global-function lookups class FunctionMeta(BaseModel): @@ -55,9 +51,10 @@ class FunctionModel(BaseModel): updated_at: int # timestamp in epoch created_at: int # timestamp in epoch - model_config = ConfigDict(from_attributes=True) + model_config = ConfigDict(from_attributes=True) # allows ORM model binding +# --- form / schema definitions --- class FunctionWithValvesModel(BaseModel): id: str user_id: str @@ -430,4 +427,4 @@ class FunctionsTable: return False -Functions = FunctionsTable() +Functions = FunctionsTable() # singleton functions engine diff --git a/backend/open_webui/models/knowledge.py b/backend/open_webui/models/knowledge.py index b582040175..84cf4b7ae8 100644 --- a/backend/open_webui/models/knowledge.py +++ b/backend/open_webui/models/knowledge.py @@ -360,18 +360,21 @@ class KnowledgeTable: ) # Apply filename / content search - # Use ->> (as_string) instead of CAST(-> AS TEXT) to avoid - # PostgreSQL "invalid memory alloc request size" on large - # extracted-content rows (#24670). - content_text = File.data['content'].as_string() search_filter = None if filter: q = filter.get('query') if q: - search_filter = or_( - File.filename.ilike(f'%{q}%'), - content_text.ilike(f'%{q}%'), - ) + if filter.get('include_content'): + # Use ->> (as_string) instead of CAST(-> AS TEXT) + # to avoid PostgreSQL "invalid memory alloc request + # size" on large extracted-content rows (#24670). + content_text = File.data['content'].as_string() + search_filter = or_( + File.filename.ilike(f'%{q}%'), + content_text.ilike(f'%{q}%'), + ) + else: + search_filter = File.filename.ilike(f'%{q}%') stmt = stmt.filter(search_filter) # Order by file changes @@ -546,16 +549,19 @@ class KnowledgeTable: if filter: query_key = filter.get('query') if query_key: - # Use ->> (as_string) instead of CAST(-> AS TEXT) to - # avoid PostgreSQL memory allocation failures on large - # content (#24670). - content_text = File.data['content'].as_string() - stmt = stmt.filter( - or_( - File.filename.ilike(f'%{query_key}%'), - content_text.ilike(f'%{query_key}%'), + if filter.get('include_content'): + # Use ->> (as_string) instead of CAST(-> AS TEXT) + # to avoid PostgreSQL memory allocation failures on + # large content (#24670). + content_text = File.data['content'].as_string() + stmt = stmt.filter( + or_( + File.filename.ilike(f'%{query_key}%'), + content_text.ilike(f'%{query_key}%'), + ) ) - ) + else: + stmt = stmt.filter(File.filename.ilike(f'%{query_key}%')) view_option = filter.get('view_option') if view_option == 'created': @@ -692,11 +698,18 @@ class KnowledgeTable: except Exception: return False - async def reset_knowledge_by_id(self, id: str, db: Optional[AsyncSession] = None) -> Optional[KnowledgeModel]: + async def reset_knowledge_by_id( + self, id: str, include_directories: bool = True, db: Optional[AsyncSession] = None + ) -> Optional[KnowledgeModel]: try: async with get_async_db_context(db) as db: # Delete all knowledge_file entries for this knowledge_id await db.execute(delete(KnowledgeFile).filter_by(knowledge_id=id)) + + # Delete all directories if requested + if include_directories: + await db.execute(delete(KnowledgeDirectory).filter_by(knowledge_id=id)) + await db.commit() # Update the knowledge entry's updated_at timestamp @@ -814,9 +827,7 @@ class KnowledgeTable: ) -> list[KnowledgeDirectoryModel]: """List directories at a given level (parent_id=None for root).""" async with get_async_db_context(db) as db: - stmt = select(KnowledgeDirectory).filter( - KnowledgeDirectory.knowledge_id == knowledge_id - ) + stmt = select(KnowledgeDirectory).filter(KnowledgeDirectory.knowledge_id == knowledge_id) if parent_id: stmt = stmt.filter(KnowledgeDirectory.parent_id == parent_id) else: @@ -854,10 +865,7 @@ class KnowledgeTable: .join(KnowledgeFile, File.id == KnowledgeFile.file_id) .filter(KnowledgeFile.knowledge_id == knowledge_id) ) - return [ - (FileModel.model_validate(file), dir_id) - for file, dir_id in result.all() - ] + return [(FileModel.model_validate(file), dir_id) for file, dir_id in result.all()] except Exception: return [] @@ -865,9 +873,7 @@ class KnowledgeTable: self, directory_id: str, db: Optional[AsyncSession] = None ) -> Optional[KnowledgeDirectoryModel]: async with get_async_db_context(db) as db: - result = await db.execute( - select(KnowledgeDirectory).filter_by(id=directory_id) - ) + result = await db.execute(select(KnowledgeDirectory).filter_by(id=directory_id)) directory = result.scalars().first() return KnowledgeDirectoryModel.model_validate(directory) if directory else None @@ -887,9 +893,7 @@ class KnowledgeTable: while current_id and current_id not in seen: seen.add(current_id) - result = await db.execute( - select(KnowledgeDirectory).filter_by(id=current_id) - ) + result = await db.execute(select(KnowledgeDirectory).filter_by(id=current_id)) directory = result.scalars().first() if not directory: break @@ -908,9 +912,7 @@ class KnowledgeTable: async with get_async_db_context(db) as db: try: await db.execute( - update(KnowledgeDirectory) - .filter_by(id=directory_id) - .values(name=name, updated_at=int(time.time())) + update(KnowledgeDirectory).filter_by(id=directory_id).values(name=name, updated_at=int(time.time())) ) await db.commit() return await self.get_directory_by_id(directory_id, db=db) @@ -936,9 +938,7 @@ class KnowledgeTable: if current == directory_id: return None # Would create a cycle seen.add(current) - result = await db.execute( - select(KnowledgeDirectory.parent_id).filter_by(id=current) - ) + result = await db.execute(select(KnowledgeDirectory.parent_id).filter_by(id=current)) row = result.first() current = row[0] if row else None @@ -986,9 +986,7 @@ class KnowledgeTable: async with get_async_db_context(db) as db: try: # Get the directory to find its parent - result = await db.execute( - select(KnowledgeDirectory).filter_by(id=directory_id) - ) + result = await db.execute(select(KnowledgeDirectory).filter_by(id=directory_id)) directory = result.scalars().first() if not directory: return False @@ -998,9 +996,7 @@ class KnowledgeTable: if move_files_to_parent: # Move files in this directory to its parent (or root) await db.execute( - update(KnowledgeFile) - .filter_by(directory_id=directory_id) - .values(directory_id=parent_id) + update(KnowledgeFile).filter_by(directory_id=directory_id).values(directory_id=parent_id) ) # Recursively move files from all subdirectories too await self._move_files_from_subtree(directory_id, parent_id, db=db) @@ -1009,9 +1005,7 @@ class KnowledgeTable: await self._delete_files_in_subtree(directory_id, db=db) # CASCADE on parent_id will handle deleting subdirectories - await db.execute( - delete(KnowledgeDirectory).filter_by(id=directory_id) - ) + await db.execute(delete(KnowledgeDirectory).filter_by(id=directory_id)) await db.commit() return True except Exception as e: @@ -1025,16 +1019,12 @@ class KnowledgeTable: db: AsyncSession, ) -> None: """Recursively move all files from a directory subtree to the target.""" - result = await db.execute( - select(KnowledgeDirectory.id).filter_by(parent_id=directory_id) - ) + result = await db.execute(select(KnowledgeDirectory.id).filter_by(parent_id=directory_id)) child_ids = [row[0] for row in result.all()] for child_id in child_ids: await db.execute( - update(KnowledgeFile) - .filter_by(directory_id=child_id) - .values(directory_id=target_directory_id) + update(KnowledgeFile).filter_by(directory_id=child_id).values(directory_id=target_directory_id) ) await self._move_files_from_subtree(child_id, target_directory_id, db=db) @@ -1044,12 +1034,8 @@ class KnowledgeTable: db: AsyncSession, ) -> None: """Recursively delete all files from a directory subtree.""" - await db.execute( - delete(KnowledgeFile).filter_by(directory_id=directory_id) - ) - result = await db.execute( - select(KnowledgeDirectory.id).filter_by(parent_id=directory_id) - ) + await db.execute(delete(KnowledgeFile).filter_by(directory_id=directory_id)) + result = await db.execute(select(KnowledgeDirectory.id).filter_by(parent_id=directory_id)) child_ids = [row[0] for row in result.all()] for child_id in child_ids: await self._delete_files_in_subtree(child_id, db=db) diff --git a/backend/open_webui/models/memories.py b/backend/open_webui/models/memories.py index d7f51e2c9e..2337371f12 100644 --- a/backend/open_webui/models/memories.py +++ b/backend/open_webui/models/memories.py @@ -1,3 +1,5 @@ +"""Long-term memory storage for per-user context recall.""" + from __future__ import annotations import time @@ -9,36 +11,28 @@ from pydantic import BaseModel, ConfigDict from sqlalchemy import BigInteger, Column, String, Text, delete, select from sqlalchemy.ext.asyncio import AsyncSession -#################### -# Memory DB Schema -# What was learned at cost should not need to be paid -# for again. Let the memory hold. -#################### +class Memory(Base): # user memory store + """Stores user-created memory entries linked to a vector collection.""" -class Memory(Base): __tablename__ = 'memory' id = Column(String, primary_key=True, unique=True) user_id = Column(String, index=True) - content = Column(Text) - updated_at = Column(BigInteger) - created_at = Column(BigInteger) + content = Column(Text) # free-form text learned from conversation + updated_at = Column(BigInteger) # epoch seconds + created_at = Column(BigInteger) # epoch seconds class MemoryModel(BaseModel): + """Pydantic mirror of the Memory table row.""" + id: str user_id: str content: str updated_at: int # timestamp in epoch created_at: int # timestamp in epoch - - model_config = ConfigDict(from_attributes=True) - - -#################### -# Forms -#################### + model_config = ConfigDict(from_attributes=True) # allows ORM mapping class MemoriesTable: @@ -48,26 +42,20 @@ class MemoriesTable: content: str, db: AsyncSession | None = None, ) -> MemoryModel | None: + """Persist a new memory entry and return the created model.""" async with get_async_db_context(db) as db: - id = str(uuid.uuid4()) - - memory = MemoryModel( - **{ - 'id': id, - 'user_id': user_id, - 'content': content, - 'created_at': int(time.time()), - 'updated_at': int(time.time()), - } + now = int(time.time()) + record = Memory( + id=str(uuid.uuid4()), + user_id=user_id, + content=content, + created_at=now, + updated_at=now, ) - result = Memory(**memory.model_dump()) - db.add(result) + db.add(record) await db.commit() - await db.refresh(result) - if result: - return MemoryModel.model_validate(result) - else: - return None + await db.refresh(record) + return MemoryModel.model_validate(record) if record else None async def update_memory_by_id_and_user_id( self, @@ -143,15 +131,13 @@ class MemoriesTable: try: memory = await db.get(Memory, id) if not memory or memory.user_id != user_id: - return None + return False - # Delete the memory await db.delete(memory) await db.commit() - return True except Exception: return False -Memories = MemoriesTable() +Memories = MemoriesTable() # user memory registry diff --git a/backend/open_webui/models/models.py b/backend/open_webui/models/models.py index 443cd4530d..0fab100c46 100755 --- a/backend/open_webui/models/models.py +++ b/backend/open_webui/models/models.py @@ -9,40 +9,53 @@ from open_webui.internal.db import Base, JSONField, get_async_db_context from open_webui.models.access_grants import AccessGrantModel, AccessGrants from open_webui.models.groups import Groups from open_webui.models.users import User, UserModel, UserResponse, Users -from pydantic import BaseModel, ConfigDict, Field, model_validator +from open_webui.utils.validate import validate_profile_image_url +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from sqlalchemy import BigInteger, Boolean, Column, String, Text, cast, delete, func, or_, select, update from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) - -#################### -# Models DB Schema -# A misconfigured model wastes the time of everyone -# who trusts it. Let what is set here be set with care. -#################### +# Track invalid profile_image_url values we've already warned about so we +# don't flood the logs on every DB read (the validator fires per-row). +_warned_profile_urls: set[str] = set() + + +# --- Models DB Schema --- -# ModelParams is a model for the data stored in the params field of the Model table class ModelParams(BaseModel): + """Parameters for model inference (temperature, top_p, etc.).""" + model_config = ConfigDict(extra='allow') - pass -# ModelMeta is a model for the data stored in the meta field of the Model table class ModelMeta(BaseModel): - profile_image_url: str | None = '/static/favicon.png' - - description: str | None = None - """ - User-facing description of the model. - """ + """Metadata for a workspace model entry (profile, description, tags, capabilities).""" + profile_image_url: str | None = None + description: str | None = Field(default=None, description='User-facing description of the model.') capabilities: dict | None = None model_config = ConfigDict(extra='allow') + @field_validator('profile_image_url', mode='before') + @classmethod + def check_profile_image_url(cls, v: str | None) -> str | None: + if v is None: + return v + try: + return validate_profile_image_url(v) + except ValueError: + if v not in _warned_profile_urls: + _warned_profile_urls.add(v) + log.warning( + 'Clearing invalid profile_image_url stored in DB (likely a legacy SVG data-URI): %.80s…', + v, + ) + return None + @model_validator(mode='before') @classmethod def normalize_tags(cls, data): @@ -60,38 +73,19 @@ class ModelMeta(BaseModel): class Model(Base): + """Workspace model entry — wraps an upstream LLM with custom params and metadata.""" + __tablename__ = 'model' - id = Column(Text, primary_key=True, unique=True) - """ - The model's id as used in the API. If set to an existing model, it will override the model. - """ - user_id = Column(Text) - - base_model_id = Column(Text, nullable=True) - """ - An optional pointer to the actual model that should be used when proxying requests. - """ - - name = Column(Text) - """ - The human-readable display name of the model. - """ - - params = Column(JSONField) - """ - Holds a JSON encoded blob of parameters, see `ModelParams`. - """ - - meta = Column(JSONField) - """ - Holds a JSON encoded blob of metadata, see `ModelMeta`. - """ - - is_active = Column(Boolean, default=True) - - updated_at = Column(BigInteger) - created_at = Column(BigInteger) + id = Column(Text, primary_key=True, unique=True) # API model identifier; overrides built-in when matching + user_id = Column(Text) # owner + base_model_id = Column(Text, nullable=True) # actual upstream model for proxied requests + name = Column(Text) # human-readable display name + params = Column(JSONField) # see ModelParams + meta = Column(JSONField) # see ModelMeta + is_active = Column(Boolean, default=True) # soft-disable toggle + updated_at = Column(BigInteger) # epoch seconds + created_at = Column(BigInteger) # epoch seconds class ModelModel(BaseModel): @@ -109,12 +103,9 @@ class ModelModel(BaseModel): updated_at: int # timestamp in epoch created_at: int # timestamp in epoch - model_config = ConfigDict(from_attributes=True) - - -#################### -# Forms -#################### + model_config = ConfigDict( + from_attributes=True, + ) class ModelUserResponse(ModelModel): @@ -199,10 +190,13 @@ class ModelsTable: all_models = result.scalars().all() model_ids = [model.id for model in all_models] grants_map = await AccessGrants.get_grants_by_resources('model', model_ids, db=db) - return [ - await self._to_model_model(model, access_grants=grants_map.get(model.id, []), db=db) - for model in all_models - ] + models: list[ModelModel] = [] + for model in all_models: + try: + models.append(await self._to_model_model(model, access_grants=grants_map.get(model.id, []), db=db)) + except Exception as exc: + log.error('Skipping model %r during get_all_models due to error: %s', model.id, exc) + return models async def get_models(self, db: AsyncSession | None = None) -> list[ModelUserResponse]: async with get_async_db_context(db) as db: @@ -595,4 +589,4 @@ class ModelsTable: return [] -Models = ModelsTable() +Models = ModelsTable() # singleton model registry diff --git a/backend/open_webui/models/prompt_history.py b/backend/open_webui/models/prompt_history.py index a73032c4bb..bb27657032 100644 --- a/backend/open_webui/models/prompt_history.py +++ b/backend/open_webui/models/prompt_history.py @@ -151,13 +151,19 @@ class PromptHistoryTable: self, from_id: str, to_id: str, + prompt_id: str, db: Optional[AsyncSession] = None, ) -> Optional[dict]: """Compute diff between two history entries.""" async with get_async_db_context(db) as db: - result_from = await db.execute(select(PromptHistory).filter(PromptHistory.id == from_id)) + # Bind both entries to the authorized prompt; an unbound id reads another prompt's snapshot. + result_from = await db.execute( + select(PromptHistory).filter(PromptHistory.id == from_id, PromptHistory.prompt_id == prompt_id) + ) from_entry = result_from.scalars().first() - result_to = await db.execute(select(PromptHistory).filter(PromptHistory.id == to_id)) + result_to = await db.execute( + select(PromptHistory).filter(PromptHistory.id == to_id, PromptHistory.prompt_id == prompt_id) + ) to_entry = result_to.scalars().first() if not from_entry or not to_entry: @@ -203,11 +209,13 @@ class PromptHistoryTable: async def delete_history_entry( self, history_id: str, + prompt_id: str, db: Optional[AsyncSession] = None, ) -> bool: """Delete a history entry and reparent its children to grandparent.""" async with get_async_db_context(db) as db: - result = await db.execute(select(PromptHistory).filter_by(id=history_id)) + # Bind to the authorized prompt; an unbound id deletes another prompt's history. + result = await db.execute(select(PromptHistory).filter_by(id=history_id, prompt_id=prompt_id)) entry = result.scalars().first() if not entry: return False diff --git a/backend/open_webui/models/prompts.py b/backend/open_webui/models/prompts.py index 732c868227..23a5017acf 100644 --- a/backend/open_webui/models/prompts.py +++ b/backend/open_webui/models/prompts.py @@ -1,10 +1,15 @@ +"""Prompt template models, forms, and database operations.""" + from __future__ import annotations import json +import logging import time import uuid from typing import Optional +log = logging.getLogger(__name__) + from open_webui.internal.db import Base, JSONField, get_async_db_context from open_webui.models.access_grants import AccessGrantModel, AccessGrants from open_webui.models.groups import Groups @@ -14,23 +19,19 @@ from pydantic import BaseModel, ConfigDict, Field from sqlalchemy import JSON, BigInteger, Boolean, Column, String, Text, cast, delete, func, or_, select, text, update from sqlalchemy.ext.asyncio import AsyncSession -#################### -# Prompts DB Schema -# Every word here was weighed before it was set down. -# Let the weight not be wasted when it is spoken aloud. -#################### +class Prompt(Base): # versioned template + """Slash-command prompt with history tracking and access control.""" -class Prompt(Base): __tablename__ = 'prompt' id = Column(Text, primary_key=True) command = Column(String, unique=True, index=True) - user_id = Column(String) + user_id = Column(String, index=True) # owner user id name = Column(Text) - content = Column(Text) - data = Column(JSON, nullable=True) - meta = Column(JSON, nullable=True) + content = Column(Text) # the prompt template body + data = Column(JSON, nullable=True) # structured prompt parameters + meta = Column(JSON, nullable=True) # freeform metadata (description, etc.) tags = Column(JSON, nullable=True) is_active = Column(Boolean, default=True) version_id = Column(Text, nullable=True) # Points to active history entry @@ -53,10 +54,10 @@ class PromptModel(BaseModel): updated_at: int | None = None access_grants: list[AccessGrantModel] = Field(default_factory=list) - model_config = ConfigDict(from_attributes=True) + model_config = ConfigDict(from_attributes=True) # allows ORM model binding -#################### +# --- form / schema definitions --- # Forms #################### @@ -114,101 +115,112 @@ class PromptsTable: now = int(time.time()) prompt_id = str(uuid.uuid4()) - prompt = PromptModel( - id=prompt_id, - user_id=user_id, - command=form_data.command, - name=form_data.name, - content=form_data.content, - data=form_data.data or {}, - meta=form_data.meta or {}, - tags=form_data.tags or [], - access_grants=[], - is_active=True, - created_at=now, - updated_at=now, - ) + async with get_async_db_context(db) as session: + try: + record = Prompt( + id=prompt_id, + user_id=user_id, + command=form_data.command, + name=form_data.name, + content=form_data.content, + data=form_data.data or {}, + meta=form_data.meta or {}, + tags=form_data.tags or [], + is_active=True, + created_at=now, + updated_at=now, + ) + session.add(record) + await session.commit() + await session.refresh(record) # populate generated defaults - try: - async with get_async_db_context(db) as db: - result = Prompt(**prompt.model_dump(exclude={'access_grants'})) - db.add(result) - await db.commit() - await db.refresh(result) - await AccessGrants.set_access_grants('prompt', prompt_id, form_data.access_grants, db=db) + await AccessGrants.set_access_grants( + 'prompt', + prompt_id, + form_data.access_grants, + db=session, + ) # persist sharing rules - if result: - current_access_grants = await self._get_access_grants(prompt_id, db=db) - snapshot = { - 'name': form_data.name, - 'content': form_data.content, - 'command': form_data.command, - 'data': form_data.data or {}, - 'meta': form_data.meta or {}, - 'tags': form_data.tags or [], - 'access_grants': [grant.model_dump() for grant in current_access_grants], - } - - history_entry = await PromptHistories.create_history_entry( - prompt_id=prompt_id, - snapshot=snapshot, - user_id=user_id, - parent_id=None, # Initial commit has no parent - commit_message=form_data.commit_message or 'Initial version', - db=db, - ) - - # Set the initial version as the production version - if history_entry: - result.version_id = history_entry.id - await db.commit() - await db.refresh(result) - - return await self._to_prompt_model(result, db=db) - else: + if not record: # shouldn't happen, but guard anyway return None - except Exception: - return None + + # Build the initial version snapshot. + grants = await self._get_access_grants(prompt_id, db=session) + snapshot = { + 'name': form_data.name, + 'content': form_data.content, + 'command': form_data.command, + 'data': form_data.data or {}, + 'meta': form_data.meta or {}, + 'tags': form_data.tags or [], + 'access_grants': [g.model_dump() for g in grants], + } + + history_entry = await PromptHistories.create_history_entry( + prompt_id=prompt_id, + snapshot=snapshot, + user_id=user_id, + parent_id=None, + commit_message=form_data.commit_message or 'Initial version', + db=session, + ) # creates the first version entry + + # Pin the initial history entry as the production version. + if history_entry: + record.version_id = history_entry.id + await session.commit() + await session.refresh(record) # re-read version_id + + return await self._to_prompt_model(record, db=session) + except Exception as e: + log.exception('Error creating prompt: %s', e) + return None async def get_prompt_by_id(self, prompt_id: str, db: AsyncSession | None = None) -> PromptModel | None: - """Get prompt by UUID.""" try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(id=prompt_id)) - prompt = result.scalars().first() - if prompt: - return await self._to_prompt_model(prompt, db=db) - return None - except Exception: - return None + async with get_async_db_context(db) as session: + result = await session.execute( + select(Prompt).filter_by(id=prompt_id), + ) + prompt = result.scalars().first() # None when not found + if not prompt: + return None + return await self._to_prompt_model(prompt, db=session) + except Exception: # connection / integrity error + return async def get_prompt_by_command(self, command: str, db: AsyncSession | None = None) -> PromptModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(command=command)) - prompt = result.scalars().first() - if prompt: - return await self._to_prompt_model(prompt, db=db) - return None - except Exception: - return None + """Look up a prompt by its unique slash-command string.""" + async with get_async_db_context(db) as session: + match = (await session.execute(select(Prompt).where(Prompt.command == command))).scalars().first() + if match is None: + return + return await self._to_prompt_model(match, db=session) + # --- context manager always returns above --- + return async def get_prompts(self, db: AsyncSession | None = None) -> list[PromptUserResponse]: - async with get_async_db_context(db) as db: - result = await db.execute( - select(Prompt).filter(Prompt.is_active == True).order_by(Prompt.updated_at.desc()) + """Return all active prompts ordered by most recently updated.""" + async with get_async_db_context(db) as session: + active = ( + ( + await session.execute( + select(Prompt).where(Prompt.is_active.is_(True)).order_by(Prompt.updated_at.desc()) + ) + ) + .scalars() + .all() ) - all_prompts = result.scalars().all() - user_ids = list(set(prompt.user_id for prompt in all_prompts)) - prompt_ids = [prompt.id for prompt in all_prompts] + user_ids = list(set(p.user_id for p in active)) + prompt_ids = [p.id for p in active] - users = await Users.get_users_by_user_ids(user_ids, db=db) if user_ids else [] - users_dict = {user.id: user for user in users} - grants_map = await AccessGrants.get_grants_by_resources('prompt', prompt_ids, db=db) + users = await Users.get_users_by_user_ids(user_ids, db=session) if user_ids else [] + users_dict = {u.id: u for u in users} + grants_map = await AccessGrants.get_grants_by_resources('prompt', prompt_ids, db=session) prompts = [] - for prompt in all_prompts: + for prompt in active: user = users_dict.get(prompt.user_id) prompts.append( PromptUserResponse.model_validate( @@ -217,7 +229,7 @@ class PromptsTable: await self._to_prompt_model( prompt, access_grants=grants_map.get(prompt.id, []), - db=db, + db=session, ) ).model_dump(), 'user': user.model_dump() if user else None, @@ -230,8 +242,8 @@ class PromptsTable: async def get_prompts_by_user_id( self, user_id: str, permission: str = 'write', db: AsyncSession | None = None ) -> list[PromptUserResponse]: - async with get_async_db_context(db) as db: - user_groups = await Groups.get_groups_by_member_id(user_id, db=db) + async with get_async_db_context(db) as session: + user_groups = await Groups.get_groups_by_member_id(user_id, db=session) user_group_ids = [group.id for group in user_groups] query = select(Prompt).filter(Prompt.is_active == True).order_by(Prompt.updated_at.desc()) @@ -244,7 +256,7 @@ class PromptsTable: permission=permission, ) - result = await db.execute(query) + result = await session.execute(query) accessible_prompts = result.scalars().all() if not accessible_prompts: @@ -253,9 +265,9 @@ class PromptsTable: prompt_ids = [p.id for p in accessible_prompts] owner_ids = list({p.user_id for p in accessible_prompts}) - users = await Users.get_users_by_user_ids(owner_ids, db=db) + users = await Users.get_users_by_user_ids(owner_ids, db=session) users_dict = {u.id: u for u in users} - grants_map = await AccessGrants.get_grants_by_resources('prompt', prompt_ids, db=db) + grants_map = await AccessGrants.get_grants_by_resources('prompt', prompt_ids, db=session) results = [] for prompt in accessible_prompts: @@ -284,7 +296,7 @@ class PromptsTable: limit: int = 30, db: AsyncSession | None = None, ) -> PromptListResponse: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: # Join with User table for user filtering and sorting query = select(Prompt, User).outerjoin(User, User.id == Prompt.user_id) @@ -319,7 +331,7 @@ class PromptsTable: tag = filter.get('tag') if tag: - bind = await db.connection() + bind = await session.connection() dialect_name = bind.dialect.name tag_lower = tag.lower() @@ -367,7 +379,7 @@ class PromptsTable: query = query.order_by(Prompt.updated_at.desc()) # Count BEFORE pagination - count_result = await db.execute(select(func.count()).select_from(query.subquery())) + count_result = await session.execute(select(func.count()).select_from(query.subquery())) total = count_result.scalar() if skip: @@ -375,11 +387,11 @@ class PromptsTable: if limit: query = query.limit(limit) - result = await db.execute(query) + result = await session.execute(query) items = result.all() prompt_ids = [prompt.id for prompt, _ in items] - grants_map = await AccessGrants.get_grants_by_resources('prompt', prompt_ids, db=db) + grants_map = await AccessGrants.get_grants_by_resources('prompt', prompt_ids, db=session) prompts = [] for prompt, user in items: @@ -405,16 +417,18 @@ class PromptsTable: user_id: str, db: AsyncSession | None = None, ) -> PromptModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(command=command)) + if not command: + return None + try: # database transaction + async with get_async_db_context(db) as session: + result = await session.execute(select(Prompt).filter_by(command=command)) prompt = result.scalars().first() if not prompt: return None - latest_history = await PromptHistories.get_latest_history_entry(prompt.id, db=db) + latest_history = await PromptHistories.get_latest_history_entry(prompt.id, db=session) parent_id = latest_history.id if latest_history else None - current_access_grants = await self._get_access_grants(prompt.id, db=db) + current_access_grants = await self._get_access_grants(prompt.id, db=session) # Check if content changed to decide on history creation content_changed = ( @@ -430,10 +444,10 @@ class PromptsTable: prompt.meta = form_data.meta or prompt.meta prompt.updated_at = int(time.time()) if form_data.access_grants is not None: - await AccessGrants.set_access_grants('prompt', prompt.id, form_data.access_grants, db=db) - current_access_grants = await self._get_access_grants(prompt.id, db=db) + await AccessGrants.set_access_grants('prompt', prompt.id, form_data.access_grants, db=session) + current_access_grants = await self._get_access_grants(prompt.id, db=session) - await db.commit() + await session.commit() # Create history entry only if content changed if content_changed: @@ -458,9 +472,9 @@ class PromptsTable: # Set as production if flag is True (default) if form_data.is_production and history_entry: prompt.version_id = history_entry.id - await db.commit() + await session.commit() - return await self._to_prompt_model(prompt, db=db) + return await self._to_prompt_model(prompt, db=session) except Exception: return None @@ -472,15 +486,15 @@ class PromptsTable: db: AsyncSession | None = None, ) -> PromptModel | None: try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(id=prompt_id)) + async with get_async_db_context(db) as session: + result = await session.execute(select(Prompt).filter_by(id=prompt_id)) prompt = result.scalars().first() if not prompt: return None - latest_history = await PromptHistories.get_latest_history_entry(prompt.id, db=db) + latest_history = await PromptHistories.get_latest_history_entry(prompt.id, db=session) parent_id = latest_history.id if latest_history else None - current_access_grants = await self._get_access_grants(prompt.id, db=db) + current_access_grants = await self._get_access_grants(prompt.id, db=session) # Check if content changed to decide on history creation content_changed = ( @@ -502,12 +516,12 @@ class PromptsTable: prompt.tags = form_data.tags if form_data.access_grants is not None: - await AccessGrants.set_access_grants('prompt', prompt.id, form_data.access_grants, db=db) - current_access_grants = await self._get_access_grants(prompt.id, db=db) + await AccessGrants.set_access_grants('prompt', prompt.id, form_data.access_grants, db=session) + current_access_grants = await self._get_access_grants(prompt.id, db=session) prompt.updated_at = int(time.time()) - await db.commit() + await session.commit() # Create history entry only if content changed if content_changed: @@ -533,9 +547,9 @@ class PromptsTable: # Set as production if flag is True (default) if form_data.is_production and history_entry: prompt.version_id = history_entry.id - await db.commit() + await session.commit() - return await self._to_prompt_model(prompt, db=db) + return await self._to_prompt_model(prompt, db=session) except Exception: return None @@ -549,8 +563,8 @@ class PromptsTable: ) -> PromptModel | None: """Update only name, command, and tags (no history created).""" try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(id=prompt_id)) + async with get_async_db_context(db) as session: + result = await session.execute(select(Prompt).filter_by(id=prompt_id)) prompt = result.scalars().first() if not prompt: return None @@ -562,9 +576,9 @@ class PromptsTable: prompt.tags = tags prompt.updated_at = int(time.time()) - await db.commit() + await session.commit() - return await self._to_prompt_model(prompt, db=db) + return await self._to_prompt_model(prompt, db=session) except Exception: return None @@ -576,15 +590,16 @@ class PromptsTable: ) -> PromptModel | None: """Set the active version of a prompt and restore content from that version's snapshot.""" try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(id=prompt_id)) + async with get_async_db_context(db) as session: + result = await session.execute(select(Prompt).filter_by(id=prompt_id)) prompt = result.scalars().first() if not prompt: return None - history_entry = await PromptHistories.get_history_entry_by_id(version_id, db=db) + history_entry = await PromptHistories.get_history_entry_by_id(version_id, db=session) - if not history_entry: + # Reject a version_id from another prompt; restoring it would copy a foreign snapshot in. + if not history_entry or history_entry.prompt_id != prompt_id: return None # Restore prompt content from the snapshot @@ -599,24 +614,31 @@ class PromptsTable: prompt.version_id = version_id prompt.updated_at = int(time.time()) - await db.commit() + await session.commit() - return await self._to_prompt_model(prompt, db=db) - except Exception: + return await self._to_prompt_model(prompt, db=session) + except Exception as e: # connection error + log.error(f'Failed to restore prompt version: {e}') + return None # restoration failed + + async def toggle_prompt_active( + self, + prompt_id: str, + db: AsyncSession | None = None, + ) -> PromptModel | None: + """Flip the is_active flag on a prompt.""" + if not prompt_id: return None - - async def toggle_prompt_active(self, prompt_id: str, db: AsyncSession | None = None) -> PromptModel | None: - """Toggle the is_active flag on a prompt.""" - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(id=prompt_id)) + try: # activation state toggle + async with get_async_db_context(db) as session: + result = await session.execute(select(Prompt).filter_by(id=prompt_id)) prompt = result.scalars().first() if prompt: prompt.is_active = not prompt.is_active prompt.updated_at = int(time.time()) - await db.commit() - await db.refresh(prompt) - return await self._to_prompt_model(prompt, db=db) + await session.commit() + await session.refresh(prompt) + return await self._to_prompt_model(prompt, db=session) return None except Exception: return None @@ -624,15 +646,15 @@ class PromptsTable: async def delete_prompt_by_command(self, command: str, db: AsyncSession | None = None) -> bool: """Permanently delete a prompt and its history.""" try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(command=command)) + async with get_async_db_context(db) as session: + result = await session.execute(select(Prompt).filter_by(command=command)) prompt = result.scalars().first() if prompt: - await PromptHistories.delete_history_by_prompt_id(prompt.id, db=db) - await AccessGrants.revoke_all_access('prompt', prompt.id, db=db) + await PromptHistories.delete_history_by_prompt_id(prompt.id, db=session) + await AccessGrants.revoke_all_access('prompt', prompt.id, db=session) - await db.delete(prompt) - await db.commit() + await session.delete(prompt) + await session.commit() return True return False except Exception: @@ -641,24 +663,25 @@ class PromptsTable: async def delete_prompt_by_id(self, prompt_id: str, db: AsyncSession | None = None) -> bool: """Permanently delete a prompt and its history.""" try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt).filter_by(id=prompt_id)) + async with get_async_db_context(db) as session: + result = await session.execute(select(Prompt).filter_by(id=prompt_id)) prompt = result.scalars().first() if prompt: - await PromptHistories.delete_history_by_prompt_id(prompt.id, db=db) - await AccessGrants.revoke_all_access('prompt', prompt.id, db=db) + await PromptHistories.delete_history_by_prompt_id(prompt.id, db=session) + await AccessGrants.revoke_all_access('prompt', prompt.id, db=session) - await db.delete(prompt) - await db.commit() + await session.delete(prompt) + await session.commit() return True return False - except Exception: - return False + except Exception as err: + log.error(f'Failed to delete prompt: {err}') + return False # deletion failed async def get_tags(self, db: AsyncSession | None = None) -> list[str]: try: - async with get_async_db_context(db) as db: - result = await db.execute(select(Prompt.tags).filter(Prompt.is_active == True)) + async with get_async_db_context(db) as session: + result = await session.execute(select(Prompt.tags).filter(Prompt.is_active == True)) tags = set() for (tag_list,) in result.all(): if tag_list: @@ -671,8 +694,8 @@ class PromptsTable: async def get_tags_by_user_id(self, user_id: str, db: AsyncSession | None = None) -> list[str]: try: - async with get_async_db_context(db) as db: - user_groups = await Groups.get_groups_by_member_id(user_id, db=db) + async with get_async_db_context(db) as session: + user_groups = await Groups.get_groups_by_member_id(user_id, db=session) user_group_ids = [group.id for group in user_groups] query = select(Prompt.tags).filter(Prompt.is_active == True) @@ -685,7 +708,7 @@ class PromptsTable: permission='read', ) - result = await db.execute(query) + result = await session.execute(query) tags = set() for (tag_list,) in result.all(): if tag_list: @@ -697,4 +720,4 @@ class PromptsTable: return [] -Prompts = PromptsTable() +Prompts = PromptsTable() # singleton prompts registry diff --git a/backend/open_webui/models/tags.py b/backend/open_webui/models/tags.py index defd424d59..87f6bac7e3 100644 --- a/backend/open_webui/models/tags.py +++ b/backend/open_webui/models/tags.py @@ -1,10 +1,12 @@ +"""Tag models and database operations.""" + from __future__ import annotations import logging import time import uuid -from typing import Optional +# local imports from open_webui.internal.db import Base, JSONField, get_async_db_context from pydantic import BaseModel, ConfigDict from sqlalchemy import JSON, BigInteger, Column, Index, PrimaryKeyConstraint, String, delete, select @@ -13,16 +15,11 @@ from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) -#################### -# Tag DB Schema -# To name a thing is to claim it. The creator has -# already named everything stored in this table. -#################### -class Tag(Base): +class Tag(Base): # database table mapping for tag entity __tablename__ = 'tag' id = Column(String) - name = Column(String) - user_id = Column(String) + name = Column(String, index=True) # tag label + user_id = Column(String, index=True) # user identifier meta = Column(JSON, nullable=True) __table_args__ = ( @@ -39,10 +36,10 @@ class TagModel(BaseModel): name: str user_id: str meta: dict | None = None - model_config = ConfigDict(from_attributes=True) + model_config = ConfigDict(from_attributes=True) # allows ORM model binding -#################### +# --- tag schema forms --- # Forms #################### @@ -53,22 +50,24 @@ class TagChatIdForm(BaseModel): class TagTable: - async def insert_new_tag(self, name: str, user_id: str, db: AsyncSession | None = None) -> TagModel | None: + async def insert_new_tag( + self, + name: str, + user_id: str, + db: AsyncSession | None = None, + ) -> TagModel | None: + """Create a new tag, deriving the id from the name.""" async with get_async_db_context(db) as db: - id = name.replace(' ', '_').lower() - tag = TagModel(**{'id': id, 'user_id': user_id, 'name': name}) + tag_id = name.replace(' ', '_').lower() try: - result = Tag(**tag.model_dump()) - db.add(result) + record = Tag(id=tag_id, user_id=user_id, name=name) + db.add(record) await db.commit() - await db.refresh(result) - if result: - return TagModel.model_validate(result) - else: - return None + await db.refresh(record) + return TagModel.model_validate(record) if record else None except Exception as e: - log.exception(f'Error inserting a new tag: {e}') - return None + log.exception('Error inserting tag %r: %s', name, e) + return None # insertion failed async def get_tag_by_name_and_user_id( self, name: str, user_id: str, db: AsyncSession | None = None @@ -137,4 +136,4 @@ class TagTable: await db.commit() -Tags = TagTable() +Tags = TagTable() # singleton tag repository diff --git a/backend/open_webui/models/tools.py b/backend/open_webui/models/tools.py index 9a1a202292..d575cc1439 100644 --- a/backend/open_webui/models/tools.py +++ b/backend/open_webui/models/tools.py @@ -1,9 +1,11 @@ +"""Tool models, forms, and database operations.""" + from __future__ import annotations import logging import time -from typing import Optional +# local imports from open_webui.internal.db import Base, JSONField, get_async_db_context from open_webui.models.access_grants import AccessGrantModel, AccessGrants from open_webui.models.groups import Groups @@ -14,26 +16,20 @@ from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) -#################### -# Tools DB Schema -# A tool that fails silently is worse than one that -# refuses outright. Let each one here be honest in its work. -#################### - -class Tool(Base): +class Tool(Base): # database table definition __tablename__ = 'tool' id = Column(String, primary_key=True, unique=True) - user_id = Column(String) - name = Column(Text) - content = Column(Text) - specs = Column(JSONField) - meta = Column(JSONField) - valves = Column(JSONField) + user_id = Column(String, index=True) # owner user id + name = Column(Text) # human-readable label + content = Column(Text) # Python source code + specs = Column(JSONField) # OpenAPI-style function specs + meta = Column(JSONField) # description, manifest, etc. + valves = Column(JSONField) # admin-configurable runtime parameters - updated_at = Column(BigInteger) - created_at = Column(BigInteger) + updated_at = Column(BigInteger, nullable=False) # modification timestamp + created_at = Column(BigInteger, index=True) # creation timestamp class ToolMeta(BaseModel): @@ -53,10 +49,10 @@ class ToolModel(BaseModel): updated_at: int # timestamp in epoch created_at: int # timestamp in epoch - model_config = ConfigDict(from_attributes=True) + model_config = ConfigDict(from_attributes=True) # enables ORM mapping -#################### +# --- tool request forms --- # Forms #################### @@ -141,16 +137,36 @@ class ToolsTable: return None except Exception as e: log.exception(f'Error creating a new tool: {e}') - return None + return None # creation failed - async def get_tool_by_id(self, id: str, db: AsyncSession | None = None) -> ToolModel | None: - try: - async with get_async_db_context(db) as db: - tool = await db.get(Tool, id) - return await self._to_tool_model(tool, db=db) if tool else None + async def get_tool_by_id( + self, + id: str, + db: AsyncSession | None = None, + ) -> ToolModel | None: + """Fetch a single tool by primary key, including access grants.""" + try: # single PK lookup + access grants + async with get_async_db_context(db) as session: + tool = await session.get(Tool, id) + if not tool: + return None + return await self._to_tool_model(tool, db=session) except Exception: return None + async def get_tools_by_ids(self, tool_ids: list[str], db: AsyncSession | None = None) -> dict[str, ToolModel]: + """Batch-fetch multiple tools by ID, returning a dict keyed by tool ID.""" + if not tool_ids: + return {} + async with get_async_db_context(db) as db: + result = await db.execute(select(Tool).where(Tool.id.in_(tool_ids))) + tools = result.scalars().all() + grants_map = await AccessGrants.get_grants_by_resources('tool', [tool.id for tool in tools], db=db) + return { + tool.id: await self._to_tool_model(tool, access_grants=grants_map.get(tool.id, []), db=db) + for tool in tools + } + async def get_tools(self, defer_content: bool = False, db: AsyncSession | None = None) -> list[ToolUserModel]: async with get_async_db_context(db) as db: stmt = select(Tool).order_by(Tool.updated_at.desc()) @@ -299,4 +315,4 @@ class ToolsTable: return False -Tools = ToolsTable() +Tools = ToolsTable() # singleton tool registry diff --git a/backend/open_webui/models/users.py b/backend/open_webui/models/users.py index 56c3c21e63..bd64887ad8 100644 --- a/backend/open_webui/models/users.py +++ b/backend/open_webui/models/users.py @@ -1,9 +1,10 @@ +"""User models, Pydantic schemas, and database access layer.""" + from __future__ import annotations import datetime import time from typing import Optional - from open_webui.env import DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL from open_webui.internal.db import Base, JSONField, get_async_db_context from open_webui.utils.misc import throttle @@ -42,40 +43,45 @@ class UserSettings(BaseModel): pass -class User(Base): - __tablename__ = 'user' +class User(Base): # identity & profile + """One row per registered account — profile, role, and settings.""" - id = Column(String, primary_key=True, unique=True) - email = Column(String) - username = Column(String(50), nullable=True) - role = Column(String) + __tablename__: str = 'user' # Identity & Credentials + id = Column(String, primary_key=True, unique=True) # unique user id + email = Column(String, unique=True) # user email address + username = Column(String(50), nullable=True) # custom handle + role = Column(String, default='pending') # permissions role + name = Column(String, nullable=False) # display name - name = Column(String) - - profile_image_url = Column(Text) + # Profile + profile_image_url = Column(Text) # data-uri, path, or external URL profile_banner_image_url = Column(Text, nullable=True) - bio = Column(Text, nullable=True) gender = Column(Text, nullable=True) date_of_birth = Column(Date, nullable=True) timezone = Column(String, nullable=True) + # Online status presence_state = Column(String, nullable=True) status_emoji = Column(String, nullable=True) status_message = Column(Text, nullable=True) status_expires_at = Column(BigInteger, nullable=True) + # Metadata info = Column(JSON, nullable=True) settings = Column(JSON, nullable=True) - oauth = Column(JSON, nullable=True) scim = Column(JSON, nullable=True) + # Timestamps (epoch seconds) last_active_at = Column(BigInteger) updated_at = Column(BigInteger) created_at = Column(BigInteger) +_DEFAULT_PROFILE_IMAGE_URL = '/api/v1/users/{user_id}/profile/image' + + class UserModel(BaseModel): id: str @@ -108,12 +114,16 @@ class UserModel(BaseModel): updated_at: int # timestamp in epoch created_at: int # timestamp in epoch - model_config = ConfigDict(from_attributes=True) + model_config = ConfigDict( + from_attributes=True, + ) + # validation schema logic + # --- model validators --- @model_validator(mode='after') - def set_profile_image_url(self): - if not self.profile_image_url: - self.profile_image_url = f'/api/v1/users/{self.id}/profile/image' + def _ensure_profile_image(self) -> 'UserModel': + """Assign a generated avatar when no profile image is provided.""" + self.profile_image_url = self.profile_image_url or _DEFAULT_PROFILE_IMAGE_URL.format(user_id=self.id) return self @@ -269,7 +279,7 @@ class UsersTable: oauth: dict | None = None, db: AsyncSession | None = None, ) -> UserModel | None: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: user = UserModel( **{ 'id': id, @@ -285,79 +295,91 @@ class UsersTable: } ) result = User(**user.model_dump()) - db.add(result) - await db.commit() - await db.refresh(result) - if result: - return user - else: - return None + session.add(result) + await session.commit() + await session.refresh(result) + return user if result else None - async def get_user_by_id(self, id: str, db: AsyncSession | None = None) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - return UserModel.model_validate(user) if user else None - except Exception: - return None + # database read methods + # --- read / lookup operations --- + async def get_user_by_id( + self, + id: str, + db: AsyncSession | None = None, + ) -> UserModel | None: + """Fetch a single user by primary key.""" + async with get_async_db_context(db) as session: + user = await session.get(User, id) + return UserModel.model_validate(user) if user else None - async def get_user_by_api_key(self, api_key: str, db: AsyncSession | None = None) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute( - select(User).join(ApiKey, User.id == ApiKey.user_id).filter(ApiKey.key == api_key) - ) - user = result.scalars().first() - return UserModel.model_validate(user) if user else None - except Exception: - return None + # api key auth helper + async def get_user_by_api_key( + self, + api_key: str, + db: AsyncSession | None = None, + ) -> UserModel | None: + """Resolve a user from their API key via a JOIN on the api_key table.""" + async with get_async_db_context(db) as session: + result = await session.execute( + select(User).join(ApiKey, User.id == ApiKey.user_id).where(ApiKey.key == api_key), + ) + user = result.scalars().first() + return UserModel.model_validate(user) if user else None - async def get_user_by_email(self, email: str, db: AsyncSession | None = None) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter(func.lower(User.email) == email.lower())) - user = result.scalars().first() - return UserModel.model_validate(user) if user else None - except Exception: - return None + async def get_user_by_email( + self, + email: str, + db: AsyncSession | None = None, + ) -> UserModel | None: + """Case-insensitive email lookup using SQL lower().""" + async with get_async_db_context(db) as session: + email_filter = func.lower(User.email) == email.lower() + query = select(User).where(email_filter) + match = (await session.execute(query)).scalars().first() + if match is None: + return + return UserModel.model_validate(match) + # --- context manager above always returns --- + return - async def get_user_by_oauth_sub(self, provider: str, sub: str, db: AsyncSession | None = None) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - dialect_name = db.bind.dialect.name - - stmt = select(User) - if dialect_name == 'sqlite': - stmt = stmt.filter(User.oauth.contains({provider: {'sub': sub}})) - elif dialect_name == 'postgresql': - stmt = stmt.filter(User.oauth[provider].cast(JSONB)['sub'].astext == sub) - - result = await db.execute(stmt) - user = result.scalars().first() - return UserModel.model_validate(user) if user else None - except Exception as e: - # You may want to log the exception here - return None + # --- oauth & integrations --- + async def get_user_by_oauth_sub( + self, + provider: str, + sub: str, + db: AsyncSession | None = None, + ) -> UserModel | None: + """Look up a user by OAuth provider + subject claim (dialect-aware JSON filter).""" + async with get_async_db_context(db) as session: + dialect = session.bind.dialect.name + query = select(User) + if dialect == 'sqlite': + oauth_match = User.oauth.contains({provider: {'sub': sub}}) + query = query.where(oauth_match) + elif dialect == 'postgresql': + oauth_match = User.oauth[provider].cast(JSONB)['sub'].astext == sub + query = query.where(oauth_match) + row = (await session.execute(query)).scalars().first() + return UserModel.model_validate(row) if row else None async def get_user_by_scim_external_id( - self, provider: str, external_id: str, db: AsyncSession | None = None + self, + provider: str, + external_id: str, + db: AsyncSession | None = None, ) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - dialect_name = db.bind.dialect.name - - stmt = select(User) - if dialect_name == 'sqlite': - stmt = stmt.filter(User.scim.contains({provider: {'external_id': external_id}})) - elif dialect_name == 'postgresql': - stmt = stmt.filter(User.scim[provider].cast(JSONB)['external_id'].astext == external_id) - - result = await db.execute(stmt) - user = result.scalars().first() - return UserModel.model_validate(user) if user else None - except Exception: - return None + """Look up a user by SCIM provider + external ID (dialect-aware JSON filter).""" + async with get_async_db_context(db) as session: + dialect = session.bind.dialect.name + query = select(User) + if dialect == 'sqlite': + scim_match = User.scim.contains({provider: {'external_id': external_id}}) + query = query.where(scim_match) + elif dialect == 'postgresql': + scim_match = User.scim[provider].cast(JSONB)['external_id'].astext == external_id + query = query.where(scim_match) + row = (await session.execute(query)).scalars().first() + return UserModel.model_validate(row) if row else None async def get_users( self, @@ -366,8 +388,9 @@ class UsersTable: limit: int | None = None, db: AsyncSession | None = None, ) -> dict: - async with get_async_db_context(db) as db: - # Import here to avoid circular imports + """Paginated user listing with optional filters for role, group, and channel.""" + async with get_async_db_context(db) as session: + # Deferred imports to avoid circular dependencies from open_webui.models.channels import ChannelMember from open_webui.models.groups import GroupMember @@ -487,7 +510,7 @@ class UsersTable: stmt = stmt.order_by(User.created_at.desc()) # Count BEFORE pagination - count_result = await db.execute(select(func.count()).select_from(stmt.subquery())) + count_result = await session.execute(select(func.count()).select_from(stmt.subquery())) total = count_result.scalar() # correct pagination logic @@ -496,7 +519,7 @@ class UsersTable: if limit is not None: stmt = stmt.limit(limit) - result = await db.execute(stmt) + result = await session.execute(stmt) users = result.scalars().all() return { 'users': [UserModel.model_validate(user) for user in users], @@ -504,150 +527,114 @@ class UsersTable: } async def get_users_by_group_id(self, group_id: str, db: AsyncSession | None = None) -> list[UserModel]: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: from open_webui.models.groups import GroupMember - result = await db.execute( + result = await session.execute( select(User).join(GroupMember, User.id == GroupMember.user_id).filter(GroupMember.group_id == group_id) ) users = result.scalars().all() return [UserModel.model_validate(user) for user in users] async def get_users_by_user_ids(self, user_ids: list[str], db: AsyncSession | None = None) -> list[UserStatusModel]: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter(User.id.in_(user_ids))) + async with get_async_db_context(db) as session: + result = await session.execute(select(User).filter(User.id.in_(user_ids))) users = result.scalars().all() return [UserModel.model_validate(user) for user in users] + # count registered accounts async def get_num_users(self, db: AsyncSession | None = None) -> int | None: - async with get_async_db_context(db) as db: - result = await db.execute(select(func.count()).select_from(User)) + async with get_async_db_context(db) as session: + result = await session.execute(select(func.count()).select_from(User)) return result.scalar() + # check user existence async def has_users(self, db: AsyncSession | None = None) -> bool: - async with get_async_db_context(db) as db: - result = await db.execute(select(exists(select(User)))) + async with get_async_db_context(db) as session: + result = await session.execute(select(exists(select(User)))) return result.scalar() - async def get_first_user(self, db: AsyncSession | None = None) -> UserModel: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).order_by(User.created_at).limit(1)) - user = result.scalars().first() - return UserModel.model_validate(user) if user else None - except Exception: - return None + async def get_first_user(self, db: AsyncSession | None = None) -> UserModel | None: + """Return the earliest-created user (bootstrap admin detection).""" + async with get_async_db_context(db) as session: + stmt = select(User).order_by(User.created_at).limit(1) + row = (await session.execute(stmt)).scalars().first() + return UserModel.model_validate(row) if row else None async def get_user_webhook_url_by_id(self, id: str, db: AsyncSession | None = None) -> str | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - - if user.settings is None: - return None - else: - return user.settings.get('ui', {}).get('notifications', {}).get('webhook_url', None) - except Exception: + async with get_async_db_context(db) as session: + user = await session.get(User, id) + if user and user.settings: + return user.settings.get('ui', {}).get('notifications', {}).get('webhook_url', None) return None async def get_num_users_active_today(self, db: AsyncSession | None = None) -> int | None: - async with get_async_db_context(db) as db: - current_timestamp = int(datetime.datetime.now().timestamp()) + async with get_async_db_context(db) as session: + current_timestamp = int(time.time()) today_midnight_timestamp = current_timestamp - (current_timestamp % 86400) - result = await db.execute( - select(func.count()).select_from(User).filter(User.last_active_at > today_midnight_timestamp) + result = await session.execute( + select(func.count()).select_from(User).where(User.last_active_at > today_midnight_timestamp) ) return result.scalar() async def update_user_role_by_id(self, id: str, role: str, db: AsyncSession | None = None) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - if not user: - return None - user.role = role - await db.commit() - await db.refresh(user) - return UserModel.model_validate(user) - except Exception: - return None + async with get_async_db_context(db) as session: + user = await session.get(User, id) + if not user: + return None + user.role = role + await session.commit() + await session.refresh(user) + return UserModel.model_validate(user) async def update_user_status_by_id( self, id: str, form_data: UserStatus, db: AsyncSession | None = None ) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - if not user: - return None - for key, value in form_data.model_dump(exclude_none=True).items(): - setattr(user, key, value) - await db.commit() - await db.refresh(user) - return UserModel.model_validate(user) - except Exception: - return None + async with get_async_db_context(db) as session: + user = await session.get(User, id) + if not user: + return None + for key, value in form_data.model_dump(exclude_none=True).items(): + setattr(user, key, value) + await session.commit() + await session.refresh(user) + return UserModel.model_validate(user) async def update_user_profile_image_url_by_id( - self, id: str, profile_image_url: str, db: AsyncSession | None = None + self, + id: str, + profile_image_url: str, + db: AsyncSession | None = None, ) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - if not user: - return None - user.profile_image_url = profile_image_url - await db.commit() - await db.refresh(user) - return UserModel.model_validate(user) - except Exception: - return None + async with get_async_db_context(db) as session: + user = await session.get(User, id) + if user is None: + return None + user.profile_image_url = profile_image_url + await session.commit() + await session.refresh(user) + return UserModel.model_validate(user) @throttle(DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL) async def update_last_active_by_id(self, id: str, db: AsyncSession | None = None) -> None: - try: - async with get_async_db_context(db) as db: - await db.execute(update(User).filter_by(id=id).values(last_active_at=int(time.time()))) - await db.commit() - except Exception: - pass + async with get_async_db_context(db) as session: + await session.execute(update(User).where(User.id == id).values(last_active_at=int(time.time()))) + await session.commit() async def update_user_oauth_by_id( self, id: str, provider: str, sub: str, db: AsyncSession | None = None ) -> UserModel | None: - """ - Update or insert an OAuth provider/sub pair into the user's oauth JSON field. - Example resulting structure: - { - "google": { "sub": "123" }, - "github": { "sub": "abc" } - } - """ - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - if not user: - return None - - # Load existing oauth JSON or create empty - oauth = user.oauth or {} - - # Update or insert provider entry - oauth[provider] = {'sub': sub} - - # Persist updated JSON - await db.execute(update(User).filter_by(id=id).values(oauth=oauth)) - await db.commit() - - return UserModel.model_validate(user) - - except Exception: - return None + """Update or insert an OAuth provider/sub pair into the user's oauth JSON field.""" + async with get_async_db_context(db) as session: + user = await session.get(User, id) + if not user: + return None + oauth = dict(user.oauth or {}) + oauth[provider] = {'sub': sub} + user.oauth = oauth + await session.commit() + await session.refresh(user) + return UserModel.model_validate(user) async def update_user_scim_by_id( self, @@ -656,157 +643,102 @@ class UsersTable: external_id: str, db: AsyncSession | None = None, ) -> UserModel | None: - """ - Update or insert a SCIM provider/external_id pair into the user's scim JSON field. - Example resulting structure: - { - "microsoft": { "external_id": "abc" }, - "okta": { "external_id": "def" } - } - """ - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - if not user: - return None - - scim = user.scim or {} - scim[provider] = {'external_id': external_id} - - await db.execute(update(User).filter_by(id=id).values(scim=scim)) - await db.commit() - - return UserModel.model_validate(user) - - except Exception: - return None + """Update or insert a SCIM provider/external_id pair into the user's scim JSON field.""" + async with get_async_db_context(db) as session: + user = await session.get(User, id) + if not user: + return None + scim = dict(user.scim or {}) + scim[provider] = {'external_id': external_id} + user.scim = scim + await session.commit() + await session.refresh(user) + return UserModel.model_validate(user) async def update_user_by_id(self, id: str, updated: dict, db: AsyncSession | None = None) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - if not user: - return None - for key, value in updated.items(): - setattr(user, key, value) - await db.commit() - await db.refresh(user) - return UserModel.model_validate(user) - except Exception as e: - print(e) - return None + async with get_async_db_context(db) as session: + user = await session.get(User, id) + if not user: + return None + for key, value in updated.items(): + setattr(user, key, value) + await session.commit() + await session.refresh(user) + return UserModel.model_validate(user) + # settings update helper async def update_user_settings_by_id( self, id: str, updated: dict, db: AsyncSession | None = None ) -> UserModel | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - if not user: - return None - - user_settings = user.settings - - if user_settings is None: - user_settings = {} - - user_settings.update(updated) - - await db.execute(update(User).filter_by(id=id).values(settings=user_settings)) - await db.commit() - - result = await db.execute(select(User).filter_by(id=id)) - user = result.scalars().first() - return UserModel.model_validate(user) - except Exception: - return None + async with get_async_db_context(db) as session: + user = await session.get(User, id) + if not user: + return None + user_settings = dict(user.settings or {}) + user_settings.update(updated) + user.settings = user_settings + await session.commit() + await session.refresh(user) + return UserModel.model_validate(user) async def delete_user_by_id(self, id: str, db: AsyncSession | None = None) -> bool: - try: - from open_webui.models.chats import Chats - from open_webui.models.groups import Groups + from open_webui.models.chats import Chats + from open_webui.models.groups import Groups - # Remove User from Groups - await Groups.remove_user_from_all_groups(id) + # Remove User from Groups + await Groups.remove_user_from_all_groups(id) - # Delete User Chats - result = await Chats.delete_chats_by_user_id(id, db=db) - if result: - async with get_async_db_context(db) as db: - # Delete User - await db.execute(delete(User).filter_by(id=id)) - await db.commit() - - return True - else: - return False - except Exception: - return False + # Delete User Chats + async with get_async_db_context(db) as session: + deleted_chats = await Chats.delete_chats_by_user_id(id, db=session) + if not deleted_chats: + return False # chats deletion failed + await session.execute(delete(User).where(User.id == id)) + await session.commit() + return True async def get_user_api_key_by_id(self, id: str, db: AsyncSession | None = None) -> str | None: - try: - async with get_async_db_context(db) as db: - result = await db.execute(select(ApiKey).filter_by(user_id=id)) - api_key = result.scalars().first() - return api_key.key if api_key else None - except Exception: - return None + async with get_async_db_context(db) as session: + api_key = (await session.execute(select(ApiKey).where(ApiKey.user_id == id))).scalars().first() + return api_key.key if api_key else None async def update_user_api_key_by_id(self, id: str, api_key: str, db: AsyncSession | None = None) -> bool: - try: - async with get_async_db_context(db) as db: - await db.execute(delete(ApiKey).filter_by(user_id=id)) - await db.commit() - - now = int(time.time()) - new_api_key = ApiKey( - id=f'key_{id}', - user_id=id, - key=api_key, - created_at=now, - updated_at=now, - ) - db.add(new_api_key) - await db.commit() - - return True - - except Exception: - return False + async with get_async_db_context(db) as session: + await session.execute(delete(ApiKey).where(ApiKey.user_id == id)) + now_ts = int(time.time()) + new_key = ApiKey( + id=f'key_{id}', + user_id=id, + key=api_key, + created_at=now_ts, + updated_at=now_ts, + ) + session.add(new_key) + await session.commit() + return True async def delete_user_api_key_by_id(self, id: str, db: AsyncSession | None = None) -> bool: - try: - async with get_async_db_context(db) as db: - await db.execute(delete(ApiKey).filter_by(user_id=id)) - await db.commit() - return True - except Exception: - return False + async with get_async_db_context(db) as session: + await session.execute(delete(ApiKey).where(ApiKey.user_id == id)) + await session.commit() + return True async def get_valid_user_ids(self, user_ids: list[str], db: AsyncSession | None = None) -> list[str]: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter(User.id.in_(user_ids))) - users = result.scalars().all() - return [user.id for user in users] + async with get_async_db_context(db) as session: + result = await session.execute(select(User).where(User.id.in_(user_ids))) + return [u.id for u in result.scalars().all()] async def get_super_admin_user(self, db: AsyncSession | None = None) -> UserModel | None: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(role='admin').limit(1)) - user = result.scalars().first() - if user: - return UserModel.model_validate(user) - else: - return None + async with get_async_db_context(db) as session: + row = (await session.execute(select(User).where(User.role == 'admin').limit(1))).scalars().first() + return UserModel.model_validate(row) if row else None async def get_active_user_count(self, db: AsyncSession | None = None) -> int: - async with get_async_db_context(db) as db: + async with get_async_db_context(db) as session: # Consider user active if last_active_at within the last 3 minutes three_minutes_ago = int(time.time()) - 180 - result = await db.execute( - select(func.count()).select_from(User).filter(User.last_active_at >= three_minutes_ago) + result = await session.execute( + select(func.count()).select_from(User).where(User.last_active_at >= three_minutes_ago) ) return result.scalar() @@ -819,9 +751,8 @@ class UsersTable: return False async def is_user_active(self, user_id: str, db: AsyncSession | None = None) -> bool: - async with get_async_db_context(db) as db: - result = await db.execute(select(User).filter_by(id=user_id)) - user = result.scalars().first() + async with get_async_db_context(db) as session: + user = await session.get(User, user_id) if user and user.last_active_at: # Consider user active if last_active_at within the last 3 minutes three_minutes_ago = int(time.time()) - 180 @@ -829,4 +760,4 @@ class UsersTable: return False -Users = UsersTable() +Users = UsersTable() # singleton user repository diff --git a/backend/open_webui/retrieval/loaders/main.py b/backend/open_webui/retrieval/loaders/main.py index 93278d402f..a8cd1ff773 100644 --- a/backend/open_webui/retrieval/loaders/main.py +++ b/backend/open_webui/retrieval/loaders/main.py @@ -234,7 +234,6 @@ class Loader: def load(self, filename: str, file_content_type: str, file_path: str) -> list[Document]: loader = self._get_loader(filename, file_content_type, file_path) docs = loader.load() - return [Document(page_content=ftfy.fix_text(doc.page_content), metadata=doc.metadata) for doc in docs] async def aload(self, filename: str, file_content_type: str, file_path: str) -> list[Document]: @@ -257,6 +256,140 @@ class Loader: and not file_content_type.find('html') >= 0 ) + def _detect_text_encoding(self, file_path: str) -> str: + """Detect the encoding of a text file with CJK-aware fallbacks. + + Langchain's ``TextLoader`` uses chardet internally when + ``autodetect_encoding=True``, but chardet frequently misidentifies + CJK encodings (e.g. GB18030 detected as GB2312 or even Cyrillic). + This method replaces that by: + + 1. Trying UTF-8 first (fast path for the vast majority of files). + 2. Using chardet as a *hint* to prioritise the right CJK codec + family, but mapping subset names to their superset + (e.g. GB2312 → gb18030). + 3. Validating that decoded text actually contains CJK characters, + guarding against codecs that "succeed" but produce garbage. + 4. Falling back to latin-1 (always valid, ftfy fixes mojibake later). + """ + try: + with open(file_path, 'rb') as f: + raw = f.read() + except OSError: + return 'utf-8' + + if not raw: + return 'utf-8' + + # Fast path: most files are UTF-8 + try: + raw.decode('utf-8') + return 'utf-8' + except UnicodeDecodeError: + pass + + # Use chardet as a hint, not as ground truth + import chardet + + detected = chardet.detect(raw) + detected_enc = (detected.get('encoding') or '').lower().replace('-', '').replace('_', '') + + # Map chardet's detected encoding to the correct superset codec. + # chardet often reports GB2312 for content that is actually GB18030; + # GB18030 is a strict superset of both GB2312 and GBK. + _ENC_FAMILY = { + 'gb2312': 'gb18030', + 'gb18030': 'gb18030', + 'gbk': 'gb18030', + 'big5': 'big5', + 'euckr': 'euc-kr', + 'eucjp': 'euc-jp', + 'iso2022jp': 'euc-jp', + 'shiftjis': 'shift_jis', + } + + # Build priority list: chardet-hinted codec first, then remaining CJK + base_order = ['gb18030', 'big5', 'euc-kr', 'euc-jp'] + hinted = _ENC_FAMILY.get(detected_enc) + if hinted and hinted in base_order: + ordered = [hinted] + [e for e in base_order if e != hinted] + else: + ordered = base_order + + for enc in ordered: + try: + text = raw.decode(enc) + if text.strip() and self._has_cjk_characters(text): + log.info( + 'Detected encoding %s for %s (chardet guessed %s)', + enc, + file_path, + detected.get('encoding'), + ) + return enc + except (UnicodeDecodeError, LookupError): + continue + + # If chardet gave a non-CJK answer that isn't in our family map, + # try it directly — it might be a valid Western encoding. + chardet_encoding = detected.get('encoding') + if chardet_encoding: + try: + raw.decode(chardet_encoding) + log.info( + 'Using chardet-detected encoding %s for %s', + chardet_encoding, + file_path, + ) + return chardet_encoding + except (UnicodeDecodeError, LookupError): + pass + + # latin-1 is the ultimate fallback: every byte 0x00–0xFF is valid. + # ftfy.fix_text() (applied downstream) repairs most mojibake that + # results from treating Windows-1252 content as Latin-1. + log.info('Falling back to latin-1 encoding for %s', file_path) + return 'latin-1' + + @staticmethod + def _has_cjk_characters(text: str, threshold: float = 0.05) -> bool: + """Check if decoded text contains a meaningful proportion of CJK characters. + + This guards against codecs that technically "succeed" but decode the + bytes into wrong Unicode codepoints (e.g. PUA chars, random symbols). + A genuine CJK document should have at least ``threshold`` fraction of + its non-whitespace characters in CJK Unicode blocks. + """ + if not text: + return False + + cjk_count = 0 + total = 0 + for ch in text: + if ch.isspace(): + continue + total += 1 + cp = ord(ch) + if ( + 0x4E00 <= cp <= 0x9FFF # CJK Unified Ideographs + or 0x3400 <= cp <= 0x4DBF # CJK Extension A + or 0x20000 <= cp <= 0x2A6DF # CJK Extension B + or 0x2A700 <= cp <= 0x2B73F # CJK Extension C + or 0x2B740 <= cp <= 0x2B81F # CJK Extension D + or 0xF900 <= cp <= 0xFAFF # CJK Compatibility Ideographs + or 0x3000 <= cp <= 0x303F # CJK Symbols and Punctuation + or 0x3040 <= cp <= 0x309F # Hiragana + or 0x30A0 <= cp <= 0x30FF # Katakana + or 0xAC00 <= cp <= 0xD7AF # Hangul Syllables + or 0xFF00 <= cp <= 0xFFEF # Halfwidth and Fullwidth Forms + ): + cjk_count += 1 + + if total == 0: + return False + + return (cjk_count / total) >= threshold + def _get_loader(self, filename: str, file_content_type: str, file_path: str): file_ext = filename.split('.')[-1].lower() @@ -274,7 +407,7 @@ class Loader: ) elif self.engine == 'tika' and self.kwargs.get('TIKA_SERVER_URL'): if self._is_text_file(file_ext, file_content_type): - loader = TextLoader(file_path, autodetect_encoding=True) + loader = TextLoader(file_path, encoding=self._detect_text_encoding(file_path)) else: loader = TikaLoader( url=self.kwargs.get('TIKA_SERVER_URL'), @@ -326,7 +459,7 @@ class Loader: ) elif self.engine == 'docling' and self.kwargs.get('DOCLING_SERVER_URL'): if self._is_text_file(file_ext, file_content_type): - loader = TextLoader(file_path, autodetect_encoding=True) + loader = TextLoader(file_path, encoding=self._detect_text_encoding(file_path)) else: # Build params for DoclingLoader params = self.kwargs.get('DOCLING_PARAMS', {}) @@ -371,7 +504,7 @@ class Loader: azure_credential=DefaultAzureCredential(), api_model=self.kwargs.get('DOCUMENT_INTELLIGENCE_MODEL'), ) - elif self.engine == 'mineru' and file_ext in ['pdf']: # MinerU currently only supports PDF + elif self.engine == 'mineru' and file_ext in self.kwargs.get('MINERU_FILE_EXTENSIONS', ['pdf']): mineru_timeout = self.kwargs.get('MINERU_API_TIMEOUT', 300) if mineru_timeout: try: @@ -413,7 +546,7 @@ class Loader: mode=self.kwargs.get('PDF_LOADER_MODE', 'page'), ) elif file_ext == 'csv': - loader = CSVLoader(file_path, autodetect_encoding=True) + loader = CSVLoader(file_path, encoding=self._detect_text_encoding(file_path)) elif file_ext == 'rst': try: from langchain_community.document_loaders import UnstructuredRSTLoader @@ -425,7 +558,7 @@ class Loader: 'Falling back to plain text loading for .rst file. ' 'Install it with: pip install unstructured' ) - loader = TextLoader(file_path, autodetect_encoding=True) + loader = TextLoader(file_path, encoding=self._detect_text_encoding(file_path)) elif file_ext == 'xml': try: from langchain_community.document_loaders import UnstructuredXMLLoader @@ -437,11 +570,11 @@ class Loader: 'Falling back to plain text loading for .xml file. ' 'Install it with: pip install unstructured' ) - loader = TextLoader(file_path, autodetect_encoding=True) + loader = TextLoader(file_path, encoding=self._detect_text_encoding(file_path)) elif file_ext in ['htm', 'html']: loader = BSHTMLLoader(file_path, open_encoding='unicode_escape') elif file_ext == 'md': - loader = TextLoader(file_path, autodetect_encoding=True) + loader = TextLoader(file_path, encoding=self._detect_text_encoding(file_path)) elif file_content_type == 'application/epub+zip': try: from langchain_community.document_loaders import UnstructuredEPubLoader @@ -457,6 +590,16 @@ class Loader: or file_ext == 'docx' ): loader = Docx2txtLoader(file_path) + elif file_ext == 'doc' or file_content_type == 'application/msword': + try: + from langchain_community.document_loaders import UnstructuredWordDocumentLoader + + loader = UnstructuredWordDocumentLoader(file_path) + except ImportError: + raise ValueError( + "Processing .doc files requires the 'unstructured' package. " + 'Install it with: pip install unstructured' + ) elif file_content_type in [ 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', @@ -500,8 +643,8 @@ class Loader: 'Install it with: pip install unstructured' ) elif self._is_text_file(file_ext, file_content_type): - loader = TextLoader(file_path, autodetect_encoding=True) + loader = TextLoader(file_path, encoding=self._detect_text_encoding(file_path)) else: - loader = TextLoader(file_path, autodetect_encoding=True) + loader = TextLoader(file_path, encoding=self._detect_text_encoding(file_path)) return loader diff --git a/backend/open_webui/retrieval/loaders/youtube.py b/backend/open_webui/retrieval/loaders/youtube.py index 97c1a0c20c..ad4c3524ac 100644 --- a/backend/open_webui/retrieval/loaders/youtube.py +++ b/backend/open_webui/retrieval/loaders/youtube.py @@ -98,7 +98,7 @@ class YoutubeLoader: try: transcript_list = transcript_api.list(self.video_id) except Exception as e: - log.exception('Loading YouTube transcript failed') + log.warning(f'Loading YouTube transcript failed: {e}') return [] # Try each language in order of priority diff --git a/backend/open_webui/retrieval/utils.py b/backend/open_webui/retrieval/utils.py index 8c39fe90ca..41415ba8c3 100644 --- a/backend/open_webui/retrieval/utils.py +++ b/backend/open_webui/retrieval/utils.py @@ -29,7 +29,9 @@ from open_webui.env import ( AIOHTTP_CLIENT_ALLOW_REDIRECTS, AIOHTTP_CLIENT_SESSION_SSL, AIOHTTP_CLIENT_TIMEOUT, + BYPASS_RETRIEVAL_ACCESS_CONTROL, ENABLE_FORWARD_USER_INFO_HEADERS, + ENABLE_RETRIEVAL_UNSCOPED_COLLECTIONS, OFFLINE_MODE, ) from open_webui.models.access_grants import AccessGrants @@ -117,6 +119,7 @@ def build_loader_from_config(request): MINERU_API_KEY=config.MINERU_API_KEY, MINERU_API_TIMEOUT=config.MINERU_API_TIMEOUT, MINERU_PARAMS=config.MINERU_PARAMS, + MINERU_FILE_EXTENSIONS=config.MINERU_FILE_EXTENSIONS, ) @@ -175,6 +178,18 @@ def get_content_from_url(request, url: str) -> str: # Validate URL before making any request (blocks private IPs, non-HTTP, filter list) validate_url(url) + # YouTube URLs (including youtu.be short links) should go straight to + # YoutubeLoader, which uses youtube-transcript-api and never needs the + # HTTP response body. Probing the URL first is harmful for short URLs: + # youtu.be returns a 303 redirect with Content-Type: application/binary + # when allow_redirects=False, causing the binary-content path to run + # and produce empty docs → HTTP 400. + if is_youtube_url(url): + loader = get_loader(request, url) + docs = loader.load() + content = ' '.join([doc.page_content for doc in docs]) + return content, docs + # Streamed GET to check Content-Type without downloading the body. # allow_redirects=False prevents redirect-based SSRF: validate_url() above is # called on the originally-submitted URL only; following 3xx redirects without @@ -914,6 +929,13 @@ def get_embedding_function( concurrent_requests=0, ) -> Awaitable: if embedding_engine == '': + if embedding_function is None: + raise ValueError( + 'No embedding model is loaded. Set RAG_EMBEDDING_MODEL to a valid ' + 'SentenceTransformer model name, or configure an external ' + 'RAG_EMBEDDING_ENGINE (ollama, openai, azure_openai).' + ) + # Sentence transformers: CPU-bound sync operation async def async_embedding_function(query, prefix=None, user=None): return await asyncio.to_thread( @@ -1053,6 +1075,16 @@ def get_reranking_function(reranking_engine, reranking_model, reranking_function ) +# UUIDs, SHA-256 digests, and prefixed variants thereof all fit [A-Za-z0-9_-]. +# Anything else cannot be a real Open WebUI collection and could break out of +# a Milvus expression literal. +_SAFE_COLLECTION_NAME_RE = re.compile(r'^[A-Za-z0-9_-]{1,255}$') + + +def _is_safe_collection_name(name: str) -> bool: + return isinstance(name, str) and bool(_SAFE_COLLECTION_NAME_RE.match(name)) + + async def filter_accessible_collections( collection_names: set[str], user: UserModel, @@ -1062,20 +1094,33 @@ async def filter_accessible_collections( Return only the collection names the user is allowed to access. Admins bypass all checks. For non-admins the policy is: + - any name with characters outside [A-Za-z0-9_-] → rejected - file-* → validated via has_access_to_file - user-memory-* → must match user's own memory collection - web-search-* → ephemeral per-query collections, always allowed - knowledge-bases → always denied (system meta-collection) - everything else → if the name matches a knowledge base, validated via Knowledges.check_access_by_user_id; if no - such KB exists, the name is treated as an - ephemeral/legacy collection and allowed + such KB exists, denied by default. When + ENABLE_RETRIEVAL_UNSCOPED_COLLECTIONS is True, + the name is treated as a legacy/ephemeral + collection and allowed. """ + # Applied before the admin bypass — malformed names should never reach the vector store. + safe_names = {n for n in collection_names if _is_safe_collection_name(n)} + rejected = collection_names - safe_names + if rejected: + log.warning( + 'filter_accessible_collections: rejected %d collection name(s) with unsafe characters (user_id=%s)', + len(rejected), + getattr(user, 'id', ''), + ) + if user.role == 'admin': - return collection_names + return safe_names validated = set() - for name in collection_names: + for name in safe_names: if name == 'knowledge-bases': # System meta-collection — never exposed to non-admins. continue @@ -1094,11 +1139,13 @@ async def filter_accessible_collections( else: # May be a knowledge-base ID or a legacy/ephemeral collection. # If it IS a KB, enforce access control. If no such KB - # exists, treat it as a non-sensitive collection (e.g. legacy - # model knowledge, process_text SHA256 collections) and allow. + # exists, the behaviour depends on + # ENABLE_RETRIEVAL_UNSCOPED_COLLECTIONS: + # False (default) — deny (closes the unscoped namespace) + # True — allow (preserves legacy behaviour) if await Knowledges.check_access_by_user_id(name, user.id, permission=access_type): validated.add(name) - elif not await Knowledges.get_knowledge_by_id(name): + elif ENABLE_RETRIEVAL_UNSCOPED_COLLECTIONS and not await Knowledges.get_knowledge_by_id(name): # Not a KB at all — legacy/ephemeral collection, allow validated.add(name) return validated @@ -1242,11 +1289,27 @@ async def get_sources_from_items( ], } else: - # Fallback to collection names - if item.get('legacy'): - collection_names.append(f'{item["id"]}') - else: - collection_names.append(f'file-{item["id"]}') + # Chunked-retrieval fallback — verify read access before + # exposing the file's vector collection (same posture as the + # full-context branch above). + file_id = item.get('id') + if file_id: + if BYPASS_RETRIEVAL_ACCESS_CONTROL: + if item.get('legacy'): + collection_names.append(f'{file_id}') + else: + collection_names.append(f'file-{file_id}') + else: + file_object = await Files.get_file_by_id(file_id) + if file_object and ( + user.role == 'admin' + or file_object.user_id == user.id + or await has_access_to_file(file_id, 'read', user) + ): + if item.get('legacy'): + collection_names.append(f'{file_id}') + else: + collection_names.append(f'file-{file_id}') elif item.get('type') == 'collection': # Manual Full Mode Toggle for Collection @@ -1292,9 +1355,18 @@ async def get_sources_from_items( 'metadatas': [metadatas], } else: - # Fallback to collection names if item.get('legacy'): - collection_names = item.get('collection_names', []) + if BYPASS_RETRIEVAL_ACCESS_CONTROL: + collection_names = item.get('collection_names', []) + else: + # Legacy KB: item.collection_names is client-supplied. + # Validate against the KB's actual files to prevent + # cross-tenant collection name substitution. + files = await Knowledges.get_files_by_id(knowledge_base.id) + owned_names = {f'file-{f.id}' for f in files} + owned_names.add(knowledge_base.id) + valid_names = [n for n in (item.get('collection_names') or []) if n in owned_names] + collection_names = valid_names if valid_names else [knowledge_base.id] else: collection_names.append(item['id']) @@ -1305,11 +1377,20 @@ async def get_sources_from_items( 'metadatas': [[doc.get('metadata') for doc in item.get('docs')]], } elif item.get('collection_name'): - # Direct Collection Name - collection_names.append(item['collection_name']) + if BYPASS_RETRIEVAL_ACCESS_CONTROL: + collection_names.append(item['collection_name']) + else: + log.debug( + "get_sources_from_items: ignoring untrusted direct collection_name '%s' on item without type", + item.get('collection_name'), + ) elif item.get('collection_names'): - # Collection Names List - collection_names.extend(item['collection_names']) + if BYPASS_RETRIEVAL_ACCESS_CONTROL: + collection_names.extend(item['collection_names']) + else: + log.debug( + 'get_sources_from_items: ignoring untrusted direct collection_names on item without type', + ) # If query_result is None # Fallback to collection names and vector search the collections diff --git a/backend/open_webui/retrieval/vector/dbs/milvus_multitenancy.py b/backend/open_webui/retrieval/vector/dbs/milvus_multitenancy.py index d43e2e61d4..af64919b6e 100644 --- a/backend/open_webui/retrieval/vector/dbs/milvus_multitenancy.py +++ b/backend/open_webui/retrieval/vector/dbs/milvus_multitenancy.py @@ -3,6 +3,7 @@ NOTE: This vector database integration is community-supported and maintained on """ import logging +import re from typing import Any, Dict, List, Optional, Tuple from open_webui.config import ( @@ -35,6 +36,30 @@ log = logging.getLogger(__name__) RESOURCE_ID_FIELD = 'resource_id' +# Milvus expressions are SQL-like strings with no parameterized-query API; +# values get interpolated into single-quoted literals. Reject anything that +# can't be a legitimate Open WebUI collection name. +_SAFE_RESOURCE_ID_RE = re.compile(r'^[A-Za-z0-9_-]{1,255}$') +_SAFE_METADATA_KEY_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]{0,63}$') + + +def _validate_resource_id(resource_id: str) -> str: + if not isinstance(resource_id, str) or not _SAFE_RESOURCE_ID_RE.match(resource_id): + raise ValueError(f'Invalid Milvus resource_id (collection name): {resource_id!r}') + return resource_id + + +def _validate_metadata_key(key: str) -> str: + if not isinstance(key, str) or not _SAFE_METADATA_KEY_RE.match(key): + raise ValueError(f'Invalid Milvus metadata filter key: {key!r}') + return key + + +def _escape_milvus_string(value: str) -> str: + if not isinstance(value, str): + raise TypeError(f'Expected str for Milvus expression value, got {type(value).__name__}') + return value.replace('\\', '\\\\').replace("'", "\\'") + class MilvusClient(VectorDBBase): def __init__(self): @@ -126,6 +151,7 @@ class MilvusClient(VectorDBBase): def has_collection(self, collection_name: str) -> bool: mt_collection, resource_id = self._get_collection_and_resource_id(collection_name) + _validate_resource_id(resource_id) if not utility.has_collection(mt_collection): return False @@ -138,6 +164,7 @@ class MilvusClient(VectorDBBase): if not items: return mt_collection, resource_id = self._get_collection_and_resource_id(collection_name) + _validate_resource_id(resource_id) dimension = len(items[0]['vector']) self._ensure_collection(mt_collection, dimension) collection = Collection(mt_collection) @@ -165,6 +192,7 @@ class MilvusClient(VectorDBBase): return None mt_collection, resource_id = self._get_collection_and_resource_id(collection_name) + _validate_resource_id(resource_id) if not utility.has_collection(mt_collection): return None @@ -203,21 +231,22 @@ class MilvusClient(VectorDBBase): filter: Optional[Dict[str, Any]] = None, ): mt_collection, resource_id = self._get_collection_and_resource_id(collection_name) + _validate_resource_id(resource_id) if not utility.has_collection(mt_collection): return collection = Collection(mt_collection) - # Build expression expr = [f"{RESOURCE_ID_FIELD} == '{resource_id}'"] if ids: # Milvus expects a string list for 'in' operator - id_list_str = ', '.join([f"'{id_val}'" for id_val in ids]) + id_list_str = ', '.join([f"'{_escape_milvus_string(str(id_val))}'" for id_val in ids]) expr.append(f'id in [{id_list_str}]') if filter: for key, value in filter.items(): - expr.append(f"metadata['{key}'] == '{value}'") + _validate_metadata_key(key) + expr.append(f"metadata['{key}'] == '{_escape_milvus_string(str(value))}'") collection.delete(' and '.join(expr)) @@ -228,6 +257,7 @@ class MilvusClient(VectorDBBase): def delete_collection(self, collection_name: str): mt_collection, resource_id = self._get_collection_and_resource_id(collection_name) + _validate_resource_id(resource_id) if not utility.has_collection(mt_collection): return @@ -236,6 +266,7 @@ class MilvusClient(VectorDBBase): def query(self, collection_name: str, filter: Dict[str, Any], limit: Optional[int] = None) -> Optional[GetResult]: mt_collection, resource_id = self._get_collection_and_resource_id(collection_name) + _validate_resource_id(resource_id) if not utility.has_collection(mt_collection): return None @@ -245,10 +276,15 @@ class MilvusClient(VectorDBBase): expr = [f"{RESOURCE_ID_FIELD} == '{resource_id}'"] if filter: for key, value in filter.items(): + _validate_metadata_key(key) if isinstance(value, str): - expr.append(f"metadata['{key}'] == '{value}'") - else: + expr.append(f"metadata['{key}'] == '{_escape_milvus_string(value)}'") + elif isinstance(value, bool): + expr.append(f"metadata['{key}'] == {str(value).lower()}") + elif isinstance(value, (int, float)): expr.append(f"metadata['{key}'] == {value}") + else: + raise TypeError(f'Unsupported Milvus filter value type for key {key!r}: {type(value).__name__}') iterator = collection.query_iterator( expr=' and '.join(expr), diff --git a/backend/open_webui/retrieval/vector/dbs/qdrant.py b/backend/open_webui/retrieval/vector/dbs/qdrant.py index acf4e61993..7156a16c53 100644 --- a/backend/open_webui/retrieval/vector/dbs/qdrant.py +++ b/backend/open_webui/retrieval/vector/dbs/qdrant.py @@ -216,28 +216,23 @@ class QdrantClient(VectorDBBase): ids: Optional[list[str]] = None, filter: Optional[dict] = None, ): - # Delete the items from the collection based on the ids. - field_conditions = [] - + # Delete by point ID: the point ID is the item's id (see _create_points). + # Filtering on metadata.id silently misses points whose payload omits an + # id (e.g. memories), leaving orphaned vectors behind. if ids: - for id_value in ids: - ( - field_conditions.append( - models.FieldCondition( - key='metadata.id', - match=models.MatchValue(value=id_value), - ), - ), - ) - elif filter: + return self.client.delete( + collection_name=f'{self.collection_prefix}_{collection_name}', + points_selector=models.PointIdsList(points=ids), + ) + + field_conditions = [] + if filter: for key, value in filter.items(): - ( - field_conditions.append( - models.FieldCondition( - key=f'metadata.{key}', - match=models.MatchValue(value=value), - ), - ), + field_conditions.append( + models.FieldCondition( + key=f'metadata.{key}', + match=models.MatchValue(value=value), + ) ) return self.client.delete( diff --git a/backend/open_webui/retrieval/vector/dbs/qdrant_multitenancy.py b/backend/open_webui/retrieval/vector/dbs/qdrant_multitenancy.py index 15e72f1d16..9b717644c5 100644 --- a/backend/open_webui/retrieval/vector/dbs/qdrant_multitenancy.py +++ b/backend/open_webui/retrieval/vector/dbs/qdrant_multitenancy.py @@ -228,15 +228,17 @@ class QdrantClient(VectorDBBase): return None must_conditions = [_tenant_filter(tenant_id)] - should_conditions = [] if ids: - should_conditions = [_metadata_filter('id', id_value) for id_value in ids] + # Delete by point ID within the tenant. The point ID is the item's id + # (see _create_points); filtering on metadata.id silently misses points + # whose payload omits an id (e.g. memories), leaving orphaned vectors. + must_conditions.append(models.HasIdCondition(has_id=ids)) elif filter: must_conditions += [_metadata_filter(k, v) for k, v in filter.items()] return self.client.delete( collection_name=mt_collection, - points_selector=models.FilterSelector(filter=models.Filter(must=must_conditions, should=should_conditions)), + points_selector=models.FilterSelector(filter=models.Filter(must=must_conditions)), ) def search( diff --git a/backend/open_webui/retrieval/vector/dbs/valkey.py b/backend/open_webui/retrieval/vector/dbs/valkey.py new file mode 100644 index 0000000000..1db10281a4 --- /dev/null +++ b/backend/open_webui/retrieval/vector/dbs/valkey.py @@ -0,0 +1,765 @@ +# NOTE: This vector database integration is community-supported and maintained on a best-effort basis. +# Requires Valkey core >= 9.0.1 with the valkey-search module >= 1.2.0 loaded. + +import atexit +import json +import logging +import re +import struct +from urllib.parse import urlparse + +from open_webui.config import ( + VALKEY_COLLECTION_PREFIX, + VALKEY_DISTANCE_METRIC, + VALKEY_HNSW_EF_CONSTRUCTION, + VALKEY_HNSW_EF_RUNTIME, + VALKEY_HNSW_M, + VALKEY_INDEX_TYPE, + VALKEY_URL, +) +from open_webui.retrieval.vector.main import ( + GetResult, + SearchResult, + VectorDBBase, + VectorItem, +) +from open_webui.retrieval.vector.utils import process_metadata + +log = logging.getLogger(__name__) + + +def _import_glide(): + """Lazily import glide_sync so the module can be loaded without valkey-glide-sync installed.""" + try: + from glide_sync import ( + Batch, + DataType, + DistanceMetricType, + FtCreateOptions, + FtSearchLimit, + FtSearchOptions, + GlideClient, + GlideClientConfiguration, + NodeAddress, + RequestError, + ReturnField, + TagField, + TextField, + VectorAlgorithm, + VectorField, + VectorFieldAttributesFlat, + VectorFieldAttributesHnsw, + VectorType, + ) + from glide_sync import ( + ft as glide_ft, + ) + except ImportError as e: + raise ImportError( + 'valkey-glide-sync is required when VECTOR_DB=valkey. Install it with: pip install valkey-glide-sync==2.3.1' + ) from e + return { + 'Batch': Batch, + 'DataType': DataType, + 'DistanceMetricType': DistanceMetricType, + 'FtCreateOptions': FtCreateOptions, + 'FtSearchLimit': FtSearchLimit, + 'FtSearchOptions': FtSearchOptions, + 'GlideClient': GlideClient, + 'GlideClientConfiguration': GlideClientConfiguration, + 'NodeAddress': NodeAddress, + 'RequestError': RequestError, + 'ReturnField': ReturnField, + 'TagField': TagField, + 'TextField': TextField, + 'VectorAlgorithm': VectorAlgorithm, + 'VectorField': VectorField, + 'VectorFieldAttributesFlat': VectorFieldAttributesFlat, + 'VectorFieldAttributesHnsw': VectorFieldAttributesHnsw, + 'VectorType': VectorType, + 'glide_ft': glide_ft, + } + + +# valkey-search 1.2.0 requires Valkey core 9.0.1+ per upstream release notes. +# Unlike RediSearch (dialects 1-4), valkey-search only implements DIALECT 2 — GLIDE's +# FtSearchOptions doesn't expose a dialect parameter because it's always dialect 2. +MIN_VALKEY_VERSION = (9, 0, 1) +MIN_SEARCH_MODULE_VERSION = (1, 2, 0) + +_VALID_DISTANCE_METRICS = {'COSINE', 'L2', 'IP'} +_NEVER_MATCH_SENTINEL = '__open_webui_valkey_never_match__' + +# Compile once at module load — includes `?` which is a single-char wildcard in TAG queries. +_TAG_SPECIAL_RE = re.compile(r'([,.<>{}\[\]"\':;!@#$%^&*()\-+=~?\\/| \t\n\r])') + + +_SAFE_FIELD_RE = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$') + + +def _vector_to_bytes(vector: list[float | int]) -> bytes: + """Pack a list of floats as a float32 little-endian binary blob.""" + return struct.pack(f'<{len(vector)}f', *vector) + + +def _escape_tag_value(value: str) -> str: + """Escape special characters for RediSearch/Valkey-Search TAG field queries.""" + return _TAG_SPECIAL_RE.sub(r'\\\1', str(value)) + + +def _build_filter_expression(filter: dict) -> str: + """Translate a Chroma-style filter dict into a valkey-search filter expression. + + Supports simple equality, $in, $ne, and $eq. Multiple keys are ANDed together. + Raises ValueError on unsupported operators rather than silently matching nothing. + """ + parts = [] + for key, value in filter.items(): + if not _SAFE_FIELD_RE.match(key): + raise ValueError( + f'Invalid filter field name: {key!r}. ' + 'Field names must start with a letter or underscore and contain only alphanumerics/underscores.' + ) + if isinstance(value, dict): + for op, operand in value.items(): + if op == '$in' and isinstance(operand, list): + if not operand: + # Empty $in → match nothing, not "match all". + parts.append(f'@{key}:{{{_NEVER_MATCH_SENTINEL}}}') + continue + escaped = [_escape_tag_value(str(v)) for v in operand] + parts.append(f'@{key}:{{{"|".join(escaped)}}}') + elif op in ('$eq', '$ne'): + prefix = '-' if op == '$ne' else '' + parts.append(f'{prefix}@{key}:{{{_escape_tag_value(str(operand))}}}') + else: + raise ValueError( + f'Unsupported filter operator {op!r} for key {key!r}. Supported operators: $in, $ne, $eq.' + ) + else: + parts.append(f'@{key}:{{{_escape_tag_value(str(value))}}}') + return ' '.join(parts) + + +def _decode(value) -> str: + """Decode bytes to str; pass through str unchanged.""" + if isinstance(value, (bytes, bytearray)): + return value.decode() + return str(value) if value is not None else '' + + +class ValkeyClient(VectorDBBase): + def __init__(self): + if not VALKEY_URL: + raise ValueError( + 'VALKEY_URL is required when VECTOR_DB=valkey. ' + 'Set it to your Valkey server URL (e.g., valkey://localhost:6379).' + ) + + # Lazily import glide_sync — only needed when this backend is actually used. + self._g = _import_glide() + + # Validate distance metric at init — invalid values pass through to FT.CREATE + # and fail with a cryptic server error. + metric = VALKEY_DISTANCE_METRIC.upper() + if metric not in _VALID_DISTANCE_METRICS: + raise ValueError( + f'Invalid VALKEY_DISTANCE_METRIC={VALKEY_DISTANCE_METRIC!r}. ' + f'Must be one of: {", ".join(sorted(_VALID_DISTANCE_METRICS))}.' + ) + + DistanceMetricType = self._g['DistanceMetricType'] + self._distance_metric_map = { + 'COSINE': DistanceMetricType.COSINE, + 'L2': DistanceMetricType.L2, + 'IP': DistanceMetricType.IP, + } + + self.collection_prefix = VALKEY_COLLECTION_PREFIX + self.index_type = VALKEY_INDEX_TYPE + self.distance_metric = metric + + parsed = urlparse(VALKEY_URL) + host = parsed.hostname or 'localhost' + port = parsed.port or 6379 + db = int(parsed.path.lstrip('/') or 0) + + GlideClientConfiguration = self._g['GlideClientConfiguration'] + NodeAddress = self._g['NodeAddress'] + GlideClient = self._g['GlideClient'] + + config = GlideClientConfiguration( + addresses=[NodeAddress(host=host, port=port)], + database_id=db if db else None, + request_timeout=5000, + client_name='open_webui_vector_store_client', + ) + try: + self.client = GlideClient.create(config) + except Exception as e: + raise ConnectionError(f'Failed to connect to Valkey at {host}:{port}: {e}') from e + + # Separate client for batch writes — large HSET payloads on the multiplexed + # connection can starve concurrent reads. + batch_config = GlideClientConfiguration( + addresses=[NodeAddress(host=host, port=port)], + database_id=db if db else None, + request_timeout=10000, # 10s — HNSW indexing can take 1-4s per vector + client_name='open_webui_vector_store_batch_client', + ) + try: + self.batch_client = GlideClient.create(batch_config) + except Exception as e: + raise ConnectionError(f'Failed to create batch write client for Valkey at {host}:{port}: {e}') from e + + try: + self.client.ping() + except Exception as e: + raise ConnectionError(f'Failed to ping Valkey at {host}:{port}: {e}') from e + + # Catch misconfigured deployments at startup (e.g., valkey-bundle:9.0.1 ships + # valkey-search 1.0.0 which lacks TEXT fields and filter-only FT.SEARCH). + self._check_core_version() + self._check_search_module() + + atexit.register(self.close) + + def close(self) -> None: + """Close both GLIDE clients, flushing in-flight requests.""" + try: + self.client.close() + except Exception: + pass + try: + self.batch_client.close() + except Exception: + pass + + # ----- version checks ---------------------------------------------------- + + @staticmethod + def _parse_semver(version_str: str) -> tuple[int, int, int] | None: + if not version_str: + return None + m = re.match(r'^(\d+)\.(\d+)\.(\d+)', version_str) + return (int(m.group(1)), int(m.group(2)), int(m.group(3))) if m else None + + @staticmethod + def _format_version(v: tuple[int, int, int]) -> str: + return f'{v[0]}.{v[1]}.{v[2]}' + + def _check_core_version(self) -> None: + try: + info_raw = self.client.info() + except Exception as e: + log.warning(f'Could not fetch Valkey INFO for version check, proceeding: {e}') + return + + raw = None + text = _decode(info_raw) if info_raw else '' + redis_fallback = None + for line in text.splitlines(): + if line.startswith('valkey_version:'): + raw = line.split(':', 1)[1].strip() + break + if line.startswith('redis_version:') and redis_fallback is None: + redis_fallback = line.split(':', 1)[1].strip() + if raw is None: + raw = redis_fallback + version = self._parse_semver(raw) if raw else None + + if version is None: + log.warning( + f'Could not determine Valkey core version (raw={raw!r}); proceeding but ' + f'minimum {self._format_version(MIN_VALKEY_VERSION)} is required.' + ) + elif version < MIN_VALKEY_VERSION: + raise RuntimeError( + f'Valkey core {self._format_version(version)} is below the minimum required version ' + f'{self._format_version(MIN_VALKEY_VERSION)}. valkey-search 1.2.0 requires Valkey core ' + '9.0.1 or later. Upgrade your server or use valkey-bundle:9.1.0-rc2+.' + ) + log.info(f'Valkey core version: {self._format_version(version) if version else "unknown"}') + + def _check_search_module(self) -> None: + try: + modules = self.client.custom_command(['MODULE', 'LIST']) + except Exception as e: + log.warning( + f'Could not list modules on the Valkey server ({e}); proceeding but ' + f'valkey-search >= {self._format_version(MIN_SEARCH_MODULE_VERSION)} is required.' + ) + return + + # MODULE LIST returns [{b'name': b'search', b'ver': 66048, ...}] + # ver encoding: major*10000 + minor*100 + patch + search_version: tuple[int, int, int] | None = None + module_present = False + raw_ver = None + for entry in modules or []: + if isinstance(entry, dict): + name = _decode(entry.get(b'name') or entry.get('name') or '') + raw_ver = entry.get(b'ver') or entry.get('ver', 0) + else: + parsed = self._decode_kv_pairs(entry) + name = parsed.get('name', '') + raw_ver = parsed.get('ver', 0) + if name.lower() == 'search': + module_present = True + try: + ver_int = int(raw_ver) + search_version = (ver_int // 10000, (ver_int % 10000) // 100, ver_int % 100) + except (TypeError, ValueError): + search_version = None + break + + if not module_present: + raise RuntimeError( + 'The valkey-search module is not loaded on the Valkey server. ' + f'This backend requires valkey-search >= {self._format_version(MIN_SEARCH_MODULE_VERSION)}. ' + 'Use valkey-bundle:9.1.0-rc2+ or load libsearch.so via --loadmodule on a Valkey 9.0.1+ server.' + ) + if search_version is None: + log.warning( + f'valkey-search module is loaded but version could not be parsed (raw={raw_ver!r}); ' + f'proceeding but minimum {self._format_version(MIN_SEARCH_MODULE_VERSION)} is required.' + ) + elif search_version < MIN_SEARCH_MODULE_VERSION: + raise RuntimeError( + f'valkey-search {self._format_version(search_version)} is below the minimum required ' + f'version {self._format_version(MIN_SEARCH_MODULE_VERSION)}. Earlier versions lack the ' + 'TEXT field type and filter-only FT.SEARCH support required by this backend. ' + 'Upgrade to valkey-bundle:9.1.0-rc2+ or load valkey-search 1.2.0+ as a module.' + ) + log.info(f'valkey-search version: {self._format_version(search_version) if search_version else "unknown"}') + + def _index_name(self, collection_name: str) -> str: + return f'idx:{self.collection_prefix}:{collection_name}' + + def _key_prefix(self, collection_name: str) -> str: + return f'{self.collection_prefix}:{collection_name}:' + + def _item_key(self, collection_name: str, item_id: str) -> str: + return f'{self.collection_prefix}:{collection_name}:{item_id}' + + def _create_index(self, collection_name: str, dimension: int) -> None: + """Create an FT index for a collection with the given vector dimension.""" + g = self._g + index_name = self._index_name(collection_name) + prefix = self._key_prefix(collection_name) + distance_metric = self._distance_metric_map[self.distance_metric] + + if self.index_type == 'HNSW': + vector_attrs = g['VectorFieldAttributesHnsw']( + dimensions=dimension, + distance_metric=distance_metric, + type=g['VectorType'].FLOAT32, + number_of_edges=VALKEY_HNSW_M, + vectors_examined_on_construction=VALKEY_HNSW_EF_CONSTRUCTION, + vectors_examined_on_runtime=VALKEY_HNSW_EF_RUNTIME, + ) + algo = g['VectorAlgorithm'].HNSW + else: + if self.index_type != 'FLAT': + log.warning(f'Unrecognized VALKEY_INDEX_TYPE={self.index_type!r}; falling back to FLAT.') + vector_attrs = g['VectorFieldAttributesFlat']( + dimensions=dimension, + distance_metric=distance_metric, + type=g['VectorType'].FLOAT32, + ) + algo = g['VectorAlgorithm'].FLAT + + schema = [ + g['VectorField'](name='vector', algorithm=algo, attributes=vector_attrs), + g['TextField'](name='text'), + g['TagField'](name='id'), + g['TextField'](name='metadata_json'), + g['TagField'](name='hash'), + g['TagField'](name='file_id'), + g['TagField'](name='source'), + g['TagField'](name='knowledge_base_id'), + ] + + options = g['FtCreateOptions'](data_type=g['DataType'].HASH, prefixes=[prefix]) + + try: + g['glide_ft'].create(self.client, index_name, schema, options) + log.info( + f'Created Valkey index {index_name} with dimension={dimension}, ' + f'type={self.index_type}, metric={self.distance_metric}' + ) + except g['RequestError'] as e: + if 'already exists' in str(e).lower(): + log.debug(f'Index {index_name} already exists, skipping creation.') + else: + raise + + def _verify_collection_dimension(self, collection_name: str, dimension: int) -> None: + index_name = self._index_name(collection_name) + try: + info = self._g['glide_ft'].info(self.client, index_name) + except Exception as e: + log.warning(f'Could not FT.INFO {index_name} for dimension check, skipping: {e}') + return + + # ft.info response has nested structure: b'attributes' → list of fields, + # each field is [k1, v1, ...] with a nested 'index' sub-list containing 'dimensions'. + existing = None + attrs = None + if isinstance(info, dict): + attrs = info.get(b'attributes') or info.get('attributes') + elif isinstance(info, (list, tuple)): + attrs = self._find_in_kv_pairs(info, 'attributes', case_insensitive=True) + + for attr in attrs or []: + if not isinstance(attr, (list, tuple)): + continue + field_type = self._find_in_kv_pairs(attr, 'type', case_insensitive=True) + if _decode(field_type).upper() != 'VECTOR': + continue + index_params = self._find_in_kv_pairs(attr, 'index', case_insensitive=True) + if index_params and isinstance(index_params, (list, tuple)): + dim_raw = self._find_in_kv_pairs(index_params, 'dimensions', case_insensitive=True) + if dim_raw is not None: + try: + existing = int(dim_raw) + except (ValueError, TypeError): + pass + break + + if existing is None: + log.warning( + f'Could not determine vector dimension for {index_name} from FT.INFO response, ' + 'skipping dimension check.' + ) + return + if existing != dimension: + raise ValueError( + f'Collection {collection_name!r} was created with dim={existing}, refusing to ' + f'insert vectors with dim={dimension}. Recreate the collection (e.g., via ' + 'VECTOR_DB_CLIENT.delete_collection) if you intend to switch embedding models.' + ) + + def has_collection(self, collection_name: str) -> bool: + index_name = self._index_name(collection_name) + try: + self._g['glide_ft'].info(self.client, index_name) + return True + except self._g['RequestError'] as e: + msg = str(e).lower() + if 'no such index' in msg or 'unknown index' in msg or 'not found in database' in msg: + return False + log.warning(f'Unexpected FT.INFO response for collection {collection_name}: {e}') + raise + + def delete_collection(self, collection_name: str): + index_name = self._index_name(collection_name) + try: + self._g['glide_ft'].dropindex(self.client, index_name) + log.info(f'Dropped index {index_name}') + except self._g['RequestError'] as e: + log.debug(f'Could not drop index {index_name}: {e}') + + self._delete_keys_by_prefix(self._key_prefix(collection_name)) + + def insert(self, collection_name: str, items: list[VectorItem]): + if not items: + return + + dimension = len(items[0]['vector']) + if not self.has_collection(collection_name): + self._create_index(collection_name, dimension) + else: + self._verify_collection_dimension(collection_name, dimension) + + # Individual HSET rather than Batch.exec() — each command gets its own timeout. + # HNSW indexing can take 1-4s per vector (ef_construction=200), and Batch.exec() + # applies a single timeout to ALL commands, causing all-or-nothing failures on + # large inserts. + for item in items: + metadata = process_metadata(item['metadata']) if item.get('metadata') else {} + mapping = { + 'id': item['id'], + 'vector': _vector_to_bytes(item['vector']), + 'text': item['text'], + 'metadata_json': json.dumps(metadata), + # `or ''` prevents indexing literal 'None' as a TAG value, which would + # poison $ne / equality queries. + 'hash': str(metadata.get('hash') or ''), + 'file_id': str(metadata.get('file_id') or ''), + 'source': str(metadata.get('source') or ''), + 'knowledge_base_id': str(metadata.get('knowledge_base_id') or ''), + } + self.batch_client.hset(self._item_key(collection_name, item['id']), mapping) + + log.debug(f'Inserted {len(items)} items into collection {collection_name}') + + def upsert(self, collection_name: str, items: list[VectorItem]): + self.insert(collection_name, items) + + def search( + self, + collection_name: str, + vectors: list[list[float | int]], + filter: dict | None = None, + limit: int = 10, + ) -> SearchResult | None: + if not vectors: + return None + if not self.has_collection(collection_name): + return None + + filter_expr = _build_filter_expression(filter) if filter else '' + query_str = ( + f'({filter_expr})=>[KNN {limit} @vector $query_vec]' + if filter_expr + else f'*=>[KNN {limit} @vector $query_vec]' + ) + + g = self._g + try: + opts = g['FtSearchOptions']( + params={'query_vec': _vector_to_bytes(vectors[0])}, + limit=g['FtSearchLimit'](offset=0, count=limit), + ) + result = g['glide_ft'].search(self.client, self._index_name(collection_name), query_str, opts) + except g['RequestError'] as e: + log.error(f'Valkey search error on collection {collection_name}: {e}') + return None + + return self._parse_glide_search_response(result, include_score=True) + + def query(self, collection_name: str, filter: dict, limit: int | None = None) -> GetResult | None: + if not self.has_collection(collection_name): + return None + if not filter: + return self.get(collection_name, limit=limit) + + query_str = _build_filter_expression(filter) + if not query_str: + return self.get(collection_name, limit=limit) + + # Hard cap when no limit provided — FT.SEARCH requires a finite count. + effective_limit = limit if limit and limit > 0 else 10000 + if not (limit and limit > 0): + log.warning( + f'query() called without a limit on collection {collection_name}; ' + f'capping at {effective_limit} results. Pass an explicit limit to avoid silent truncation.' + ) + + g = self._g + try: + opts = g['FtSearchOptions']( + return_fields=[ + g['ReturnField'](field_identifier='id'), + g['ReturnField'](field_identifier='text'), + g['ReturnField'](field_identifier='metadata_json'), + ], + limit=g['FtSearchLimit'](offset=0, count=effective_limit), + ) + result = g['glide_ft'].search(self.client, self._index_name(collection_name), query_str, opts) + except g['RequestError'] as e: + log.error(f'Valkey query error on collection {collection_name}: {e}') + return None + + return self._parse_glide_search_response(result, include_score=False) + + def get(self, collection_name: str, limit: int | None = None) -> GetResult | None: + if not self.has_collection(collection_name): + return None + + # FT.SEARCH "*" wildcard not yet in a tagged valkey-search release (tracked in #957). + # SCAN fallback is acceptable here — get() is not on the hot search path. + prefix = self._key_prefix(collection_name) + ids, documents, metadatas = [], [], [] + cursor = '0' + while True: + scan_result = self.client.scan(cursor=cursor, match=f'{prefix}*', count=500) + cursor = _decode(scan_result[0]) + keys = scan_result[1] + if keys: + batch = self._g['Batch'](is_atomic=False) + for key in keys: + batch.hgetall(key) + results = self.client.exec(batch, raise_on_error=False) or [] + for fields in results: + if not fields: + continue + ids.append(_decode(fields.get(b'id', b''))) + documents.append(_decode(fields.get(b'text', b''))) + try: + metadatas.append(json.loads(_decode(fields.get(b'metadata_json', b'{}')))) + except (json.JSONDecodeError, TypeError): + metadatas.append({}) + if limit is not None and limit > 0 and len(ids) >= limit: + return GetResult(ids=[ids], documents=[documents], metadatas=[metadatas]) + if cursor == '0': + break + + return GetResult(ids=[ids], documents=[documents], metadatas=[metadatas]) + + def delete( + self, + collection_name: str, + ids: list[str] | None = None, + filter: dict | None = None, + ): + if ids: + keys = [self._item_key(collection_name, item_id) for item_id in ids] + try: + self.batch_client.delete(keys) + except self._g['RequestError'] as e: + log.error(f'Valkey delete error on collection {collection_name}: {e}') + return + + if not filter: + return + + filter_expr = _build_filter_expression(filter) + if not filter_expr: + return + + index_name = self._index_name(collection_name) + page_size = 10000 + g = self._g + while True: + try: + opts = g['FtSearchOptions']( + return_fields=[g['ReturnField'](field_identifier='id')], + limit=g['FtSearchLimit'](offset=0, count=page_size), + ) + result = g['glide_ft'].search(self.client, index_name, filter_expr, opts) + except g['RequestError'] as e: + log.error(f'Valkey delete-by-filter error on collection {collection_name}: {e}') + return + + if not result or result[0] == 0: + return + + keys_map = result[1] if len(result) > 1 else {} + keys = [_decode(k) for k in keys_map.keys()] if isinstance(keys_map, dict) else [] + if not keys: + return + self.batch_client.delete(keys) + if len(keys) < page_size: + return + + def reset(self): + glide_ft = self._g['glide_ft'] + collections: list[str] = [] + try: + indexes = glide_ft.list(self.client) or [] + idx_prefix = f'idx:{self.collection_prefix}:' + for idx in indexes: + name = _decode(idx) + if name.startswith(idx_prefix): + collections.append(name[len(idx_prefix) :]) + try: + glide_ft.dropindex(self.client, idx) + log.info(f'Dropped index: {name}') + except Exception as e: + log.error(f'Error dropping index {name}: {e}') + except Exception as e: + log.error(f'Error listing indexes during reset: {e}') + + for collection in collections: + self._delete_keys_by_prefix(self._key_prefix(collection)) + log.info(f'Valkey vector store reset complete (prefix: {self.collection_prefix})') + + def _delete_keys_by_prefix(self, prefix: str) -> None: + cursor = '0' + while True: + scan_result = self.client.scan(cursor=cursor, match=f'{prefix}*', count=500) + cursor = _decode(scan_result[0]) + keys = scan_result[1] + if keys: + self.batch_client.delete(keys) + if cursor == '0': + break + + @staticmethod + def _decode_kv_pairs(fields) -> dict: + """Decode a flat [k1, v1, k2, v2, ...] wire array into a dict.""" + if not fields: + return {} + if len(fields) % 2 != 0: + fields = fields[:-1] + out = {} + for k, v in zip(fields[::2], fields[1::2]): + key = _decode(k) + if isinstance(v, (bytes, bytearray)): + try: + val = v.decode() + except UnicodeDecodeError: + val = v + else: + val = v + out[key] = val + return out + + @staticmethod + def _find_in_kv_pairs(pairs, target: str, case_insensitive: bool = False): + """Look up a value in a flat [k1, v1, k2, v2, ...] array or dict.""" + if isinstance(pairs, dict): + needle = target.lower() if case_insensitive else target + for k, v in pairs.items(): + key = _decode(k) + if (key.lower() if case_insensitive else key) == needle: + return v + return None + if not isinstance(pairs, (list, tuple)) or len(pairs) < 2: + return None + needle = target.lower() if case_insensitive else target + for j in range(0, len(pairs) - 1, 2): + key = _decode(pairs[j]) + if (key.lower() if case_insensitive else key) == needle: + return pairs[j + 1] + return None + + def _parse_glide_search_response(self, result, include_score: bool) -> SearchResult | GetResult | None: + """Parse ft.search response: [total_count, {key: {field: value, ...}, ...}]""" + empty_search = SearchResult(ids=[[]], distances=[[]], documents=[[]], metadatas=[[]]) + empty_get = GetResult(ids=[[]], documents=[[]], metadatas=[[]]) + if not result or result[0] == 0: + return empty_search if include_score else empty_get + + docs_map = result[1] if len(result) > 1 else {} + if not isinstance(docs_map, dict): + return empty_search if include_score else empty_get + + ids, documents, metadatas, distances = [], [], [], [] + for _key, fields in docs_map.items(): + if not isinstance(fields, dict): + continue + ids.append(_decode(fields.get(b'id', b''))) + documents.append(_decode(fields.get(b'text', b''))) + try: + metadatas.append(json.loads(_decode(fields.get(b'metadata_json', b'{}')))) + except (json.JSONDecodeError, TypeError): + metadatas.append({}) + + if include_score: + try: + raw_score = _decode(fields.get(b'__vector_score', b'0')) + distances.append(self._normalize_score(float(raw_score))) + except (ValueError, TypeError): + distances.append(0.0) + + if not include_score: + return GetResult(ids=[ids], documents=[documents], metadatas=[metadatas]) + + return SearchResult(ids=[ids], distances=[distances], documents=[documents], metadatas=[metadatas]) + + def _normalize_score(self, score: float) -> float: + """Convert valkey-search __vector_score (a distance, lower = more similar) to [0, 1] similarity. + + All metrics return distance: COSINE/IP in [0, 2] for unit vectors, L2 in [0, ∞). + """ + if self.distance_metric == 'COSINE': + # COSINE distance: 0 (identical) → 2 (opposite). Map to similarity [1, -1], clamp [0, 1]. + return max(0.0, min(1.0, 1.0 - score)) + if self.distance_metric == 'L2': + # L2 distance: 0 (identical) → ∞. + return 1.0 / (1.0 + score) + # IP: distance = 1 - inner_product + return max(0.0, min(1.0, 1.0 - score)) diff --git a/backend/open_webui/retrieval/vector/factory.py b/backend/open_webui/retrieval/vector/factory.py index 59ebb1c4e4..3080956163 100644 --- a/backend/open_webui/retrieval/vector/factory.py +++ b/backend/open_webui/retrieval/vector/factory.py @@ -80,6 +80,10 @@ class Vector: from open_webui.retrieval.vector.dbs.weaviate import WeaviateClient return WeaviateClient() + case VectorType.VALKEY: + from open_webui.retrieval.vector.dbs.valkey import ValkeyClient + + return ValkeyClient() case _: raise ValueError(f'Unsupported vector type: {vector_type}') diff --git a/backend/open_webui/retrieval/vector/type.py b/backend/open_webui/retrieval/vector/type.py index 999aee9c54..15e6da0f9e 100644 --- a/backend/open_webui/retrieval/vector/type.py +++ b/backend/open_webui/retrieval/vector/type.py @@ -14,3 +14,4 @@ class VectorType(StrEnum): S3VECTOR = 's3vector' WEAVIATE = 'weaviate' OPENGAUSS = 'opengauss' + VALKEY = 'valkey' diff --git a/backend/open_webui/retrieval/web/bing.py b/backend/open_webui/retrieval/web/bing.py index b026302b4b..00449f9091 100644 --- a/backend/open_webui/retrieval/web/bing.py +++ b/backend/open_webui/retrieval/web/bing.py @@ -64,5 +64,12 @@ def main(): args = parser.parse_args() - results = search_bing(args.locale, args.query, args.count, args.filter) + results = search_bing( + os.environ.get('BING_SEARCH_V7_SUBSCRIPTION_KEY', ''), + os.environ.get('BING_SEARCH_V7_ENDPOINT', 'https://api.bing.microsoft.com/v7.0/search'), + args.locale, + args.query, + args.count, + args.filter, + ) pprint(results) diff --git a/backend/open_webui/retrieval/web/brave.py b/backend/open_webui/retrieval/web/brave.py index eb80094dbb..f785cbe779 100644 --- a/backend/open_webui/retrieval/web/brave.py +++ b/backend/open_webui/retrieval/web/brave.py @@ -1,20 +1,26 @@ from __future__ import annotations +import asyncio import logging -import time -import requests from open_webui.retrieval.web.main import SearchResult, get_filtered_results +from open_webui.utils.session_pool import get_session log = logging.getLogger(__name__) +# Brave free-tier rate limit: 1 request per second. +_RATE_LIMIT_RETRY_DELAY = 1.0 -def search_brave(api_key: str, query: str, count: int, filter_list: list[str | None] = None) -> list[SearchResult]: - """Search using Brave's Search API and return the results as a list of SearchResult objects. - Args: - api_key (str): A Brave Search API key - query (str): The query to search for +async def search_brave( + api_key: str, + query: str, + count: int, + filter_list: list[str | None] | None = None, +) -> list[SearchResult]: + """Query the Brave Web Search API and return normalised results. + + Retries once on HTTP 429 (rate-limit) after a short delay. """ url = 'https://api.search.brave.com/res/v1/web/search' headers = { @@ -24,27 +30,27 @@ def search_brave(api_key: str, query: str, count: int, filter_list: list[str | N } params = {'q': query, 'count': count} - response = requests.get(url, headers=headers, params=params) + session = await get_session() + async with session.get(url, headers=headers, params=params) as response: + if response.status == 429: + log.info('Brave Search rate-limited (429); retrying after %.1fs', _RATE_LIMIT_RETRY_DELAY) + await asyncio.sleep(_RATE_LIMIT_RETRY_DELAY) + async with session.get(url, headers=headers, params=params) as retry_resp: + retry_resp.raise_for_status() + payload = await retry_resp.json() + else: + response.raise_for_status() + payload = await response.json() - # Handle 429 rate limiting - Brave free tier allows 1 request/second - # If rate limited, wait 1 second and retry once before failing - if response.status_code == 429: - log.info('Brave Search API rate limited (429), retrying after 1 second...') - time.sleep(1) - response = requests.get(url, headers=headers, params=params) - - response.raise_for_status() - - json_response = response.json() - results = json_response.get('web', {}).get('results', []) + web_results = payload.get('web', {}).get('results', []) if filter_list: - results = get_filtered_results(results, filter_list) + web_results = get_filtered_results(web_results, filter_list) return [ SearchResult( - link=result['url'], - title=result.get('title'), - snippet=result.get('description'), + link=item.get('url', ''), + title=item.get('title'), + snippet=item.get('description'), ) - for result in results[:count] + for item in web_results[:count] ] diff --git a/backend/open_webui/retrieval/web/firecrawl.py b/backend/open_webui/retrieval/web/firecrawl.py index 4bbd4f212b..baffb6207d 100644 --- a/backend/open_webui/retrieval/web/firecrawl.py +++ b/backend/open_webui/retrieval/web/firecrawl.py @@ -197,8 +197,11 @@ def search_firecrawl( }, timeout=count * 3 + 10, ) + # Firecrawl /search has historically returned both `{"data": [...]}` + # (flat list, what v1 did and what frost19k reported under #23966) + # and `{"data": {"web": [...]}}` (current v2). Accept either. data = response.get('data') or {} - results = data.get('web') or [] + results = data if isinstance(data, list) else (data.get('web') or []) if filter_list: from open_webui.retrieval.web.main import get_filtered_results diff --git a/backend/open_webui/retrieval/web/google_pse.py b/backend/open_webui/retrieval/web/google_pse.py index ec7b6d5af8..3b5fe0d685 100644 --- a/backend/open_webui/retrieval/web/google_pse.py +++ b/backend/open_webui/retrieval/web/google_pse.py @@ -2,70 +2,65 @@ from __future__ import annotations import logging -import requests from open_webui.retrieval.web.main import SearchResult, get_filtered_results +from open_webui.utils.session_pool import get_session log = logging.getLogger(__name__) -def search_google_pse( +async def search_google_pse( api_key: str, search_engine_id: str, query: str, count: int, - filter_list: list[str | None] = None, + filter_list: list[str | None] | None = None, referer: str | None = None, ) -> list[SearchResult]: - """Search using Google's Programmable Search Engine API and return the results as a list of SearchResult objects. - Handles pagination for counts greater than 10. + """Query Google Programmable Search Engine with automatic pagination. - Args: - api_key (str): A Programmable Search Engine API key - search_engine_id (str): A Programmable Search Engine ID - query (str): The query to search for - count (int): The number of results to return (max 100, as PSE max results per query is 10 and max page is 10) - filter_list (list[str | None], optional): A list of keywords to filter out from results. Defaults to None. - - Returns: - list[SearchResult]: A list of SearchResult objects. + The PSE API returns at most 10 results per request, so this function + issues multiple requests when ``count > 10``. """ url = 'https://www.googleapis.com/customsearch/v1' - - headers = {'Content-Type': 'application/json'} + headers: dict[str, str] = {'Content-Type': 'application/json'} if referer: headers['Referer'] = referer - all_results = [] - start_index = 1 # Google PSE start parameter is 1-based + all_items: list[dict] = [] + start_index = 1 # PSE uses 1-based pagination - while count > 0: - num_results_this_page = min(count, 10) # Google PSE max results per page is 10 + session = await get_session() + remaining = count + while remaining > 0: + page_size = min(remaining, 10) params = { 'cx': search_engine_id, 'q': query, 'key': api_key, - 'num': num_results_this_page, - 'start': start_index, + 'num': str(page_size), + 'start': str(start_index), } - response = requests.request('GET', url, headers=headers, params=params) - response.raise_for_status() - json_response = response.json() - results = json_response.get('items', []) - if results: # check if results are returned. If not, no more pages to fetch. - all_results.extend(results) - count -= len(results) # Decrement count by the number of results fetched in this page. - start_index += 10 # Increment start index for the next page - else: - break # No more results from Google PSE, break the loop + + async with session.get(url, headers=headers, params=params) as response: + response.raise_for_status() + payload = await response.json() + + items = payload.get('items', []) + if not items: + break + + all_items.extend(items) + remaining -= len(items) + start_index += 10 if filter_list: - all_results = get_filtered_results(all_results, filter_list) + all_items = get_filtered_results(all_items, filter_list) return [ SearchResult( - link=result['link'], - title=result.get('title'), - snippet=result.get('snippet'), + link=item.get('link', ''), + title=item.get('title'), + snippet=item.get('snippet'), ) - for result in all_results + for item in all_items ] diff --git a/backend/open_webui/retrieval/web/kagi.py b/backend/open_webui/retrieval/web/kagi.py index e6ed570011..cb35ccbb22 100644 --- a/backend/open_webui/retrieval/web/kagi.py +++ b/backend/open_webui/retrieval/web/kagi.py @@ -17,21 +17,20 @@ def search_kagi(api_key: str, query: str, count: int, filter_list: Optional[list query (str): The query to search for count (int): The number of results to return """ - url = 'https://kagi.com/api/v0/search' + url = 'https://kagi.com/api/v1/search' headers = { - 'Authorization': f'Bot {api_key}', + 'Authorization': f'Bearer {api_key}', } - params = {'q': query, 'limit': count} + params = {'query': query, 'limit': count} - response = requests.get(url, headers=headers, params=params) + response = requests.post(url, headers=headers, json=params) response.raise_for_status() json_response = response.json() - search_results = json_response.get('data', []) + search_results = json_response.get('data', {}).get('search', []) results = [ SearchResult(link=result['url'], title=result['title'], snippet=result.get('snippet')) for result in search_results - if result['t'] == 0 ] print(results) diff --git a/backend/open_webui/retrieval/web/linkup.py b/backend/open_webui/retrieval/web/linkup.py new file mode 100644 index 0000000000..b62ec9ed53 --- /dev/null +++ b/backend/open_webui/retrieval/web/linkup.py @@ -0,0 +1,74 @@ +import logging +from typing import Optional + +import requests + +from open_webui.retrieval.web.main import SearchResult, get_filtered_results + +log = logging.getLogger(__name__) + +DEFAULT_LINKUP_PARAMS = { + 'url': 'https://api.linkup.so/v1/search', + 'depth': 'standard', + 'outputType': 'sourcedAnswer', +} + + +def search_linkup( + api_key: str, + query: str, + count: int, + filter_list: Optional[list[str]] = None, + params: Optional[dict] = None, +) -> list[SearchResult]: + """Search using the Linkup Search API. + + ``params`` is forwarded almost verbatim as the JSON body; only ``q`` + and ``maxResults`` are injected automatically. The special key + ``url`` (default ``https://api.linkup.so/v1/search``) is popped and + used as the endpoint. + """ + if hasattr(api_key, '__str__'): + api_key = str(api_key) + + merged = {**DEFAULT_LINKUP_PARAMS, **(params or {})} + api_url = str(merged.pop('url', DEFAULT_LINKUP_PARAMS['url'])) + + payload = {**merged, 'q': query, 'maxResults': count} + + try: + response = requests.post( + api_url, + headers={ + 'Authorization': f'Bearer {api_key}', + 'Content-Type': 'application/json', + }, + json=payload, + timeout=30, + ) + response.raise_for_status() + json_response = response.json() + + output_type = merged.get('outputType', 'sourcedAnswer') + search_results = ( + json_response.get('sources', []) if output_type == 'sourcedAnswer' else json_response.get('results', []) + ) + + if filter_list: + search_results = get_filtered_results(search_results, filter_list) + + return [ + SearchResult( + link=r.get('url', ''), + title=r.get('name') or r.get('title'), + snippet=r.get('content') or r.get('text') or r.get('snippet'), + ) + for r in search_results + ][:count] + + except requests.exceptions.RequestException as e: + log.error(f'Linkup API request failed: {e}') + raise Exception(f'Linkup search failed: {str(e)}') + except Exception as e: + log.error(f'Error searching Linkup: {e}') + raise Exception(f'Linkup search error: {str(e)}') diff --git a/backend/open_webui/retrieval/web/perplexity.py b/backend/open_webui/retrieval/web/perplexity.py index 3794057ebc..05f2d5d51c 100644 --- a/backend/open_webui/retrieval/web/perplexity.py +++ b/backend/open_webui/retrieval/web/perplexity.py @@ -2,6 +2,7 @@ import logging from typing import Literal, Optional import requests +from open_webui.env import VERSION from open_webui.retrieval.web.main import SearchResult, get_filtered_results MODELS = Literal[ @@ -64,6 +65,7 @@ def search_perplexity( headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json', + 'X-Pplx-Integration': f'open-webui/{VERSION}', } # Make the API request diff --git a/backend/open_webui/retrieval/web/perplexity_search.py b/backend/open_webui/retrieval/web/perplexity_search.py index dede51cadd..f3284f9586 100644 --- a/backend/open_webui/retrieval/web/perplexity_search.py +++ b/backend/open_webui/retrieval/web/perplexity_search.py @@ -2,6 +2,7 @@ import logging from typing import Literal, Optional import requests +from open_webui.env import VERSION from open_webui.retrieval.web.main import SearchResult, get_filtered_results from open_webui.utils.headers import include_user_info_headers @@ -47,6 +48,7 @@ def search_perplexity_search( headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json', + 'X-Pplx-Integration': f'open-webui/{VERSION}', } # Forward user info headers if user is provided diff --git a/backend/open_webui/retrieval/web/searxng.py b/backend/open_webui/retrieval/web/searxng.py index 67ca8da64a..9c48b0f1b3 100644 --- a/backend/open_webui/retrieval/web/searxng.py +++ b/backend/open_webui/retrieval/web/searxng.py @@ -2,87 +2,65 @@ from __future__ import annotations import logging -import requests from open_webui.retrieval.web.main import SearchResult, get_filtered_results +from open_webui.utils.session_pool import get_session log = logging.getLogger(__name__) +# SearXNG request headers — identifies the bot to instance operators. +_SEARXNG_HEADERS = { + 'User-Agent': 'Open WebUI (https://github.com/open-webui/open-webui) RAG Bot', + 'Accept': 'text/html', + 'Accept-Encoding': 'gzip, deflate', + 'Accept-Language': 'en-US,en;q=0.5', + 'Connection': 'keep-alive', +} -def search_searxng( # noqa: PLR0913 + +async def search_searxng( query_url: str, query: str, count: int, - filter_list: list[str | None] = None, + filter_list: list[str | None] | None = None, **kwargs, ) -> list[SearchResult]: + """Query a SearXNG instance and return results sorted by relevance score. + + Optional keyword arguments (language, safesearch, time_range, categories) + are forwarded directly as SearXNG query parameters. """ - Search a SearXNG instance for a given query and return the results as a list of SearchResult objects. - - The function allows passing additional parameters such as language or time_range to tailor the search result. - - Args: - query_url (str): The base URL of the SearXNG server. - query (str): The search term or question to find in the SearXNG database. - count (int): The maximum number of results to retrieve from the search. - - Keyword Args: - language (str): Language filter for the search results; e.g., "all", "en-US", "es". Defaults to "all". - safesearch (int): Safe search filter for safer web results; 0 = off, 1 = moderate, 2 = strict. Defaults to 1 (moderate). - time_range (str): Time range for filtering results by date; e.g., "2023-04-05..today" or "all-time". Defaults to ''. - categories: (list[str | None]): Specific categories within which the search should be performed, defaulting to an empty string if not provided. - - Returns: - list[SearchResult]: A list of SearchResults sorted by relevance score in descending order. - - Raise: - requests.exceptions.RequestException: If a request error occurs during the search process. - """ - - # Default values for optional parameters are provided as empty strings or None when not specified. - language = kwargs.get('language', 'all').strip().rstrip(',') - safesearch = kwargs.get('safesearch', '1') - time_range = kwargs.get('time_range', '') - categories = ''.join(kwargs.get('categories', [])) + # Normalise legacy ````-style URLs by stripping any query string. + if '' in query_url: + query_url = query_url.split('?')[0] params = { 'q': query, 'format': 'json', 'pageno': 1, - 'safesearch': safesearch, - 'language': language, - 'time_range': time_range, - 'categories': categories, + 'safesearch': kwargs.get('safesearch', '1'), + 'language': kwargs.get('language', 'all').strip().rstrip(','), + 'time_range': kwargs.get('time_range', ''), + 'categories': ''.join(kwargs.get('categories', [])), 'theme': 'simple', 'image_proxy': 0, } - # Legacy query format - if '' in query_url: - # Strip all query parameters from the URL - query_url = query_url.split('?')[0] + log.debug('searching %s', query_url) - log.debug(f'searching {query_url}') + session = await get_session() + async with session.get(query_url, headers=_SEARXNG_HEADERS, params=params) as response: + response.raise_for_status() + payload = await response.json() - response = requests.get( - query_url, - headers={ - 'User-Agent': 'Open WebUI (https://github.com/open-webui/open-webui) RAG Bot', - 'Accept': 'text/html', - 'Accept-Encoding': 'gzip, deflate', - 'Accept-Language': 'en-US,en;q=0.5', - 'Connection': 'keep-alive', - }, - params=params, - ) - - response.raise_for_status() # Raise an exception for HTTP errors. - - json_response = response.json() - results = json_response.get('results', []) - sorted_results = sorted(results, key=lambda x: x.get('score', 0), reverse=True) + results = sorted(payload.get('results', []), key=lambda x: x.get('score', 0), reverse=True) if filter_list: - sorted_results = get_filtered_results(sorted_results, filter_list) + results = get_filtered_results(results, filter_list) + return [ - SearchResult(link=result['url'], title=result.get('title'), snippet=result.get('content')) - for result in sorted_results[:count] + SearchResult( + link=item.get('url', ''), + title=item.get('title'), + snippet=item.get('content'), + ) + for item in results[:count] ] diff --git a/backend/open_webui/retrieval/web/serper.py b/backend/open_webui/retrieval/web/serper.py index 91cb78d4f4..1304529404 100644 --- a/backend/open_webui/retrieval/web/serper.py +++ b/backend/open_webui/retrieval/web/serper.py @@ -3,36 +3,39 @@ from __future__ import annotations import json import logging -import requests from open_webui.retrieval.web.main import SearchResult, get_filtered_results +from open_webui.utils.session_pool import get_session log = logging.getLogger(__name__) -def search_serper(api_key: str, query: str, count: int, filter_list: list[str | None] = None) -> list[SearchResult]: - """Search using serper.dev's API and return the results as a list of SearchResult objects. +async def search_serper( + api_key: str, + query: str, + count: int, + filter_list: list[str | None] | None = None, +) -> list[SearchResult]: + """Query the serper.dev Google Search API and return normalised results. - Args: - api_key (str): A serper.dev API key - query (str): The query to search for + Results are sorted by their position field before truncation. """ url = 'https://google.serper.dev/search' - - payload = json.dumps({'q': query}) headers = {'X-API-KEY': api_key, 'Content-Type': 'application/json'} - response = requests.request('POST', url, headers=headers, data=payload) - response.raise_for_status() + session = await get_session() + async with session.post(url, headers=headers, data=json.dumps({'q': query})) as response: + response.raise_for_status() + payload = await response.json() - json_response = response.json() - results = sorted(json_response.get('organic', []), key=lambda x: x.get('position', 0)) + organic = sorted(payload.get('organic', []), key=lambda item: item.get('position', 0)) if filter_list: - results = get_filtered_results(results, filter_list) + organic = get_filtered_results(organic, filter_list) + return [ SearchResult( - link=result['link'], - title=result.get('title'), - snippet=result.get('snippet'), + link=item.get('link', ''), + title=item.get('title'), + snippet=item.get('snippet'), ) - for result in results[:count] + for item in organic[:count] ] diff --git a/backend/open_webui/retrieval/web/serpstack.py b/backend/open_webui/retrieval/web/serpstack.py index be034e1594..532246c11a 100644 --- a/backend/open_webui/retrieval/web/serpstack.py +++ b/backend/open_webui/retrieval/web/serpstack.py @@ -2,42 +2,41 @@ from __future__ import annotations import logging -import requests from open_webui.retrieval.web.main import SearchResult, get_filtered_results +from open_webui.utils.session_pool import get_session log = logging.getLogger(__name__) -def search_serpstack( +async def search_serpstack( api_key: str, query: str, count: int, - filter_list: list[str | None] = None, + filter_list: list[str | None] | None = None, https_enabled: bool = True, ) -> list[SearchResult]: - """Search using serpstack.com's and return the results as a list of SearchResult objects. + """Query the serpstack.com API and return normalised results. - Args: - api_key (str): A serpstack.com API key - query (str): The query to search for - https_enabled (bool): Whether to use HTTPS or HTTP for the API request + Uses HTTPS by default; set ``https_enabled=False`` for free-tier HTTP access. """ - url = f'{"https" if https_enabled else "http"}://api.serpstack.com/search' + scheme = 'https' if https_enabled else 'http' + url = f'{scheme}://api.serpstack.com/search' + params = {'access_key': api_key, 'query': query} - headers = {'Content-Type': 'application/json'} - params = { - 'access_key': api_key, - 'query': query, - } + session = await get_session() + async with session.get(url, params=params) as response: + response.raise_for_status() + payload = await response.json() - response = requests.request('POST', url, headers=headers, params=params) - response.raise_for_status() - - json_response = response.json() - results = sorted(json_response.get('organic_results', []), key=lambda x: x.get('position', 0)) + organic = sorted(payload.get('organic_results', []), key=lambda x: x.get('position', 0)) if filter_list: - results = get_filtered_results(results, filter_list) + organic = get_filtered_results(organic, filter_list) + return [ - SearchResult(link=result['url'], title=result.get('title'), snippet=result.get('snippet')) - for result in results[:count] + SearchResult( + link=item.get('url', ''), + title=item.get('title'), + snippet=item.get('snippet'), + ) + for item in organic[:count] ] diff --git a/backend/open_webui/retrieval/web/utils.py b/backend/open_webui/retrieval/web/utils.py index 4f2743d169..afa73a9e0e 100644 --- a/backend/open_webui/retrieval/web/utils.py +++ b/backend/open_webui/retrieval/web/utils.py @@ -19,9 +19,13 @@ from typing import ( ) import aiohttp +import aiohttp.resolver import certifi import requests +import urllib3.connection +import urllib3.connectionpool import validators +from requests.adapters import HTTPAdapter from fastapi.concurrency import run_in_threadpool from langchain_community.document_loaders import PlaywrightURLLoader, WebBaseLoader from langchain_community.document_loaders.base import BaseLoader @@ -94,7 +98,7 @@ def validate_url(url: Union[str, Sequence[str]]): # Get IPv4 and IPv6 addresses ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname) # Check if any of the resolved addresses are private - # This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader + # DNS rebinding is mitigated at the connection layer; see _SSRFSafeResolver / _SSRFSafeAdapter for ip in ipv4_addresses + ipv6_addresses: addr = ipaddress.ip_address(ip) if not addr.is_global: @@ -118,6 +122,81 @@ def safe_validate_urls(url: Sequence[str]) -> Sequence[str]: return valid_urls +def _ssrf_safe_new_conn(self): + """Resolve DNS, validate all IPs are global, connect to validated IP. + + Replaces urllib3's _new_conn so the DNS lookup that feeds the actual TCP + connect is the same one we validate — no second resolution, no rebinding + window. + """ + host = getattr(self, '_dns_host', self.host) + port = self.port + infos = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM) + if not infos: + raise OSError(f'getaddrinfo for {host!r} returned empty list') + if not ENABLE_RAG_LOCAL_WEB_FETCH: + for _, _, _, _, sa in infos: + if not ipaddress.ip_address(sa[0]).is_global: + raise ValueError(ERROR_MESSAGES.INVALID_URL) + err = None + for fam, typ, proto, _, sa in infos: + sock = None + try: + sock = socket.socket(fam, typ, proto) + if self.timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: + sock.settimeout(self.timeout) + if getattr(self, 'source_address', None): + sock.bind(self.source_address) + for opt in getattr(self, 'socket_options', None) or (): + sock.setsockopt(*opt) + sock.connect(sa) + return sock + except OSError as exc: + err = exc + if sock is not None: + sock.close() + raise err or OSError(f'connect to {host!r}:{port} failed') + + +class _SafeHTTPConn(urllib3.connection.HTTPConnection): + _new_conn = _ssrf_safe_new_conn + + +class _SafeHTTPSConn(urllib3.connection.HTTPSConnection): + _new_conn = _ssrf_safe_new_conn + + +class _SafeHTTPPool(urllib3.connectionpool.HTTPConnectionPool): + ConnectionCls = _SafeHTTPConn + + +class _SafeHTTPSPool(urllib3.connectionpool.HTTPSConnectionPool): + ConnectionCls = _SafeHTTPSConn + + +class _SSRFSafeAdapter(HTTPAdapter): + """requests transport adapter that validates resolved IPs at connect time.""" + + def init_poolmanager(self, *args, **kwargs): + super().init_poolmanager(*args, **kwargs) + self.poolmanager.pool_classes_by_scheme = { + 'http': _SafeHTTPPool, + 'https': _SafeHTTPSPool, + } + + +class _SSRFSafeResolver(aiohttp.resolver.DefaultResolver): + """aiohttp resolver that rejects non-global IPs unless local fetch is on.""" + + async def resolve(self, host, port=0, family=socket.AF_INET): + results = await super().resolve(host, port, family) + if not ENABLE_RAG_LOCAL_WEB_FETCH: + for entry in results: + if not ipaddress.ip_address(entry['host']).is_global: + raise ValueError(ERROR_MESSAGES.INVALID_URL) + return results + + def extract_metadata(soup, url): metadata = {'source': url} if title := soup.find('title'): @@ -421,6 +500,62 @@ class SafePlaywrightURLLoader(PlaywrightURLLoader, RateLimitMixin, URLProcessing self.trust_env = trust_env self.playwright_timeout = playwright_timeout + def _intercept_navigation_sync(self, route, request=None): + req = request or route.request + + if req.resource_type != 'document': + route.continue_() + return + + try: + validate_url(req.url) + except Exception: + route.abort() + return + + if AIOHTTP_CLIENT_ALLOW_REDIRECTS: + resp = route.fetch() + else: + try: + resp = route.fetch(max_redirects=0) + except TypeError: + route.abort() + return + + if 300 <= resp.status < 400: + route.abort() + return + + route.fulfill(response=resp) + + async def _intercept_navigation(self, route, request=None): + req = request or route.request + + if req.resource_type != 'document': + await route.continue_() + return + + try: + await run_in_threadpool(validate_url, req.url) + except Exception: + await route.abort() + return + + if AIOHTTP_CLIENT_ALLOW_REDIRECTS: + resp = await route.fetch() + else: + try: + resp = await route.fetch(max_redirects=0) + except TypeError: + await route.abort() + return + + if 300 <= resp.status < 400: + await route.abort() + return + + await route.fulfill(response=resp) + def lazy_load(self) -> Iterator[Document]: """Safely load URLs synchronously with support for remote browser.""" from playwright.sync_api import sync_playwright @@ -436,6 +571,7 @@ class SafePlaywrightURLLoader(PlaywrightURLLoader, RateLimitMixin, URLProcessing try: self._safe_process_url_sync(url) page = browser.new_page() + page.route('**/*', self._intercept_navigation_sync) response = page.goto(url, timeout=self.playwright_timeout) if response is None: raise ValueError(f'page.goto() returned None for url {url}') @@ -465,6 +601,7 @@ class SafePlaywrightURLLoader(PlaywrightURLLoader, RateLimitMixin, URLProcessing try: await self._safe_process_url(url) page = await browser.new_page() + await page.route('**/*', self._intercept_navigation) response = await page.goto(url, timeout=self.playwright_timeout) if response is None: raise ValueError(f'page.goto() returned None for url {url}') @@ -512,8 +649,12 @@ class SafeWebBaseLoader(WebBaseLoader): 'allow_redirects': AIOHTTP_CLIENT_ALLOW_REDIRECTS, } + self.session.mount('http://', _SSRFSafeAdapter()) + self.session.mount('https://', _SSRFSafeAdapter()) + async def _fetch(self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5) -> str: - async with aiohttp.ClientSession(trust_env=self.trust_env) as session: + connector = aiohttp.TCPConnector(resolver=_SSRFSafeResolver()) + async with aiohttp.ClientSession(trust_env=self.trust_env, connector=connector) as session: for i in range(retries): try: kwargs: Dict = dict( diff --git a/backend/open_webui/routers/audio.py b/backend/open_webui/routers/audio.py index bba91c2d5a..441915972d 100644 --- a/backend/open_webui/routers/audio.py +++ b/backend/open_webui/routers/audio.py @@ -1,3 +1,5 @@ +"""Audio router — TTS speech synthesis and STT transcription endpoints.""" + import asyncio import base64 import hashlib @@ -8,17 +10,15 @@ import logging import mimetypes import os import uuid -from concurrent.futures import ThreadPoolExecutor from fnmatch import fnmatch +from pathlib import Path from typing import Optional import aiofiles import aiohttp -import requests from fastapi import ( APIRouter, Depends, - FastAPI, File, Form, HTTPException, @@ -26,8 +26,12 @@ from fastapi import ( UploadFile, status, ) -from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse +from pydantic import BaseModel +from pydub import AudioSegment +from pydub.silence import split_on_silence +from pydub.utils import mediainfo + from open_webui.config import ( CACHE_DIR, ELEVENLABS_API_BASE_URL, @@ -52,36 +56,22 @@ from open_webui.utils.access_control import has_permission from open_webui.utils.auth import get_admin_user, get_verified_user from open_webui.utils.headers import include_user_info_headers from open_webui.utils.misc import strict_match_mime_type -from pydantic import BaseModel -from pydub import AudioSegment -from pydub.silence import split_on_silence - -router = APIRouter() - -# Constants -MAX_FILE_SIZE_MB = 20 -MAX_FILE_SIZE = MAX_FILE_SIZE_MB * 1024 * 1024 # Convert MB to bytes -AZURE_MAX_FILE_SIZE_MB = 200 -AZURE_MAX_FILE_SIZE = AZURE_MAX_FILE_SIZE_MB * 1024 * 1024 # Convert MB to bytes +from open_webui.utils.session_pool import get_session log = logging.getLogger(__name__) +router = APIRouter() + +# --- Constants --- + +MAX_FILE_SIZE_MB: int = 20 +MAX_FILE_SIZE: int = MAX_FILE_SIZE_MB * 1024 * 1024 +AZURE_MAX_FILE_SIZE_MB: int = 200 +AZURE_MAX_FILE_SIZE: int = AZURE_MAX_FILE_SIZE_MB * 1024 * 1024 SPEECH_CACHE_DIR = CACHE_DIR / 'audio' / 'speech' SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True) -########################################## -# -# Utility functions -# Let what is spoken here be heard clearly, and let -# no voice be reduced to noise along the way. -# -########################################## - -from pydub import AudioSegment -from pydub.utils import mediainfo - - def is_audio_conversion_required(file_path): """ Check if the given audio file needs conversion to mp3. @@ -195,13 +185,6 @@ def set_faster_whisper_model(model: str, auto_update: bool = False): return whisper_model -########################################## -# -# Audio API -# -########################################## - - class TTSConfigForm(BaseModel): OPENAI_API_BASE_URL: str OPENAI_API_KEY: str @@ -283,6 +266,7 @@ async def get_audio_config(request: Request, user=Depends(get_admin_user)): @router.post('/config/update') async def update_audio_config(request: Request, form_data: AudioConfigUpdateForm, user=Depends(get_admin_user)): + # TTS settings request.app.state.config.TTS_OPENAI_API_BASE_URL = form_data.tts.OPENAI_API_BASE_URL request.app.state.config.TTS_OPENAI_API_KEY = form_data.tts.OPENAI_API_KEY request.app.state.config.TTS_OPENAI_PARAMS = form_data.tts.OPENAI_PARAMS @@ -297,13 +281,13 @@ async def update_audio_config(request: Request, form_data: AudioConfigUpdateForm request.app.state.config.TTS_MISTRAL_API_KEY = form_data.tts.MISTRAL_API_KEY request.app.state.config.TTS_MISTRAL_API_BASE_URL = form_data.tts.MISTRAL_API_BASE_URL + # STT settings request.app.state.config.STT_OPENAI_API_BASE_URL = form_data.stt.OPENAI_API_BASE_URL request.app.state.config.STT_OPENAI_API_KEY = form_data.stt.OPENAI_API_KEY request.app.state.config.STT_ENGINE = form_data.stt.ENGINE request.app.state.config.STT_MODEL = form_data.stt.MODEL request.app.state.config.STT_SUPPORTED_CONTENT_TYPES = form_data.stt.SUPPORTED_CONTENT_TYPES request.app.state.config.STT_ALLOWED_EXTENSIONS = form_data.stt.ALLOWED_EXTENSIONS - request.app.state.config.WHISPER_MODEL = form_data.stt.WHISPER_MODEL request.app.state.config.DEEPGRAM_API_KEY = form_data.stt.DEEPGRAM_API_KEY request.app.state.config.AUDIO_STT_AZURE_API_KEY = form_data.stt.AZURE_API_KEY @@ -372,9 +356,230 @@ def load_speech_pipeline(request): ) +async def _raise_tts_error(exc: Exception, r=None) -> None: + """Raise a standardised HTTPException from a TTS provider failure.""" + code = r.status if r is not None else 500 + detail = 'Open WebUI: Server Connection Error' + if r is not None: + try: + res = await r.json() + if 'error' in res: + msg = res['error'] + detail = f'External: {msg.get("message", msg) if isinstance(msg, dict) else msg}' + elif 'message' in res: + detail = f'External: {res["message"]}' + except Exception: + detail = f'External: {exc}' + raise HTTPException(status_code=code, detail=detail) + + +async def _write_tts_cache( + file_path: Path, + audio: bytes, + body_path: Path, + payload: dict, +) -> None: + """Persist audio + request metadata to the speech cache.""" + async with aiofiles.open(file_path, 'wb') as f: + await f.write(audio) + async with aiofiles.open(body_path, 'w') as f: + await f.write(json.dumps(payload)) + + +async def _tts_openai(request, payload, file_path, file_body_path, user): + """Generate speech via an OpenAI-compatible TTS endpoint.""" + payload['model'] = request.app.state.config.TTS_MODEL + if not payload.get('voice'): + payload['voice'] = request.app.state.config.TTS_VOICE + payload = {**payload, **(request.app.state.config.TTS_OPENAI_PARAMS or {})} + + headers = { + 'Content-Type': 'application/json', + 'Authorization': f'Bearer {request.app.state.config.TTS_OPENAI_API_KEY}', + } + if ENABLE_FORWARD_USER_INFO_HEADERS: + headers = include_user_info_headers(headers, user) + + r = None + try: + session = await get_session() + r = await session.post( + url=f'{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech', + json=payload, + headers=headers, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) + r.raise_for_status() + + audio_data = await r.read() + content_type = r.headers.get('Content-Type', 'audio/mpeg') + + if not await asyncio.to_thread(transcode_audio_to_mp3, audio_data, content_type, file_path): + async with aiofiles.open(file_path, 'wb') as f: + await f.write(audio_data) + + async with aiofiles.open(file_body_path, 'w') as f: + await f.write(json.dumps(payload)) + + return FileResponse(file_path) + except Exception as exc: + log.exception(exc) + await _raise_tts_error(exc, r) + + +async def _tts_elevenlabs(request, payload, file_path, file_body_path, user): + """Generate speech via the ElevenLabs TTS API.""" + voice_id = payload.get('voice', '') + if voice_id not in await get_available_voices(request): + raise HTTPException(status_code=400, detail='Invalid voice id') + + r = None + try: + session = await get_session() + async with session.post( + f'{ELEVENLABS_API_BASE_URL}/v1/text-to-speech/{voice_id}', + json={ + 'text': payload['input'], + 'model_id': request.app.state.config.TTS_MODEL, + 'voice_settings': {'stability': 0.5, 'similarity_boost': 0.5}, + }, + headers={ + 'Accept': 'audio/mpeg', + 'Content-Type': 'application/json', + 'xi-api-key': request.app.state.config.TTS_API_KEY, + }, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) as r: + r.raise_for_status() + await _write_tts_cache(file_path, await r.read(), file_body_path, payload) + return FileResponse(file_path) + except Exception as exc: + log.exception(exc) + await _raise_tts_error(exc, r) + + +async def _tts_azure(request, payload, file_path, file_body_path, user): + """Generate speech via Azure Cognitive Services TTS.""" + az_region = request.app.state.config.TTS_AZURE_SPEECH_REGION or 'eastus' + az_base = request.app.state.config.TTS_AZURE_SPEECH_BASE_URL + language = payload.get('voice') or request.app.state.config.TTS_VOICE + locale = '-'.join(language.split('-')[:2]) + output_format = request.app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT + + ssml = ( + f'' + f'{html.escape(payload["input"])}' + f'' + ) + + r = None + try: + session = await get_session() + async with session.post( + (az_base or f'https://{az_region}.tts.speech.microsoft.com') + '/cognitiveservices/v1', + headers={ + 'Ocp-Apim-Subscription-Key': request.app.state.config.TTS_API_KEY, + 'Content-Type': 'application/ssml+xml', + 'X-Microsoft-OutputFormat': output_format, + }, + data=ssml, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) as r: + r.raise_for_status() + await _write_tts_cache(file_path, await r.read(), file_body_path, payload) + return FileResponse(file_path) + except Exception as exc: + log.exception(exc) + await _raise_tts_error(exc, r) + + +async def _tts_transformers(request, payload, file_path, file_body_path, user): + """Generate speech via the local HuggingFace SpeechT5 pipeline (thread-offloaded).""" + import soundfile as sf + import torch + + load_speech_pipeline(request) + + embeddings = request.app.state.speech_speaker_embeddings_dataset + model_name = request.app.state.config.TTS_MODEL + + idx = 6799 + try: + idx = embeddings['filename'].index(model_name) + except (ValueError, KeyError): + log.debug(f'Speaker embedding not found for {model_name}, using default index {idx}') + + def _run_pipeline(): + speaker_embedding = torch.tensor(embeddings[idx]['xvector']).unsqueeze(0) + wav = request.app.state.speech_synthesiser( + payload['input'], # raw text to synthesize + forward_params={ + 'speaker_embeddings': speaker_embedding, + }, + ) + sf.write(str(file_path), wav['audio'], samplerate=wav['sampling_rate']) + + await asyncio.to_thread(_run_pipeline) + + # Audio file already written by sf.write; just persist the request metadata. + async with aiofiles.open(file_body_path, 'w') as f: + await f.write(json.dumps(payload)) + return FileResponse(file_path) + + +async def _tts_mistral(request, payload, file_path, file_body_path, user): + """Generate speech via the Mistral TTS API.""" + api_key = request.app.state.config.TTS_MISTRAL_API_KEY + api_base_url = request.app.state.config.TTS_MISTRAL_API_BASE_URL or 'https://api.mistral.ai/v1' + + if not api_key: + raise HTTPException(status_code=400, detail='Mistral API key is required for Mistral TTS') + + r = None + try: + session = await get_session() + r = await session.post( + url=f'{api_base_url}/audio/speech', + json={ + 'input': payload.get('input', ''), # text to synthesize + 'model': request.app.state.config.TTS_MODEL or 'voxtral-mini-tts-2603', + 'voice_id': payload.get('voice', ''), + 'response_format': 'mp3', + }, + headers={ + 'Content-Type': 'application/json', + 'Authorization': f'Bearer {api_key}', + }, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) + r.raise_for_status() + + res = await r.json() + audio_b64 = res.get('audio_data', '') + if not audio_b64: + raise ValueError('No audio_data in Mistral TTS response') + + await _write_tts_cache(file_path, base64.b64decode(audio_b64), file_body_path, payload) + return FileResponse(file_path) + except Exception as exc: + log.exception(exc) + await _raise_tts_error(exc, r) + + +# Dispatcher map: engine name -> handler +_TTS_ENGINES = { + 'openai': _tts_openai, + 'elevenlabs': _tts_elevenlabs, + 'azure': _tts_azure, + 'transformers': _tts_transformers, + 'mistral': _tts_mistral, +} + + @router.post('/speech') async def speech(request: Request, user=Depends(get_verified_user)): - if request.app.state.config.TTS_ENGINE == '': + engine = request.app.state.config.TTS_ENGINE + if engine == '': raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND, @@ -390,320 +595,36 @@ async def speech(request: Request, user=Depends(get_verified_user)): body = await request.body() name = hashlib.sha256( - body - + str(request.app.state.config.TTS_ENGINE).encode('utf-8') - + str(request.app.state.config.TTS_MODEL).encode('utf-8') + body + str(engine).encode('utf-8') + str(request.app.state.config.TTS_MODEL).encode('utf-8') ).hexdigest() file_path = SPEECH_CACHE_DIR.joinpath(f'{name}.mp3') file_body_path = SPEECH_CACHE_DIR.joinpath(f'{name}.json') - # Check if the file already exists in the cache + # Return cached result if available if file_path.is_file(): return FileResponse(file_path) - payload = None try: - payload = json.loads(body.decode('utf-8')) - except Exception as e: - log.exception(e) + payload = json.loads(body) + except Exception as exc: + log.exception(exc) raise HTTPException(status_code=400, detail='Invalid JSON payload') - r = None - if request.app.state.config.TTS_ENGINE == 'openai': - payload['model'] = request.app.state.config.TTS_MODEL + handler = _TTS_ENGINES.get(engine) + if handler is None: + raise HTTPException(status_code=400, detail=f'Unsupported TTS engine: {engine}') - try: - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - payload = { - **payload, - **(request.app.state.config.TTS_OPENAI_PARAMS or {}), - } - - headers = { - 'Content-Type': 'application/json', - 'Authorization': f'Bearer {request.app.state.config.TTS_OPENAI_API_KEY}', - } - if ENABLE_FORWARD_USER_INFO_HEADERS: - headers = include_user_info_headers(headers, user) - - r = await session.post( - url=f'{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech', - json=payload, - headers=headers, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) - - r.raise_for_status() - - audio_data = await r.read() - content_type_header = r.headers.get('Content-Type', 'audio/mpeg') - - if not transcode_audio_to_mp3(audio_data, content_type_header, file_path): - async with aiofiles.open(file_path, 'wb') as f: - await f.write(audio_data) - - async with aiofiles.open(file_body_path, 'w') as f: - await f.write(json.dumps(payload)) - - return FileResponse(file_path) - - except Exception as e: - log.exception(e) - detail = None - - status_code = 500 - detail = f'Open WebUI: Server Connection Error' - - if r is not None: - status_code = r.status - - try: - res = await r.json() - if 'error' in res: - detail = f'External: {res["error"]}' - except Exception: - detail = f'External: {e}' - - raise HTTPException( - status_code=status_code, - detail=detail, - ) - - elif request.app.state.config.TTS_ENGINE == 'elevenlabs': - voice_id = payload.get('voice', '') - - if voice_id not in await get_available_voices(request): - raise HTTPException( - status_code=400, - detail='Invalid voice id', - ) - - try: - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - async with session.post( - f'{ELEVENLABS_API_BASE_URL}/v1/text-to-speech/{voice_id}', - json={ - 'text': payload['input'], - 'model_id': request.app.state.config.TTS_MODEL, - 'voice_settings': {'stability': 0.5, 'similarity_boost': 0.5}, - }, - headers={ - 'Accept': 'audio/mpeg', - 'Content-Type': 'application/json', - 'xi-api-key': request.app.state.config.TTS_API_KEY, - }, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as r: - r.raise_for_status() - - async with aiofiles.open(file_path, 'wb') as f: - await f.write(await r.read()) - - async with aiofiles.open(file_body_path, 'w') as f: - await f.write(json.dumps(payload)) - - return FileResponse(file_path) - - except Exception as e: - log.exception(e) - detail = None - - try: - if r.status != 200: - res = await r.json() - if 'error' in res: - detail = f'External: {res["error"].get("message", "")}' - except Exception: - detail = f'External: {e}' - - raise HTTPException( - status_code=getattr(r, 'status', 500) if r else 500, - detail=detail if detail else 'Open WebUI: Server Connection Error', - ) - - elif request.app.state.config.TTS_ENGINE == 'azure': - try: - payload = json.loads(body.decode('utf-8')) - except Exception as e: - log.exception(e) - raise HTTPException(status_code=400, detail='Invalid JSON payload') - - region = request.app.state.config.TTS_AZURE_SPEECH_REGION or 'eastus' - base_url = request.app.state.config.TTS_AZURE_SPEECH_BASE_URL - language = request.app.state.config.TTS_VOICE - locale = '-'.join(request.app.state.config.TTS_VOICE.split('-')[:2]) - output_format = request.app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT - - try: - data = f""" - {html.escape(payload['input'])} - """ - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - async with session.post( - (base_url or f'https://{region}.tts.speech.microsoft.com') + '/cognitiveservices/v1', - headers={ - 'Ocp-Apim-Subscription-Key': request.app.state.config.TTS_API_KEY, - 'Content-Type': 'application/ssml+xml', - 'X-Microsoft-OutputFormat': output_format, - }, - data=data, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as r: - r.raise_for_status() - - async with aiofiles.open(file_path, 'wb') as f: - await f.write(await r.read()) - - async with aiofiles.open(file_body_path, 'w') as f: - await f.write(json.dumps(payload)) - - return FileResponse(file_path) - - except Exception as e: - log.exception(e) - detail = None - - try: - if r.status != 200: - res = await r.json() - if 'error' in res: - detail = f'External: {res["error"].get("message", "")}' - except Exception: - detail = f'External: {e}' - - raise HTTPException( - status_code=getattr(r, 'status', 500) if r else 500, - detail=detail if detail else 'Open WebUI: Server Connection Error', - ) - - elif request.app.state.config.TTS_ENGINE == 'transformers': - payload = None - try: - payload = json.loads(body.decode('utf-8')) - except Exception as e: - log.exception(e) - raise HTTPException(status_code=400, detail='Invalid JSON payload') - - import soundfile as sf - import torch - - load_speech_pipeline(request) - - embeddings_dataset = request.app.state.speech_speaker_embeddings_dataset - - speaker_index = 6799 - try: - speaker_index = embeddings_dataset['filename'].index(request.app.state.config.TTS_MODEL) - except Exception: - pass - - speaker_embedding = torch.tensor(embeddings_dataset[speaker_index]['xvector']).unsqueeze(0) - - speech = request.app.state.speech_synthesiser( - payload['input'], - forward_params={'speaker_embeddings': speaker_embedding}, - ) - - sf.write(file_path, speech['audio'], samplerate=speech['sampling_rate']) - - async with aiofiles.open(file_body_path, 'w') as f: - await f.write(json.dumps(payload)) - - return FileResponse(file_path) - - elif request.app.state.config.TTS_ENGINE == 'mistral': - api_key = request.app.state.config.TTS_MISTRAL_API_KEY - api_base_url = request.app.state.config.TTS_MISTRAL_API_BASE_URL or 'https://api.mistral.ai/v1' - - if not api_key: - raise HTTPException( - status_code=400, - detail='Mistral API key is required for Mistral TTS', - ) - - try: - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - mistral_payload = { - 'input': payload.get('input', ''), - 'model': request.app.state.config.TTS_MODEL or 'voxtral-mini-tts-2603', - 'voice_id': payload.get('voice', ''), - 'response_format': 'mp3', - } - - r = await session.post( - url=f'{api_base_url}/audio/speech', - json=mistral_payload, - headers={ - 'Content-Type': 'application/json', - 'Authorization': f'Bearer {api_key}', - }, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) - - r.raise_for_status() - - res = await r.json() - audio_data = res.get('audio_data', '') - if not audio_data: - raise ValueError('No audio_data in Mistral TTS response') - - audio_bytes = base64.b64decode(audio_data) - - async with aiofiles.open(file_path, 'wb') as f: - await f.write(audio_bytes) - - async with aiofiles.open(file_body_path, 'w') as f: - await f.write(json.dumps(payload)) - - return FileResponse(file_path) - - except Exception as e: - log.exception(e) - detail = None - - status_code = 500 - detail = 'Open WebUI: Server Connection Error' - - if r is not None: - status_code = r.status - - try: - res = await r.json() - if 'error' in res: - detail = f'External: {res["error"]}' - elif 'message' in res: - detail = f'External: {res["message"]}' - except Exception: - detail = f'External: {e}' - - raise HTTPException( - status_code=status_code, - detail=detail, - ) + return await handler(request, payload, file_path, file_body_path, user) -def transcription_handler(request, file_path, metadata, user=None): - filename = os.path.basename(file_path) - file_dir = os.path.dirname(file_path) - id = filename.split('.')[0] +async def _transcribe_whisper(request, file_path, languages, file_dir, id): + if request.app.state.faster_whisper_model is None: + request.app.state.faster_whisper_model = set_faster_whisper_model(request.app.state.config.WHISPER_MODEL) - metadata = metadata or {} + model = request.app.state.faster_whisper_model - languages = [ - metadata.get('language', None) if not WHISPER_LANGUAGE else WHISPER_LANGUAGE, - None, # Always fallback to None in case transcription fails - ] - - if request.app.state.config.STT_ENGINE == '': - if request.app.state.faster_whisper_model is None: - request.app.state.faster_whisper_model = set_faster_whisper_model(request.app.state.config.WHISPER_MODEL) - - model = request.app.state.faster_whisper_model + def _run(): segments, info = model.transcribe( file_path, beam_size=5, @@ -712,158 +633,150 @@ def transcription_handler(request, file_path, metadata, user=None): multilingual=WHISPER_MULTILINGUAL, ) log.info("Detected language '%s' with probability %f" % (info.language, info.language_probability)) + return ''.join([segment.text for segment in list(segments)]) - transcript = ''.join([segment.text for segment in list(segments)]) - data = {'text': transcript.strip()} + transcript = await asyncio.to_thread(_run) + data = {'text': transcript.strip()} - # save the transcript to a json file - transcript_file = os.path.join(file_dir, f'{id}.json') - with open(transcript_file, 'w') as f: - json.dump(data, f) + async with aiofiles.open(os.path.join(file_dir, f'{id}.json'), 'w') as f: + await f.write(json.dumps(data)) - log.debug(data) - return data - elif request.app.state.config.STT_ENGINE == 'openai': - r = None - try: - for language in languages: - payload = { - 'model': request.app.state.config.STT_MODEL, - } + log.debug(data) + return data - if language: - payload['language'] = language - headers = {'Authorization': f'Bearer {request.app.state.config.STT_OPENAI_API_KEY}'} - if user and ENABLE_FORWARD_USER_INFO_HEADERS: - headers = include_user_info_headers(headers, user) +async def _transcribe_openai(request, file_path, filename, languages, file_dir, id, user=None): + """Transcribe audio via an OpenAI-compatible STT endpoint.""" + r = None + try: + session = await get_session() + for language in languages: + payload = {'model': request.app.state.config.STT_MODEL} + if language: + payload['language'] = language - with open(file_path, 'rb') as audio_file: - r = requests.post( - url=f'{request.app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions', - headers=headers, - files={'file': (filename, audio_file)}, - data=payload, - timeout=AIOHTTP_CLIENT_TIMEOUT, - ) + headers = {'Authorization': f'Bearer {request.app.state.config.STT_OPENAI_API_KEY}'} + if user and ENABLE_FORWARD_USER_INFO_HEADERS: + headers = include_user_info_headers(headers, user) - if r.status_code == 200: - # Successful transcription - break + form_data = aiohttp.FormData() + for key, value in payload.items(): + form_data.add_field(key, str(value)) + form_data.add_field('file', open(file_path, 'rb'), filename=filename) - r.raise_for_status() - data = r.json() - - # save the transcript to a json file - transcript_file = os.path.join(file_dir, f'{id}.json') - with open(transcript_file, 'w') as f: - json.dump(data, f) - - return data - except Exception as e: - log.exception(e) - - detail = None - if r is not None: - try: - res = r.json() - if 'error' in res: - detail = f'External: {res["error"].get("message", "")}' - except Exception: - detail = f'External: {e}' - - raise Exception(detail if detail else 'Open WebUI: Server Connection Error') - - elif request.app.state.config.STT_ENGINE == 'deepgram': - try: - # Determine the MIME type of the file - mime, _ = mimetypes.guess_type(file_path) - if not mime: - mime = 'audio/wav' # fallback to wav if undetectable - - # Read the audio file - with open(file_path, 'rb') as f: - file_data = f.read() - - # Build headers and parameters - headers = { - 'Authorization': f'Token {request.app.state.config.DEEPGRAM_API_KEY}', - 'Content-Type': mime, - } - - for language in languages: - params = {} - if request.app.state.config.STT_MODEL: - params['model'] = request.app.state.config.STT_MODEL - - if language: - params['language'] = language - - # Make request to Deepgram API - r = requests.post( - 'https://api.deepgram.com/v1/listen?smart_format=true', - headers=headers, - params=params, - data=file_data, - timeout=AIOHTTP_CLIENT_TIMEOUT, - ) - - if r.status_code == 200: - # Successful transcription - break - - r.raise_for_status() - response_data = r.json() - - # Extract transcript from Deepgram response - try: - transcript = response_data['results']['channels'][0]['alternatives'][0].get('transcript', '') - except (KeyError, IndexError) as e: - log.error(f'Malformed response from Deepgram: {str(e)}') - raise Exception('Failed to parse Deepgram response - unexpected response format') - data = {'text': transcript.strip()} - - # Save transcript - transcript_file = os.path.join(file_dir, f'{id}.json') - with open(transcript_file, 'w') as f: - json.dump(data, f) - - return data - - except Exception as e: - log.exception(e) - detail = None - if r is not None: - try: - res = r.json() - if 'error' in res: - detail = f'External: {res["error"].get("message", "")}' - except Exception: - detail = f'External: {e}' - raise Exception(detail if detail else 'Open WebUI: Server Connection Error') - - elif request.app.state.config.STT_ENGINE == 'azure': - # Check file exists and size - if not os.path.exists(file_path): - raise HTTPException(status_code=400, detail='Audio file not found') - - # Check file size (Azure has a larger limit of 200MB) - file_size = os.path.getsize(file_path) - if file_size > AZURE_MAX_FILE_SIZE: - raise HTTPException( - status_code=400, - detail=f"File size exceeds Azure's limit of {AZURE_MAX_FILE_SIZE_MB}MB", + r = await session.post( + url=f'{request.app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions', + headers=headers, + data=form_data, + ssl=AIOHTTP_CLIENT_SESSION_SSL, ) + if r.status == 200: + break - api_key = request.app.state.config.AUDIO_STT_AZURE_API_KEY - region = request.app.state.config.AUDIO_STT_AZURE_REGION or 'eastus' - locales = request.app.state.config.AUDIO_STT_AZURE_LOCALES - base_url = request.app.state.config.AUDIO_STT_AZURE_BASE_URL - max_speakers = request.app.state.config.AUDIO_STT_AZURE_MAX_SPEAKERS or 3 + r.raise_for_status() + data = await r.json() - # IF NO LOCALES, USE DEFAULTS - if len(locales) < 2: - locales = [ + async with aiofiles.open(os.path.join(file_dir, f'{id}.json'), 'w') as f: + await f.write(json.dumps(data)) + return data + except Exception as e: + log.exception(e) + detail = None + if r is not None: + try: + res = await r.json() + if 'error' in res: + detail = f'External: {res["error"].get("message", "")}' + except Exception: + detail = f'External: {e}' + raise Exception(detail if detail else 'Open WebUI: Server Connection Error') + + +async def _transcribe_deepgram(request, file_path, languages, file_dir, id): + """Transcribe audio via the Deepgram listen API with language fallback.""" + content_type = mimetypes.guess_type(file_path)[0] or 'audio/wav' + + async with aiofiles.open(file_path, 'rb') as f: + audio_bytes = await f.read() + + api_key = request.app.state.config.DEEPGRAM_API_KEY + stt_model = request.app.state.config.STT_MODEL + + r = None + try: + session = await get_session() + for lang in languages: + query: dict = {'smart_format': 'true'} + if stt_model: + query['model'] = stt_model + if lang: + query['language'] = lang + + r = await session.post( + 'https://api.deepgram.com/v1/listen', + headers={'Authorization': f'Token {api_key}', 'Content-Type': content_type}, + params=query, + data=audio_bytes, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) + if r.status == 200: + break + + r.raise_for_status() + body = await r.json() + + # Parse the Deepgram response structure + try: + transcript = body['results']['channels'][0]['alternatives'][0].get('transcript', '').strip() + except (KeyError, IndexError) as exc: + log.error(f'Malformed Deepgram response: {exc}') + raise Exception('Failed to parse Deepgram response') from exc + + data = {'text': transcript} + async with aiofiles.open(os.path.join(file_dir, f'{id}.json'), 'w') as f: + await f.write(json.dumps(data)) + return data + + except Exception as e: + log.exception(e) + detail = 'Open WebUI: Server Connection Error' + if r is not None: + try: + res = await r.json() + msg = ( + res.get('error', {}).get('message', '') + if isinstance(res.get('error'), dict) + else str(res.get('error', '')) + ) + if msg: + detail = f'External: {msg}' + except Exception: + detail = f'External: {e}' + raise Exception(detail) + + +async def _transcribe_azure(request, file_path, filename, file_dir, id): + """Transcribe audio via Azure Cognitive Services batch transcription.""" + if not os.path.isfile(file_path): + raise HTTPException(status_code=400, detail='Audio file not found') + + audio_size = os.path.getsize(file_path) + if audio_size > AZURE_MAX_FILE_SIZE: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f'File size ({audio_size // (1024 * 1024)}MB) exceeds Azure limit of {AZURE_MAX_FILE_SIZE_MB}MB', + ) + + api_key = request.app.state.config.AUDIO_STT_AZURE_API_KEY + region = request.app.state.config.AUDIO_STT_AZURE_REGION or 'eastus' + locale_str = request.app.state.config.AUDIO_STT_AZURE_LOCALES + base_url = request.app.state.config.AUDIO_STT_AZURE_BASE_URL + max_speakers = request.app.state.config.AUDIO_STT_AZURE_MAX_SPEAKERS or 3 + + # Default to a broad set of locales when none are configured + if len(locale_str) < 2: + locale_str = ','.join( + [ 'en-US', 'es-ES', 'es-MX', @@ -878,281 +791,244 @@ def transcription_handler(request, file_path, metadata, user=None): 'pt-BR', 'zh-CN', ] - locales = ','.join(locales) + ) - if not api_key or not region: - raise HTTPException( - status_code=400, - detail='Azure API key is required for Azure STT', - ) + if not api_key or not region: + raise HTTPException(status_code=400, detail='Azure API key and region are required for Azure STT') - r = None + # Build the transcription definition payload + definition = json.dumps( + {'locales': locale_str.split(','), 'diarization': {'maxSpeakers': max_speakers, 'enabled': True}} + if locale_str + else {} + ) + endpoint = ( + base_url or f'https://{region}.api.cognitive.microsoft.com' + ) + '/speechtotext/transcriptions:transcribe?api-version=2024-11-15' + + form_data = aiohttp.FormData() + form_data.add_field('definition', definition) + form_data.add_field('audio', open(file_path, 'rb'), filename=filename) + + r = None + try: + session = await get_session() + r = await session.post( + url=endpoint, + data=form_data, + headers={'Ocp-Apim-Subscription-Key': api_key}, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) + r.raise_for_status() + response = await r.json() + + if not response.get('combinedPhrases'): + raise ValueError('No transcription found in response') + + transcript = response['combinedPhrases'][0].get('text', '').strip() + if not transcript: + raise ValueError('Empty transcript in response') + + data = {'text': transcript} + + async with aiofiles.open(os.path.join(file_dir, f'{id}.json'), 'w') as f: + await f.write(json.dumps(data)) + + log.debug(data) + return data + + except (KeyError, IndexError, ValueError) as e: + log.exception('Error parsing Azure response') + raise HTTPException(status_code=500, detail=f'Failed to parse Azure response: {str(e)}') + except aiohttp.ClientResponseError as e: + log.exception(e) + detail = None try: - # Prepare the request - data = { - 'definition': json.dumps( - { - 'locales': locales.split(','), - 'diarization': {'maxSpeakers': max_speakers, 'enabled': True}, + if r is not None and r.status != 200: + res = await r.json() + if 'code' in res and 'message' in res: + azure_code = res.get('innerError', {}).get('code', res['code']) + user_facing_codes = { + 'EmptyAudioFile', + 'AudioLengthLimitExceeded', + 'NoLanguageIdentified', + 'MultipleLanguagesIdentified', } - if locales - else {} - ) - } + if azure_code in user_facing_codes: + detail = res['message'] + else: + log.error(f'Azure STT error [{azure_code}]: {res["message"]}') + detail = 'An error occurred during transcription.' + elif 'error' in res: + detail = f'External: {res["error"].get("message", "")}' + except Exception: + detail = f'External: {e}' + raise HTTPException( + status_code=e.status if e.status else 500, + detail=detail if detail else 'Open WebUI: Server Connection Error', + ) - url = ( - base_url or f'https://{region}.api.cognitive.microsoft.com' - ) + '/speechtotext/transcriptions:transcribe?api-version=2024-11-15' - # Use context manager to ensure file is properly closed - with open(file_path, 'rb') as audio_file: - r = requests.post( - url=url, - files={'audio': audio_file}, - data=data, - headers={ - 'Ocp-Apim-Subscription-Key': api_key, - }, - timeout=AIOHTTP_CLIENT_TIMEOUT, - ) +async def transcription_handler(request, file_path, metadata, user=None): + filename = os.path.basename(file_path) + file_dir = os.path.dirname(file_path) + id = filename.split('.')[0] - r.raise_for_status() - response = r.json() + metadata = metadata or {} - # Extract transcript from response - if not response.get('combinedPhrases'): - raise ValueError('No transcription found in response') + languages = [ + metadata.get('language', None) if not WHISPER_LANGUAGE else WHISPER_LANGUAGE, + None, # Always fallback to None in case transcription fails + ] - # Get the full transcript from combinedPhrases - transcript = response['combinedPhrases'][0].get('text', '').strip() - if not transcript: - raise ValueError('Empty transcript in response') - - data = {'text': transcript} - - # Save transcript to json file (consistent with other providers) - transcript_file = os.path.join(file_dir, f'{id}.json') - with open(transcript_file, 'w') as f: - json.dump(data, f) - - log.debug(data) - return data - - except (KeyError, IndexError, ValueError) as e: - log.exception('Error parsing Azure response') - raise HTTPException( - status_code=500, - detail=f'Failed to parse Azure response: {str(e)}', - ) - except requests.exceptions.RequestException as e: - log.exception(e) - detail = None - status_code = getattr(r, 'status_code', 500) if r else 500 - - try: - if r is not None and r.status_code != 200: - res = r.json() - # Azure returns {"code": "...", "message": "...", "innerError": {...}} - if 'code' in res and 'message' in res: - azure_code = res.get('innerError', {}).get('code', res['code']) - user_facing_codes = { - 'EmptyAudioFile', - 'AudioLengthLimitExceeded', - 'NoLanguageIdentified', - 'MultipleLanguagesIdentified', - } - if azure_code in user_facing_codes: - detail = res['message'] - else: - log.error(f'Azure STT error [{azure_code}]: {res["message"]}') - detail = 'An error occurred during transcription.' - elif 'error' in res: - detail = f'External: {res["error"].get("message", "")}' - except Exception: - detail = f'External: {e}' - - raise HTTPException( - status_code=status_code, - detail=detail if detail else 'Open WebUI: Server Connection Error', - ) + if request.app.state.config.STT_ENGINE == '': + return await _transcribe_whisper(request, file_path, languages, file_dir, id) + elif request.app.state.config.STT_ENGINE == 'openai': + return await _transcribe_openai(request, file_path, filename, languages, file_dir, id, user) + elif request.app.state.config.STT_ENGINE == 'deepgram': + return await _transcribe_deepgram(request, file_path, languages, file_dir, id) + elif request.app.state.config.STT_ENGINE == 'azure': + return await _transcribe_azure(request, file_path, filename, file_dir, id) elif request.app.state.config.STT_ENGINE == 'mistral': - # Check file exists - if not os.path.exists(file_path): - raise HTTPException(status_code=400, detail='Audio file not found') + return await _transcribe_mistral(request, file_path, filename, metadata, file_dir, id) - # Check file size - file_size = os.path.getsize(file_path) - if file_size > MAX_FILE_SIZE: - raise HTTPException( - status_code=400, - detail=f'File size exceeds limit of {MAX_FILE_SIZE_MB}MB', - ) - api_key = request.app.state.config.AUDIO_STT_MISTRAL_API_KEY - api_base_url = request.app.state.config.AUDIO_STT_MISTRAL_API_BASE_URL or 'https://api.mistral.ai/v1' - use_chat_completions = request.app.state.config.AUDIO_STT_MISTRAL_USE_CHAT_COMPLETIONS +async def _transcribe_mistral(request, file_path, filename, metadata, file_dir, id): + """Transcribe audio via the Mistral STT API.""" + if not os.path.isfile(file_path): + raise HTTPException(status_code=400, detail='Audio file not found') - if not api_key: - raise HTTPException( - status_code=400, - detail='Mistral API key is required for Mistral STT', - ) + file_size = os.path.getsize(file_path) + if file_size > MAX_FILE_SIZE: + raise HTTPException(status_code=400, detail=f'File size exceeds limit of {MAX_FILE_SIZE_MB}MB') - r = None - try: - # Use voxtral-mini-latest as the default model for transcription - model = request.app.state.config.STT_MODEL or 'voxtral-mini-latest' + api_key = request.app.state.config.AUDIO_STT_MISTRAL_API_KEY + api_base_url = request.app.state.config.AUDIO_STT_MISTRAL_API_BASE_URL or 'https://api.mistral.ai/v1' + use_chat_completions = request.app.state.config.AUDIO_STT_MISTRAL_USE_CHAT_COMPLETIONS - log.info( - f'Mistral STT - model: {model}, ' - f'method: {"chat_completions" if use_chat_completions else "transcriptions"}' - ) + if not api_key: + raise HTTPException(status_code=400, detail='Mistral API key is required for Mistral STT') - if use_chat_completions: - # Use chat completions API with audio input - # This method requires mp3 or wav format - audio_file_to_use = file_path + r = None + try: + model = request.app.state.config.STT_MODEL or 'voxtral-mini-latest' + log.info( + f'Mistral STT - model: {model}, method: {"chat_completions" if use_chat_completions else "transcriptions"}' + ) - if is_audio_conversion_required(file_path): - log.debug('Converting audio to mp3 for chat completions API') - converted_path = convert_audio_to_mp3(file_path) - if converted_path: - audio_file_to_use = converted_path - else: - log.error('Audio conversion failed') - raise HTTPException( - status_code=500, - detail='Audio conversion failed. Chat completions API requires mp3 or wav format.', - ) - - # Read and encode audio file as base64 - with open(audio_file_to_use, 'rb') as audio_file: - audio_base64 = { - 'data': base64.b64encode(audio_file.read()).decode('utf-8'), - 'format': mimetypes.guess_extension(mimetypes.guess_type(audio_file_to_use)[0]).lstrip('.'), - } - - # Prepare chat completions request - url = f'{api_base_url}/chat/completions' - - # Add language instruction if specified - language = metadata.get('language', None) if metadata else None - if language: - text_instruction = f'Transcribe this audio exactly as spoken in {language}. Do not translate it.' + session = await get_session() + if use_chat_completions: + audio_file_to_use = file_path + if is_audio_conversion_required(file_path): + log.debug('Converting audio to mp3 for chat completions API') + converted_path = await asyncio.to_thread(convert_audio_to_mp3, file_path) + if converted_path: + audio_file_to_use = converted_path else: - text_instruction = 'Transcribe this audio exactly as spoken in its original language. Do not translate it to another language.' - - payload = { - 'model': model, - 'messages': [ - { - 'role': 'user', - 'content': [ - { - 'type': 'input_audio', - 'input_audio': audio_base64, - }, - {'type': 'text', 'text': text_instruction}, - ], - } - ], - } - - r = requests.post( - url=url, - json=payload, - headers={ - 'Authorization': f'Bearer {api_key}', - 'Content-Type': 'application/json', - }, - timeout=AIOHTTP_CLIENT_TIMEOUT, - ) - - r.raise_for_status() - response = r.json() - - # Extract transcript from chat completion response - transcript = response.get('choices', [{}])[0].get('message', {}).get('content', '').strip() - if not transcript: - raise ValueError('Empty transcript in response') - - data = {'text': transcript} - - else: - # Use dedicated transcriptions API - url = f'{api_base_url}/audio/transcriptions' - - # Determine the MIME type - mime_type, _ = mimetypes.guess_type(file_path) - if not mime_type: - mime_type = 'audio/webm' - - # Use context manager to ensure file is properly closed - with open(file_path, 'rb') as audio_file: - files = {'file': (filename, audio_file, mime_type)} - data_form = {'model': model} - - # Add language if specified in metadata - language = metadata.get('language', None) if metadata else None - if language: - data_form['language'] = language - - r = requests.post( - url=url, - files=files, - data=data_form, - headers={ - 'Authorization': f'Bearer {api_key}', - }, - timeout=AIOHTTP_CLIENT_TIMEOUT, + log.error('Audio conversion failed') + raise HTTPException( + status_code=500, + detail='Audio conversion failed. Chat completions API requires mp3 or wav format.', ) - r.raise_for_status() - response = r.json() + async with aiofiles.open(audio_file_to_use, 'rb') as audio_file: + raw = await audio_file.read() + audio_base64 = { + 'data': base64.b64encode(raw).decode('utf-8'), + 'format': mimetypes.guess_extension(mimetypes.guess_type(audio_file_to_use)[0]).lstrip('.'), + } - # Extract transcript from response - transcript = response.get('text', '').strip() - if not transcript: - raise ValueError('Empty transcript in response') - - data = {'text': transcript} - - # Save transcript to json file (consistent with other providers) - transcript_file = os.path.join(file_dir, f'{id}.json') - with open(transcript_file, 'w') as f: - json.dump(data, f) - - log.debug(data) - return data - - except ValueError as e: - log.exception('Error parsing Mistral response') - raise HTTPException( - status_code=500, - detail=f'Failed to parse Mistral response: {str(e)}', - ) - except requests.exceptions.RequestException as e: - log.exception(e) - detail = None - - try: - if r is not None and r.status_code != 200: - res = r.json() - if 'error' in res: - detail = f'External: {res["error"].get("message", "")}' - else: - detail = f'External: {r.text}' - except Exception: - detail = f'External: {e}' - - raise HTTPException( - status_code=getattr(r, 'status_code', 500) if r else 500, - detail=detail if detail else 'Open WebUI: Server Connection Error', + language = metadata.get('language', None) if metadata else None + text_instruction = ( + f'Transcribe this audio exactly as spoken in {language}. Do not translate it.' + if language + else 'Transcribe this audio exactly as spoken in its original language. Do not translate it to another language.' ) + payload = { + 'model': model, + 'messages': [ + { + 'role': 'user', + 'content': [ + {'type': 'input_audio', 'input_audio': audio_base64}, + {'type': 'text', 'text': text_instruction}, + ], + } + ], + } -def transcribe(request: Request, file_path: str, metadata: Optional[dict] = None, user=None): + r = await session.post( + url=f'{api_base_url}/chat/completions', + json=payload, + headers={'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json'}, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) + r.raise_for_status() + response = await r.json() + + transcript = response.get('choices', [{}])[0].get('message', {}).get('content', '').strip() + if not transcript: + raise ValueError('Empty transcript in response') + data = {'text': transcript} + + else: + mime_type, _ = mimetypes.guess_type(file_path) + if not mime_type: + mime_type = 'audio/webm' + + form_data = aiohttp.FormData() + form_data.add_field('model', model) + + language = metadata.get('language', None) if metadata else None + if language: + form_data.add_field('language', language) + + form_data.add_field('file', open(file_path, 'rb'), filename=filename, content_type=mime_type) + + r = await session.post( + url=f'{api_base_url}/audio/transcriptions', + data=form_data, + headers={'Authorization': f'Bearer {api_key}'}, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) + r.raise_for_status() + response = await r.json() + + transcript = response.get('text', '').strip() + if not transcript: + raise ValueError('Empty transcript in response') + data = {'text': transcript} + + async with aiofiles.open(os.path.join(file_dir, f'{id}.json'), 'w') as f: + await f.write(json.dumps(data)) + + log.debug(data) + return data + + except ValueError as e: + log.exception('Error parsing Mistral response') + raise HTTPException(status_code=500, detail=f'Failed to parse Mistral response: {str(e)}') + except aiohttp.ClientResponseError as e: + log.exception(e) + detail = None + try: + if r is not None and r.status != 200: + res = await r.json() + if 'error' in res: + detail = f'External: {res["error"].get("message", "")}' + else: + detail = f'External: {await r.text()}' + except Exception: + detail = f'External: {e}' + raise HTTPException( + status_code=e.status if e.status else 500, + detail=detail if detail else 'Open WebUI: Server Connection Error', + ) + + +async def transcribe(request: Request, file_path: str, metadata: Optional[dict] = None, user=None): log.info(f'transcribe: {file_path} {metadata}') if BYPASS_PYDUB_PREPROCESSING: @@ -1160,7 +1036,7 @@ def transcribe(request: Request, file_path: str, metadata: Optional[dict] = None chunk_paths = [file_path] else: if is_audio_conversion_required(file_path): - file_path = convert_audio_to_mp3(file_path) + file_path = await asyncio.to_thread(convert_audio_to_mp3, file_path) if not file_path: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, @@ -1168,13 +1044,13 @@ def transcribe(request: Request, file_path: str, metadata: Optional[dict] = None ) try: - file_path = compress_audio(file_path) + file_path = await asyncio.to_thread(compress_audio, file_path) except Exception as e: log.exception(e) # Always produce a list of chunk paths (could be one entry if small) try: - chunk_paths = split_audio(file_path, MAX_FILE_SIZE) + chunk_paths = await asyncio.to_thread(split_audio, file_path, MAX_FILE_SIZE) print(f'Chunk paths: {chunk_paths}') except Exception as e: log.exception(e) @@ -1185,28 +1061,17 @@ def transcribe(request: Request, file_path: str, metadata: Optional[dict] = None results = [] try: - if getattr(request.app.state.config, 'STT_ENGINE', '') == '': - max_workers = 1 - else: - max_workers = None - - with ThreadPoolExecutor(max_workers=max_workers) as executor: - # Submit tasks for each chunk_path - futures = [ - executor.submit(transcription_handler, request, chunk_path, metadata, user) - for chunk_path in chunk_paths - ] - # Gather results as they complete - for future in futures: - try: - results.append(future.result()) - except HTTPException: - raise - except Exception as transcribe_exc: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f'Error transcribing chunk: {transcribe_exc}', - ) + tasks = [transcription_handler(request, chunk_path, metadata, user) for chunk_path in chunk_paths] + for coro in asyncio.as_completed(tasks): + try: + results.append(await coro) + except HTTPException: + raise + except Exception as transcribe_exc: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f'Error transcribing chunk: {transcribe_exc}', + ) finally: # Clean up only the temporary chunks, never the original file for chunk_path in chunk_paths: @@ -1337,7 +1202,7 @@ async def transcription( if language: metadata = {'language': language} - result = await asyncio.to_thread(transcribe, request, file_path, metadata, user) + result = await transcribe(request, file_path, metadata, user) return { **result, @@ -1366,57 +1231,62 @@ async def transcription( async def get_available_models(request: Request) -> list[dict]: + """Return the list of available TTS models for the configured engine.""" available_models = [] - if request.app.state.config.TTS_ENGINE == 'openai': - # Use custom endpoint if not using the official OpenAI API URL - if not request.app.state.config.TTS_OPENAI_API_BASE_URL.startswith('https://api.openai.com'): - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: + engine = request.app.state.config.TTS_ENGINE + _timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST) + + if engine == 'openai': + base_url = request.app.state.config.TTS_OPENAI_API_BASE_URL + if not base_url.startswith('https://api.openai.com'): + session = await get_session() + try: + async with session.get( + f'{base_url}/audio/models', + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=_timeout, + ) as resp: + resp.raise_for_status() + data = await resp.json() + available_models = data.get('models', []) + except Exception as e: + log.debug(f'/audio/models not available, trying /models fallback: {e}') try: async with session.get( - f'{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/models', + f'{base_url}/models', ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as response: - response.raise_for_status() - data = await response.json() - available_models = data.get('models', []) - except Exception as e: - log.debug(f'/audio/models not available, trying /models fallback: {str(e)}') - # Fallback to standard OpenAI-compatible /models endpoint - # (used by KokoroTTS and similar custom TTS servers) - try: - async with session.get( - f'{request.app.state.config.TTS_OPENAI_API_BASE_URL}/models', - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as response: - response.raise_for_status() - data = await response.json() - # OpenAI /models returns {"data": [...]}, /audio/models returns {"models": [...]} - available_models = data.get('data', data.get('models', [])) - except Exception as e2: - log.error(f'Error fetching models from custom endpoint: {str(e2)}') - available_models = [{'id': 'tts-1'}, {'id': 'tts-1-hd'}] + timeout=_timeout, + ) as resp: + resp.raise_for_status() + data = await resp.json() + available_models = data.get('data', data.get('models', [])) + except Exception as e2: + log.error(f'Error fetching models from custom endpoint: {e2}') + available_models = [{'id': 'tts-1'}, {'id': 'tts-1-hd'}] else: available_models = [{'id': 'tts-1'}, {'id': 'tts-1-hd'}] - elif request.app.state.config.TTS_ENGINE == 'elevenlabs': + + elif engine == 'elevenlabs': try: - timeout = aiohttp.ClientTimeout(total=5) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - async with session.get( - f'{ELEVENLABS_API_BASE_URL}/v1/models', - headers={ - 'xi-api-key': request.app.state.config.TTS_API_KEY, - 'Content-Type': 'application/json', - }, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as response: - response.raise_for_status() - models = await response.json() - available_models = [{'name': model['name'], 'id': model['model_id']} for model in models] + session = await get_session() + async with session.get( + f'{ELEVENLABS_API_BASE_URL}/v1/models', + headers={ + 'xi-api-key': request.app.state.config.TTS_API_KEY, + 'Content-Type': 'application/json', + }, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=_timeout, + ) as resp: + resp.raise_for_status() + models = await resp.json() + available_models = [{'name': m['name'], 'id': m['model_id']} for m in models] except Exception as e: - log.error(f'Error fetching models: {str(e)}') - elif request.app.state.config.TTS_ENGINE == 'mistral': + log.error(f'Error fetching models: {e}') + + elif engine == 'mistral': available_models = [{'id': 'voxtral-mini-tts-2603'}] + return available_models @@ -1425,129 +1295,104 @@ async def get_models(request: Request, user=Depends(get_verified_user)): return {'models': await get_available_models(request)} +_OPENAI_DEFAULT_VOICES = { + 'alloy': 'alloy', + 'echo': 'echo', + 'fable': 'fable', + 'onyx': 'onyx', + 'nova': 'nova', + 'shimmer': 'shimmer', +} + + async def get_available_voices(request) -> dict: - """Returns {voice_id: voice_name} dict""" - available_voices = {} - if request.app.state.config.TTS_ENGINE == 'openai': - # Use custom endpoint if not using the official OpenAI API URL - if not request.app.state.config.TTS_OPENAI_API_BASE_URL.startswith('https://api.openai.com'): + """Return ``{voice_id: voice_name}`` for the configured TTS engine.""" + engine = request.app.state.config.TTS_ENGINE + _timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST) + + if engine == 'openai': + base_url = request.app.state.config.TTS_OPENAI_API_BASE_URL + if not base_url.startswith('https://api.openai.com'): try: - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - async with session.get( - f'{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/voices', - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as response: - response.raise_for_status() - data = await response.json() - voices_list = data.get('voices', []) - available_voices = {voice['id']: voice['name'] for voice in voices_list} + session = await get_session() + async with session.get( + f'{base_url}/audio/voices', + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=_timeout, + ) as resp: + resp.raise_for_status() + data = await resp.json() + return {v['id']: v['name'] for v in data.get('voices', [])} except Exception as e: - log.error(f'Error fetching voices from custom endpoint: {str(e)}') - available_voices = { - 'alloy': 'alloy', - 'echo': 'echo', - 'fable': 'fable', - 'onyx': 'onyx', - 'nova': 'nova', - 'shimmer': 'shimmer', - } - else: - available_voices = { - 'alloy': 'alloy', - 'echo': 'echo', - 'fable': 'fable', - 'onyx': 'onyx', - 'nova': 'nova', - 'shimmer': 'shimmer', - } - elif request.app.state.config.TTS_ENGINE == 'elevenlabs': + log.error(f'Error fetching voices from custom endpoint: {e}') + return dict(_OPENAI_DEFAULT_VOICES) + return dict(_OPENAI_DEFAULT_VOICES) + + if engine == 'elevenlabs': try: - available_voices = await get_elevenlabs_voices(api_key=request.app.state.config.TTS_API_KEY) - except Exception: - # Avoided @lru_cache with exception - pass - elif request.app.state.config.TTS_ENGINE == 'azure': + session = await get_session() + async with session.get( + f'{ELEVENLABS_API_BASE_URL}/v1/voices', + headers={ + 'xi-api-key': request.app.state.config.TTS_API_KEY, + 'Content-Type': 'application/json', + }, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=_timeout, + ) as resp: + resp.raise_for_status() + voices_data = await resp.json() + return {v['voice_id']: v['name'] for v in voices_data.get('voices', [])} + except Exception as e: + log.error(f'Error fetching ElevenLabs voices: {e}') + return {} + + if engine == 'azure': try: region = request.app.state.config.TTS_AZURE_SPEECH_REGION base_url = request.app.state.config.TTS_AZURE_SPEECH_BASE_URL url = (base_url or f'https://{region}.tts.speech.microsoft.com') + '/cognitiveservices/voices/list' - headers = {'Ocp-Apim-Subscription-Key': request.app.state.config.TTS_API_KEY} - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - async with session.get(url, headers=headers, ssl=AIOHTTP_CLIENT_SESSION_SSL) as response: - response.raise_for_status() - voices = await response.json() - - for voice in voices: - available_voices[voice['ShortName']] = f'{voice["DisplayName"]} ({voice["ShortName"]})' + session = await get_session() + async with session.get( + url, + headers={'Ocp-Apim-Subscription-Key': request.app.state.config.TTS_API_KEY}, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=_timeout, + ) as resp: + resp.raise_for_status() + voices = await resp.json() + return {v['ShortName']: f'{v["DisplayName"]} ({v["ShortName"]})' for v in voices} except Exception as e: - log.error(f'Error fetching voices: {str(e)}') - elif request.app.state.config.TTS_ENGINE == 'mistral': + log.error(f'Error fetching Azure voices: {e}') + return {} + + if engine == 'mistral': api_key = request.app.state.config.TTS_MISTRAL_API_KEY api_base_url = request.app.state.config.TTS_MISTRAL_API_BASE_URL or 'https://api.mistral.ai/v1' - if api_key: try: - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - async with session.get( - f'{api_base_url}/audio/voices', - headers={ - 'Authorization': f'Bearer {api_key}', - }, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as response: - response.raise_for_status() - voices_data = await response.json() - - # Mistral returns a paginated response: {"items": [...], "page": ..., "total": ...} - voices_list = voices_data.get('items', []) if isinstance(voices_data, dict) else voices_data - for voice in voices_list: - if isinstance(voice, dict): - voice_id = voice.get('voice_id', voice.get('id', '')) - voice_name = voice.get('name', voice_id) - if voice_id: - available_voices[voice_id] = voice_name + session = await get_session() + async with session.get( + f'{api_base_url}/audio/voices', + headers={'Authorization': f'Bearer {api_key}'}, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=_timeout, + ) as resp: + resp.raise_for_status() + voices_data = await resp.json() + items = voices_data.get('items', []) if isinstance(voices_data, dict) else voices_data + result = {} + for v in items: + if isinstance(v, dict): + vid = v.get('voice_id', v.get('id', '')) + if vid: + result[vid] = v.get('name', vid) + return result except Exception as e: - log.error(f'Error fetching Mistral voices: {str(e)}') + log.error(f'Error fetching Mistral voices: {e}') - return available_voices - - -async def get_elevenlabs_voices(api_key: str) -> dict: - """ - Note, set the following in your .env file to use Elevenlabs: - AUDIO_TTS_ENGINE=elevenlabs - AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key - AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices - AUDIO_TTS_MODEL=eleven_multilingual_v2 - """ - - try: - # TODO: Add retries - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST) - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - async with session.get( - f'{ELEVENLABS_API_BASE_URL}/v1/voices', - headers={ - 'xi-api-key': api_key, - 'Content-Type': 'application/json', - }, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as response: - response.raise_for_status() - voices_data = await response.json() - - voices = {} - for voice in voices_data.get('voices', []): - voices[voice['voice_id']] = voice['name'] - except Exception as e: - log.error(f'Error fetching voices: {str(e)}') - raise RuntimeError(f'Error fetching voices: {str(e)}') - - return voices + return {} @router.get('/voices') diff --git a/backend/open_webui/routers/auths.py b/backend/open_webui/routers/auths.py index b3a45a58f3..434a6349de 100644 --- a/backend/open_webui/routers/auths.py +++ b/backend/open_webui/routers/auths.py @@ -286,8 +286,9 @@ async def update_password( session_user=Depends(get_current_user), db: AsyncSession = Depends(get_async_session), ): + # Trusted-header auth mode delegates passwords to the reverse proxy if WEBUI_AUTH_TRUSTED_EMAIL_HEADER: - raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED) + raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.ACTION_PROHIBITED) if session_user: user = await Auths.authenticate_user( session_user.email, @@ -578,7 +579,7 @@ async def signin( if WEBUI_AUTH_TRUSTED_EMAIL_HEADER: if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers: - raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER) + raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER) email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower() name = email @@ -746,9 +747,12 @@ async def signup( has_users = await Users.has_users(db=db) if WEBUI_AUTH: - if not request.app.state.config.ENABLE_SIGNUP or not request.app.state.config.ENABLE_LOGIN_FORM: - if has_users or not ENABLE_INITIAL_ADMIN_SIGNUP: + if has_users: + if not request.app.state.config.ENABLE_SIGNUP or not request.app.state.config.ENABLE_LOGIN_FORM: raise HTTPException(status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + # Don't gate the first admin on ENABLE_SIGNUP: it auto-disables and can persist stale across a DB reset. + elif not request.app.state.config.ENABLE_LOGIN_FORM and not ENABLE_INITIAL_ADMIN_SIGNUP: + raise HTTPException(status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) else: if has_users: raise HTTPException(status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) diff --git a/backend/open_webui/routers/calendar.py b/backend/open_webui/routers/calendar.py index 6c567aa3a8..5d397ea868 100644 --- a/backend/open_webui/routers/calendar.py +++ b/backend/open_webui/routers/calendar.py @@ -301,6 +301,12 @@ async def update_event( await _check_calendar_access(event.calendar_id, user, 'write') + # A new calendar_id in the form moves the event; require write access on the + # destination too, mirroring create_event. Without this, write on the source + # calendar alone is enough to inject an event into any other calendar. + if form_data.calendar_id is not None and form_data.calendar_id != event.calendar_id: + await _check_calendar_access(form_data.calendar_id, user, 'write') + updated = await CalendarEvents.update_event_by_id(event_id, form_data) if not updated: raise HTTPException(status_code=500, detail='Failed to update') diff --git a/backend/open_webui/routers/channels.py b/backend/open_webui/routers/channels.py index 68fc71fe5a..11d3a4a871 100644 --- a/backend/open_webui/routers/channels.py +++ b/backend/open_webui/routers/channels.py @@ -911,6 +911,7 @@ async def model_response_handler(request, channel, message, user, db=None): thread_history = [] images = [] + files = [] # Batch fetch all users in a single query (fixes N+1 problem) user_ids = list({message.user_id for message in thread_messages}) @@ -934,9 +935,11 @@ async def model_response_handler(request, channel, message, user, db=None): if file.get('type', '') == 'image': images.append(file.get('url', '')) elif file.get('content_type', '').startswith('image/'): - image = await get_image_base64_from_file_id(file.get('id', '')) + image = await get_image_base64_from_file_id(file.get('id', ''), user=user) if image: images.append(image) + elif file.get('id'): + files.append(file) thread_history_string = '\n\n'.join(thread_history) system_message = { @@ -994,6 +997,8 @@ async def model_response_handler(request, channel, message, user, db=None): 'session_id': f'channel:{channel.id}', 'background_tasks': {}, } + if files: + form_data['files'] = files if tool_ids: form_data['tool_ids'] = tool_ids if features: diff --git a/backend/open_webui/routers/chats.py b/backend/open_webui/routers/chats.py index 9344173807..2689aa6d2f 100644 --- a/backend/open_webui/routers/chats.py +++ b/backend/open_webui/routers/chats.py @@ -30,6 +30,7 @@ from open_webui.models.folders import Folders from open_webui.models.shared_chats import SharedChatResponse, SharedChats from open_webui.models.tags import TagModel, Tags from open_webui.socket.main import get_event_emitter +from open_webui.tasks import stop_item_tasks from open_webui.utils.access_control import filter_allowed_access_grants, has_permission from open_webui.utils.auth import get_admin_user, get_verified_user from open_webui.utils.middleware import serialize_output @@ -521,17 +522,13 @@ async def get_user_chat_list_by_user_id( user=Depends(get_admin_user), db: AsyncSession = Depends(get_async_session), ): + """List chat summaries for a given user (admin-only endpoint).""" if not ENABLE_ADMIN_CHAT_ACCESS: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail=ERROR_MESSAGES.ACCESS_PROHIBITED, - ) - - if page is None: - page = 1 + raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + effective_page = page if page is not None else 1 limit = 60 - skip = (page - 1) * limit + skip = (effective_page - 1) * limit filter = {} if query: @@ -762,10 +759,7 @@ async def get_all_user_tags(user=Depends(get_verified_user), db: AsyncSession = @router.get('/all/db', response_model=list[ChatResponse]) async def get_all_user_chats_in_db(user=Depends(get_admin_user), db: AsyncSession = Depends(get_async_session)): if not ENABLE_ADMIN_EXPORT: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail=ERROR_MESSAGES.ACCESS_PROHIBITED, - ) + raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) return [ChatResponse(**chat.model_dump()) for chat in await Chats.get_chats(db=db)] @@ -979,14 +973,25 @@ async def update_chat_by_id( if chat: updated_chat = {**chat.chat, **form_data.chat} - # Re-derive content from output for assistant messages so that - # frontend edits to output items are always reflected in content. - # serialize_output() is the single source of truth for this conversion. - for msg in updated_chat.get('history', {}).get('messages', {}).values(): + # Re-derive content from output for assistant messages so that frontend + # edits to output items are reflected in content. Only when output + # actually changed — otherwise content set independently of output + # (e.g. a `replace` event or an outlet filter footer) would be reverted. + existing_messages = (chat.chat.get('history') or {}).get('messages') or {} + for msg_id, msg in updated_chat.get('history', {}).get('messages', {}).items(): if msg.get('role') == 'assistant' and msg.get('output'): - msg['content'] = serialize_output(msg['output']) + if msg.get('output') != existing_messages.get(msg_id, {}).get('output'): + msg['content'] = serialize_output(msg['output']) chat = await Chats.update_chat_by_id(id, updated_chat, db=db) + + # Reconcile chat_message rows with the committed blob. + # This is the only caller where the frontend pushes a full + # history with potential edits, deletions, or new branches. + messages = (updated_chat.get('history') or {}).get('messages') or {} + if messages: + await Chats.reconcile_messages_by_chat_id(id, user.id, messages) + return ChatResponse(**chat.model_dump()) else: raise HTTPException( @@ -1116,6 +1121,10 @@ async def delete_chat_by_id( user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): + # Cancel any in-flight LLM tasks (streaming, title/tags generation) + # before deleting the chat to prevent orphaned requests. + await stop_item_tasks(request.app.state.redis, id) + if user.role == 'admin': chat = await Chats.get_chat_by_id(id, db=db) if not chat: @@ -1305,13 +1314,20 @@ async def clone_shared_chat_by_id( @router.post('/{id}/archive', response_model=ChatResponse | None) -async def archive_chat_by_id(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): +async def archive_chat_by_id( + request: Request, + id: str, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db) if chat: chat = await Chats.toggle_chat_archive_by_id(id, db=db) tag_ids = chat.meta.get('tags', []) if chat.archived: + # Cancel any in-flight LLM tasks before archiving + await stop_item_tasks(request.app.state.redis, id) # Archived chats are excluded from count — clean up orphans await Chats.delete_orphan_tags_for_user(tag_ids, user.id, db=db) else: @@ -1323,9 +1339,7 @@ async def archive_chat_by_id(id: str, user=Depends(get_verified_user), db: Async raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()) -############################ -# ShareChatById -############################ +# --- Share Chat --- @router.post('/{id}/share', response_model=ChatResponse | None) @@ -1335,51 +1349,35 @@ async def share_chat_by_id( user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): - if (user.role != 'admin') and ( - not await has_permission(user.id, 'chat.share', request.app.state.config.USER_PERMISSIONS) + if user.role != 'admin' and not await has_permission( + user.id, 'chat.share', request.app.state.config.USER_PERMISSIONS ): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail=ERROR_MESSAGES.ACCESS_PROHIBITED, - ) + raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db) + if not chat: + raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) - if chat: - if chat.share_id: - # Re-snapshot existing share - shared = await SharedChats.update(chat.share_id, db=db) - if shared: - # Re-fetch the original chat to return - chat = await Chats.get_chat_by_id(id, db=db) - return ChatResponse(**chat.model_dump()) + # If a share already exists, re-snapshot it + if chat.share_id: + shared = await SharedChats.update(chat.share_id, db=db) + if shared: + chat = await Chats.get_chat_by_id(id, db=db) + return ChatResponse(**chat.model_dump()) - # Create new share - shared = await SharedChats.create(id, user.id, db=db) - if not shared: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=ERROR_MESSAGES.DEFAULT(), - ) - # Set share_id on the original chat - chat = await Chats.update_chat_share_id_by_id(id, shared.id, db=db) - if not chat: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=ERROR_MESSAGES.DEFAULT(), - ) - return ChatResponse(**chat.model_dump()) + # Create a new share + shared = await SharedChats.create(id, user.id, db=db) + if not shared: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, detail=ERROR_MESSAGES.DEFAULT()) - else: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail=ERROR_MESSAGES.ACCESS_PROHIBITED, - ) + chat = await Chats.update_chat_share_id_by_id(id, shared.id, db=db) + if not chat: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, detail=ERROR_MESSAGES.DEFAULT()) + + return ChatResponse(**chat.model_dump()) -############################ -# DeleteSharedChatById -############################ +# --- Delete Shared Chat --- @router.delete('/{id}/share', response_model=bool | None) @@ -1387,22 +1385,17 @@ async def delete_shared_chat_by_id( id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) ): chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db) - if chat: - if not chat.share_id: - return False + if not chat: + raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) - await SharedChats.delete_by_chat_id(id, db=db) - await Chats.update_chat_share_id_by_id(id, None, db=db) + if not chat.share_id: + return False - # Revoke all access grants for this shared chat - await AccessGrants.set_access_grants('shared_chat', id, [], db=db) + await SharedChats.delete_by_chat_id(id, db=db) + await Chats.update_chat_share_id_by_id(id, None, db=db) + await AccessGrants.set_access_grants('shared_chat', id, [], db=db) - return True - else: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail=ERROR_MESSAGES.ACCESS_PROHIBITED, - ) + return True ############################ @@ -1583,23 +1576,3 @@ async def delete_tag_by_id_and_tag_name( return await Tags.get_tags_by_ids_and_user_id(tags, user.id, db=db) else: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND) - - -############################ -# DeleteAllTagsById -############################ - - -@router.delete('/{id}/tags/all', response_model=bool | None) -async def delete_all_tags_by_id( - id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) -): - chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db) - if chat: - old_tags = chat.meta.get('tags', []) - await Chats.delete_all_tags_by_id_and_user_id(id, user.id, db=db) - await Chats.delete_orphan_tags_for_user(old_tags, user.id, db=db) - - return True - else: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND) diff --git a/backend/open_webui/routers/evaluations.py b/backend/open_webui/routers/evaluations.py index cce9d591ee..d1c914f4ee 100644 --- a/backend/open_webui/routers/evaluations.py +++ b/backend/open_webui/routers/evaluations.py @@ -10,9 +10,7 @@ from open_webui.models.feedbacks import ( FeedbackIdResponse, FeedbackListResponse, FeedbackModel, - FeedbackResponse, Feedbacks, - FeedbackUserResponse, LeaderboardFeedbackData, ModelHistoryEntry, ModelHistoryResponse, @@ -295,12 +293,6 @@ async def get_feedback_model_ids(user=Depends(get_admin_user), db: AsyncSession return await Feedbacks.get_distinct_model_ids(db=db) -@router.get('/feedbacks/all', response_model=list[FeedbackResponse]) -async def get_all_feedbacks(user=Depends(get_admin_user), db: AsyncSession = Depends(get_async_session)): - feedbacks = await Feedbacks.get_all_feedbacks(db=db) - return feedbacks - - @router.get('/feedbacks/all/ids', response_model=list[FeedbackIdResponse]) async def get_all_feedback_ids(user=Depends(get_admin_user), db: AsyncSession = Depends(get_async_session)): return await Feedbacks.get_all_feedback_ids(db=db) @@ -324,10 +316,19 @@ async def export_all_feedbacks( return feedbacks -@router.get('/feedbacks/user', response_model=list[FeedbackUserResponse]) -async def get_feedbacks(user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): - feedbacks = await Feedbacks.get_feedbacks_by_user_id(user.id, db=db) - return feedbacks +PAGE_ITEM_COUNT = 30 + + +@router.get('/feedbacks/user', response_model=FeedbackListResponse) +async def get_user_feedbacks( + page: Optional[int] = 1, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + limit = PAGE_ITEM_COUNT + page = max(1, page) + skip = (page - 1) * limit + return await Feedbacks.get_feedbacks_by_user_id(user.id, skip=skip, limit=limit, db=db) @router.delete('/feedbacks', response_model=bool) @@ -336,9 +337,6 @@ async def delete_feedbacks(user=Depends(get_verified_user), db: AsyncSession = D return success -PAGE_ITEM_COUNT = 30 - - @router.get('/feedbacks/list', response_model=FeedbackListResponse) async def get_feedbacks( order_by: Optional[str] = None, diff --git a/backend/open_webui/routers/files.py b/backend/open_webui/routers/files.py index 3c838524e8..dbf1ccb885 100644 --- a/backend/open_webui/routers/files.py +++ b/backend/open_webui/routers/files.py @@ -1,4 +1,5 @@ import asyncio +import hashlib import json import logging import os @@ -60,7 +61,11 @@ from open_webui.utils.access_control.files import has_access_to_file def _is_text_file(file_path: str, chunk_size: int = 8192) -> bool: - """Check if a file is likely a text file by reading a chunk and validating UTF-8. + """Check if a file is likely a text file by reading a chunk and decoding it. + + Tries UTF-8 first, then falls back to Latin-1 (which accepts every byte + in 0x00–0xFF) so that legacy-encoded files from Windows environments are + not misclassified as binary. This catches files whose extensions are mis-mapped by mimetypes/browsers (e.g. TypeScript .ts → video/mp2t) without maintaining an extension whitelist. @@ -74,9 +79,15 @@ def _is_text_file(file_path: str, chunk_size: int = 8192) -> bool: # Null bytes are a strong indicator of binary content if b'\x00' in chunk: return False - chunk.decode('utf-8') + try: + chunk.decode('utf-8') + except UnicodeDecodeError: + # Latin-1 always succeeds (every byte is valid), so this + # effectively just means "the file has no null bytes and is + # therefore likely text, even if not valid UTF-8". + chunk.decode('latin-1') return True - except (UnicodeDecodeError, Exception): + except Exception: return False @@ -112,15 +123,12 @@ async def process_uploaded_file( if _is_text_file(file_path): content_type = 'text/plain' - stt_supported = getattr( - request.app.state.config, 'STT_SUPPORTED_CONTENT_TYPES', [] - ) + stt_supported = getattr(request.app.state.config, 'STT_SUPPORTED_CONTENT_TYPES', []) if content_type and strict_match_mime_type(stt_supported, content_type): # Audio / STT-supported files → transcribe then index file_path_processed = await asyncio.to_thread(Storage.get_file, file_path) - result = await asyncio.to_thread( - transcribe, + result = await transcribe( request, file_path_processed, file_metadata, @@ -151,17 +159,12 @@ async def process_uploaded_file( db=db_session, ) else: - raise Exception( - f'File type {content_type} is not supported for processing' - ) + raise Exception(f'File type {content_type} is not supported for processing') else: # Documents, or any file when an external engine is configured if not content_type: - log.info( - f'File type {file.content_type} is not provided, ' - 'but trying to process anyway' - ) + log.info(f'File type {file.content_type} is not provided, but trying to process anyway') await process_file( request, ProcessFileForm(file_id=file_item.id), @@ -169,6 +172,28 @@ async def process_uploaded_file( db=db_session, ) + # Auto-link to Knowledge Collection when uploaded from one (#24807). + # Mirrors POST /knowledge/{id}/file/add so linking doesn't depend + # on the frontend staying connected after upload. + knowledge_id = file_metadata.get('knowledge_id') + if knowledge_id: + try: + await Knowledges.add_file_to_knowledge_by_id( + knowledge_id=knowledge_id, + file_id=file_item.id, + user_id=user.id, + directory_id=file_metadata.get('directory_id'), + ) + await process_file( + request, + ProcessFileForm(file_id=file_item.id, collection_name=knowledge_id), + user=user, + db=db_session, + ) + log.info(f'Linked file {file_item.id} to knowledge {knowledge_id}') + except Exception as e: + log.warning(f'Failed to link file {file_item.id} to knowledge {knowledge_id}: {e}') + except Exception as e: log.error(f'Error processing file: {file_item.id}') await Files.update_file_data_by_id( @@ -270,6 +295,10 @@ async def upload_file_handler( }, ) + # SHA-256 of raw uploaded bytes for incremental sync diffing. + # If the client pre-computed and sent file_hash, use that. + file_hash = file_metadata.get('file_hash') or hashlib.sha256(contents).hexdigest() + file_item = await Files.insert_new_file( user.id, FileForm( @@ -284,6 +313,7 @@ async def upload_file_handler( 'name': name, 'content_type': (file.content_type if isinstance(file.content_type, str) else None), 'size': len(contents), + 'file_hash': file_hash, 'data': file_metadata, }, } diff --git a/backend/open_webui/routers/groups.py b/backend/open_webui/routers/groups.py index 3a06cb287c..6efcd3946e 100755 --- a/backend/open_webui/routers/groups.py +++ b/backend/open_webui/routers/groups.py @@ -336,29 +336,16 @@ async def preview_group_access( return { 'group': {'id': group.id, 'name': group.name}, 'models': { - 'items': [ - {'id': m.id, 'name': m.name} - for m in active_models - if m.id in accessible_model_ids - ], + 'items': [{'id': m.id, 'name': m.name} for m in active_models if m.id in accessible_model_ids], 'total': len(active_models), }, 'knowledge': { - 'items': [ - {'id': k.id, 'name': k.name} - for k in all_knowledge - if k.id in accessible_knowledge_ids - ], + 'items': [{'id': k.id, 'name': k.name} for k in all_knowledge if k.id in accessible_knowledge_ids], 'total': len(all_knowledge), }, 'tools': { - 'items': [ - {'id': t.id, 'name': t.name} - for t in all_tools - if t.id in accessible_tool_ids - ], + 'items': [{'id': t.id, 'name': t.name} for t in all_tools if t.id in accessible_tool_ids], 'total': len(all_tools), }, 'permissions': group.permissions or {}, } - diff --git a/backend/open_webui/routers/images.py b/backend/open_webui/routers/images.py index 4eced8cb0b..9d65cebfb8 100644 --- a/backend/open_webui/routers/images.py +++ b/backend/open_webui/routers/images.py @@ -447,6 +447,7 @@ def _is_same_origin(url: str, base_url: str) -> bool: and comparing the three origin components eliminates those attack vectors. """ + def _default_port(scheme: str) -> int: return 443 if scheme == 'https' else 80 @@ -455,8 +456,7 @@ def _is_same_origin(url: str, base_url: str) -> bool: return ( parsed.scheme == trusted.scheme and parsed.hostname == trusted.hostname - and (parsed.port or _default_port(parsed.scheme)) - == (trusted.port or _default_port(trusted.scheme)) + and (parsed.port or _default_port(parsed.scheme)) == (trusted.port or _default_port(trusted.scheme)) ) @@ -626,7 +626,7 @@ async def image_generations( ssl=AIOHTTP_CLIENT_SESSION_SSL, ) as r: r.raise_for_status() - res = await r.json() + res = await r.json(content_type=None) images = [] @@ -676,7 +676,7 @@ async def image_generations( ssl=AIOHTTP_CLIENT_SESSION_SSL, ) as r: r.raise_for_status() - res = await r.json() + res = await r.json(content_type=None) images = [] @@ -743,7 +743,8 @@ async def image_generations( headers = {'Authorization': f'Bearer {request.app.state.config.COMFYUI_API_KEY}'} image_data, content_type = await get_image_data( - image['url'], headers, + image['url'], + headers, trusted_base_url=request.app.state.config.COMFYUI_BASE_URL, ) _, url = await upload_image( @@ -785,7 +786,7 @@ async def image_generations( headers={'authorization': get_automatic1111_api_auth(request)}, ssl=AIOHTTP_CLIENT_SESSION_SSL, ) as r: - res = await r.json() + res = await r.json(content_type=None) log.debug(f'res: {res}') images = [] @@ -960,7 +961,7 @@ async def image_edits( ssl=AIOHTTP_CLIENT_SESSION_SSL, ) as r: r.raise_for_status() - res = await r.json() + res = await r.json(content_type=None) images = [] for image in res['data']: @@ -1015,7 +1016,7 @@ async def image_edits( ssl=AIOHTTP_CLIENT_SESSION_SSL, ) as r: r.raise_for_status() - res = await r.json() + res = await r.json(content_type=None) images = [] for image in res['candidates']: @@ -1102,7 +1103,8 @@ async def image_edits( headers = {'Authorization': f'Bearer {request.app.state.config.IMAGES_EDIT_COMFYUI_API_KEY}'} image_data, content_type = await get_image_data( - image_url, headers, + image_url, + headers, trusted_base_url=request.app.state.config.IMAGES_EDIT_COMFYUI_BASE_URL, ) _, url = await upload_image( diff --git a/backend/open_webui/routers/knowledge.py b/backend/open_webui/routers/knowledge.py index ccf99bde58..3506986429 100644 --- a/backend/open_webui/routers/knowledge.py +++ b/backend/open_webui/routers/knowledge.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import io import logging import zipfile @@ -12,7 +13,7 @@ from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL from open_webui.constants import ERROR_MESSAGES from open_webui.internal.db import get_async_session from open_webui.models.access_grants import AccessGrants -from open_webui.models.files import FileMetadataResponse, FileModel, Files +from open_webui.models.files import FileMetadataResponse, FileModel, FileModelResponse, Files from open_webui.models.groups import Groups from open_webui.models.knowledge import ( KnowledgeDirectoryForm, @@ -216,6 +217,7 @@ async def search_knowledge_bases( @router.get('/search/files', response_model=KnowledgeFileListResponse) async def search_knowledge_files( query: str | None = None, + include_content: bool = Query(False, description='Include file content in search (expensive).'), page: int | None = 1, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), @@ -227,6 +229,8 @@ async def search_knowledge_files( filter = {} if query: filter['query'] = query + if include_content: + filter['include_content'] = True groups = await Groups.get_groups_by_member_id(user.id, db=db) if groups: @@ -548,6 +552,71 @@ async def update_knowledge_access_by_id( ) +############################ +# GetPendingKnowledgeFiles +############################ + + +@router.get('/{id}/files/pending') +async def get_pending_knowledge_files( + id: str, + stream: bool = Query(False), + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + """Return files that are being processed for this knowledge base but not yet linked. + + After a file is uploaded with ``knowledge_id`` in its metadata, the backend + processes it in a background task before linking it to the ``knowledge_file`` + join table. During this window the file is invisible to the normal file + list endpoint. This endpoint exposes those in-flight files so the frontend + can show them with a processing indicator even after a page reload. + + When ``stream=true``, returns an SSE stream that polls every 3 seconds + and emits the current pending file list. Closes when no files remain. + """ + knowledge = await Knowledges.get_knowledge_by_id(id=id, db=db) + if not knowledge: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=ERROR_MESSAGES.NOT_FOUND, + ) + + if not ( + user.role == 'admin' + or knowledge.user_id == user.id + or await AccessGrants.has_access( + user_id=user.id, + resource_type='knowledge', + resource_id=knowledge.id, + permission='read', + db=db, + ) + ): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=ERROR_MESSAGES.ACCESS_PROHIBITED, + ) + + if not stream: + return await Files.get_pending_files_for_knowledge(id, db=db) + + async def event_stream(knowledge_id: str): + MAX_POLL_DURATION = 3600 # 1 hour max + for _ in range(MAX_POLL_DURATION // 3): + pending = await Files.get_pending_files_for_knowledge(knowledge_id) + data = [f.model_dump() for f in pending] + yield f'data: {json.dumps(data)}\n\n' + if len(pending) == 0: + break + await asyncio.sleep(3) + + return StreamingResponse( + event_stream(id), + media_type='text/event-stream', + ) + + ############################ # GetKnowledgeFilesById ############################ @@ -557,11 +626,13 @@ async def update_knowledge_access_by_id( async def get_knowledge_files_by_id( id: str, query: str | None = None, + include_content: bool = Query(False, description='Include file content in search (expensive).'), view_option: str | None = None, order_by: str | None = None, direction: str | None = None, directory_id: str | None = Query(None, description='Filter by directory ID. Pass empty string for root.'), page: int | None = 1, + limit: int | None = Query(None, description='Page size (admin only). Defaults to 30.'), user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): @@ -590,12 +661,18 @@ async def get_knowledge_files_by_id( page = max(page, 1) - limit = 30 + # Allow admins to configure page size; non-admins always get the default + if user.role == 'admin' and limit is not None: + limit = max(1, limit) + else: + limit = PAGE_ITEM_COUNT skip = (page - 1) * limit filter = {} if query: filter['query'] = query + if include_content: + filter['include_content'] = True if view_option: filter['view_option'] = view_option if order_by: @@ -846,10 +923,7 @@ async def remove_file_from_knowledge_by_id( log.debug(e) pass - # Only the file owner or an admin may permanently delete the underlying - # file. Collaborators with KB write access can unlink a file from the - # knowledge base but must not be able to destroy files they do not own, - # as the same file may be referenced by other KBs and chats. + # Anyone with write permission or higher can delete files if delete_file and (file.user_id == user.id or user.role == 'admin'): try: # Remove the file's collection from vector database @@ -949,7 +1023,10 @@ async def delete_knowledge_by_id( @router.post('/{id}/reset', response_model=KnowledgeResponse | None) async def reset_knowledge_by_id( - id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) + id: str, + include_directories: bool = Query(True), + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), ): knowledge = await Knowledges.get_knowledge_by_id(id=id, db=db) if not knowledge: @@ -980,10 +1057,189 @@ async def reset_knowledge_by_id( log.debug(e) pass - knowledge = await Knowledges.reset_knowledge_by_id(id=id, db=db) + knowledge = await Knowledges.reset_knowledge_by_id(id=id, include_directories=include_directories, db=db) return knowledge +############################ +# SyncKnowledgeDiff +############################ + + +class FileManifestEntry(BaseModel): + filename: str # basename: "readme.md" + path: str # relative dir: "docs/api" or "" for root + checksum: str # SHA-256 of raw bytes + size: int + + +class SyncDiffForm(BaseModel): + manifest: list[FileManifestEntry] + + +class SyncDiffResponse(BaseModel): + added: list[dict] # [{filename, path}] — new files + modified: list[dict] # [{filename, path, stale_file_id}] — changed files + deleted: list[dict] # [{file_id, filename}] — files to remove + mkdir: list[str] # directory paths to create + rmdir: list[str] # directory IDs to remove + unmodified_count: int + directory_map: dict[str, str] # existing path → directory ID + + +@router.post('/{id}/sync/diff', response_model=SyncDiffResponse) +async def sync_knowledge_diff( + id: str, + form_data: SyncDiffForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + """ + Compare a local file manifest against the knowledge base to determine + which files need uploading, removing, and which directories to create/remove. + """ + await _verify_knowledge_write_access(id, user, db) + + # ── Index existing state ── + knowledge_files = await Knowledges.get_files_with_directory_ids(id, db=db) + existing_directories = await Knowledges.get_all_directories(id, db=db) + + # Build directory path lookups + directory_path_by_id: dict[str, str] = {} + directory_id_by_path: dict[str, str] = {} + for directory in existing_directories: + segments = [directory.name] + parent_id = directory.parent_id + while parent_id: + parent = next((d for d in existing_directories if d.id == parent_id), None) + if not parent: + break + segments.insert(0, parent.name) + parent_id = parent.parent_id + full_path = '/'.join(segments) + directory_path_by_id[directory.id] = full_path + directory_id_by_path[full_path] = directory.id + + # Index existing files by (path, filename) → {file_id, checksum} + indexed_files: dict[tuple[str, str], dict] = {} + for file_model, directory_id in knowledge_files: + file_path = directory_path_by_id.get(directory_id, '') if directory_id else '' + stored_checksum = (file_model.meta or {}).get('file_hash') + indexed_files[(file_path, file_model.filename)] = { + 'file_id': file_model.id, + 'checksum': stored_checksum, + } + + # ── Diff files ── + added: list[dict] = [] + modified: list[dict] = [] + deleted: list[dict] = [] + unmodified_count = 0 + manifest_keys: set[tuple[str, str]] = set() + + for entry in form_data.manifest: + key = (entry.path, entry.filename) + manifest_keys.add(key) + + if key not in indexed_files: + added.append({'filename': entry.filename, 'path': entry.path}) + elif indexed_files[key]['checksum'] != entry.checksum: + modified.append( + { + 'filename': entry.filename, + 'path': entry.path, + 'stale_file_id': indexed_files[key]['file_id'], + } + ) + else: + unmodified_count += 1 + + for key, file_info in indexed_files.items(): + if key not in manifest_keys: + deleted.append({'file_id': file_info['file_id'], 'filename': key[1]}) + + # ── Diff directories ── + required_directory_paths: set[str] = set() + for entry in form_data.manifest: + if entry.path: + segments = entry.path.split('/') + for depth in range(len(segments)): + required_directory_paths.add('/'.join(segments[: depth + 1])) + + mkdir = sorted([p for p in required_directory_paths if p not in directory_id_by_path], key=lambda p: p.count('/')) + + orphaned_directory_paths = set(directory_id_by_path) - required_directory_paths + rmdir = [directory_id_by_path[p] for p in orphaned_directory_paths] + + return SyncDiffResponse( + added=added, + modified=modified, + deleted=deleted, + mkdir=mkdir, + rmdir=rmdir, + unmodified_count=unmodified_count, + directory_map=directory_id_by_path, + ) + + +############################ +# SyncKnowledgeCleanup +############################ + + +class SyncCleanupForm(BaseModel): + file_ids: list[str] # file IDs to delete + dir_ids: list[str] = [] # directory IDs to rmdir + + +@router.post('/{id}/sync/cleanup') +async def sync_knowledge_cleanup( + id: str, + form_data: SyncCleanupForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + """ + Remove stale files and orphaned directories from a knowledge base + after an incremental sync. + """ + await _verify_knowledge_write_access(id, user, db) + + # ── Remove deleted files ── + for file_id in form_data.file_ids: + file = await Files.get_file_by_id(file_id, db=db) + if not file: + continue + + await Knowledges.remove_file_from_knowledge_by_id(id, file_id, db=db) + + try: + await ASYNC_VECTOR_DB_CLIENT.delete(collection_name=id, filter={'file_id': file_id}) + await ASYNC_VECTOR_DB_CLIENT.delete(collection_name=id, filter={'hash': file.hash}) + except Exception: + pass + + try: + collection_name = f'file-{file_id}' + if await ASYNC_VECTOR_DB_CLIENT.has_collection(collection_name): + await ASYNC_VECTOR_DB_CLIENT.delete_collection(collection_name) + except Exception: + pass + + if file.user_id == user.id or user.role == 'admin': + await Files.delete_file_by_id(file_id, db=db) + try: + await asyncio.to_thread(Storage.delete_file, file.path) + except Exception: + pass + + # ── Remove orphaned directories (children before parents) ── + for dir_id in reversed(form_data.dir_ids): + await Knowledges.delete_directory(dir_id, move_files_to_parent=False, db=db) + + return {'status': True} + + ############################ # AddFilesToKnowledge ############################ @@ -1046,6 +1302,23 @@ async def add_files_to_knowledge_batch( detail=ERROR_MESSAGES.ACCESS_PROHIBITED, ) + # Filter out files already linked to this knowledge base to prevent + # duplicate embeddings in the vector DB (issue #10679). + new_entries = [] + for form in form_data: + if not await Knowledges.has_file(knowledge_id=id, file_id=form.file_id, db=db): + new_entries.append(form) + + if not new_entries: + return KnowledgeFilesResponse( + **knowledge.model_dump(), + files=await Knowledges.get_file_metadatas_by_id(knowledge.id, db=db), + ) + + # Narrow the file list to only new files for processing + new_file_ids = {form.file_id for form in new_entries} + files = [f for f in files if f.id in new_file_ids] + # Process files try: result = await process_files_batch( @@ -1060,8 +1333,15 @@ async def add_files_to_knowledge_batch( # Only add files that were successfully processed successful_file_ids = [r.file_id for r in result.results if r.status == 'completed'] + dir_map = {form.file_id: form.directory_id for form in new_entries} for file_id in successful_file_ids: - await Knowledges.add_file_to_knowledge_by_id(knowledge_id=id, file_id=file_id, user_id=user.id, db=db) + await Knowledges.add_file_to_knowledge_by_id( + knowledge_id=id, + file_id=file_id, + user_id=user.id, + directory_id=dir_map.get(file_id), + db=db, + ) # If there were any errors, include them in the response if result.errors: @@ -1152,9 +1432,7 @@ class KnowledgeFileMoveForm(BaseModel): directory_id: Optional[str] = None -async def _verify_knowledge_write_access( - id: str, user, db: AsyncSession -): +async def _verify_knowledge_write_access(id: str, user, db: AsyncSession): """Verify the user has write access to the knowledge base. Returns the knowledge model.""" knowledge = await Knowledges.get_knowledge_by_id(id=id, db=db) if not knowledge: @@ -1304,4 +1582,3 @@ async def move_file_in_knowledge( detail='Failed to move file.', ) return {'status': True} - diff --git a/backend/open_webui/routers/memories.py b/backend/open_webui/routers/memories.py index 5108ab0e7c..aad881b6da 100644 --- a/backend/open_webui/routers/memories.py +++ b/backend/open_webui/routers/memories.py @@ -9,6 +9,7 @@ from open_webui.constants import ERROR_MESSAGES from open_webui.internal.db import get_async_session from open_webui.models.memories import Memories, MemoryModel from open_webui.retrieval.vector.async_client import ASYNC_VECTOR_DB_CLIENT +from open_webui.config import RAG_EMBEDDING_QUERY_PREFIX from open_webui.utils.access_control import has_permission from open_webui.utils.auth import get_verified_user from pydantic import BaseModel @@ -66,10 +67,12 @@ async def add_memory( form_data: AddMemoryForm, user=Depends(get_verified_user), ): - # NOTE: We intentionally do NOT use Depends(get_async_session) here. - # Database operations (insert_new_memory) manage their own short-lived sessions. - # This prevents holding a connection during EMBEDDING_FUNCTION() - # which makes external embedding API calls (1-5+ seconds). + """Persist a new memory and embed it into the user's vector collection. + + Does NOT use ``Depends(get_async_session)`` — database operations manage their + own short-lived sessions so a connection is not held during the external + embedding API call (``EMBEDDING_FUNCTION``), which can take 1-5+ seconds. + """ if not request.app.state.config.ENABLE_MEMORIES: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, @@ -137,7 +140,7 @@ async def query_memory( if not memories: raise HTTPException(status_code=404, detail='No memories found for user') - vector = await request.app.state.EMBEDDING_FUNCTION(form_data.content, user=user) + vector = await request.app.state.EMBEDDING_FUNCTION(form_data.content, RAG_EMBEDDING_QUERY_PREFIX, user=user) results = await ASYNC_VECTOR_DB_CLIENT.search( collection_name=f'user-memory-{user.id}', diff --git a/backend/open_webui/routers/models.py b/backend/open_webui/routers/models.py index 922d016a2e..75ee4e723b 100644 --- a/backend/open_webui/routers/models.py +++ b/backend/open_webui/routers/models.py @@ -20,7 +20,7 @@ from fastapi import ( from fastapi.responses import RedirectResponse, StreamingResponse from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL from open_webui.constants import ERROR_MESSAGES -from open_webui.env import ENABLE_PROFILE_IMAGE_URL_FORWARDING +from open_webui.env import ENABLE_PROFILE_IMAGE_URL_FORWARDING, PROFILE_IMAGE_ALLOWED_MIME_TYPES from open_webui.internal.db import get_async_session from open_webui.models.access_grants import AccessGrants from open_webui.models.groups import Groups @@ -36,6 +36,7 @@ from open_webui.models.models import ( Models, ) from open_webui.utils.access_control import filter_allowed_access_grants, has_permission +from open_webui.utils.access_control.files import has_access_to_file from open_webui.utils.auth import get_admin_user, get_verified_user from pydantic import BaseModel from sqlalchemy.ext.asyncio import AsyncSession @@ -77,6 +78,32 @@ def is_valid_model_id(model_id: str) -> bool: return model_id and len(model_id) <= 256 +async def _verify_knowledge_file_access( + knowledge_items: list | None, + user, + db: AsyncSession, +) -> None: + """Raise 403 if any knowledge item references a file the caller cannot read.""" + if not knowledge_items or user.role == 'admin': + return + for item in knowledge_items: + if not isinstance(item, dict) or item.get('type') != 'file': + continue + file_id = item.get('id') + if not file_id: + continue + if not await has_access_to_file(file_id, 'read', user, db=db): + log.warning( + 'knowledge file access denied: user %s cannot read file %s', + user.id, + file_id, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=ERROR_MESSAGES.ACCESS_PROHIBITED, + ) + + ########################### # GetModels # Let each model here be judged by what it does and not @@ -198,6 +225,7 @@ async def create_new_model( user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): + """Create a new workspace model entry.""" if user.role != 'admin' and not await has_permission( user.id, 'workspace.models', request.app.state.config.USER_PERMISSIONS, db=db ): @@ -220,6 +248,12 @@ async def create_new_model( ) else: + await _verify_knowledge_file_access( + getattr(form_data.meta, 'knowledge', None) if form_data.meta else None, + user, + db, + ) + form_data.access_grants = await filter_allowed_access_grants( request.app.state.config.USER_PERMISSIONS, user.id, @@ -326,6 +360,21 @@ async def import_models( model_id = model_data.get('id') if model_id and is_valid_model_id(model_id): + # Defense-in-depth: skip models referencing inaccessible files + try: + await _verify_knowledge_file_access( + (model_data.get('meta') or {}).get('knowledge'), + user, + db, + ) + except HTTPException: + log.warning( + 'import_models: user %s skipped model %s (knowledge file access denied)', + user.id, + model_id, + ) + continue + existing_model = existing_models.get(model_id) if existing_model: # Enforce ownership/write-access before allowing overwrite @@ -504,9 +553,19 @@ async def get_model_profile_image( header, base64_data = profile_image_url.split(',', 1) image_data = base64.b64decode(base64_data) image_buffer = io.BytesIO(image_data) - media_type = header.split(';')[0].lstrip('data:') + media_type = header.split(';')[0].lstrip('data:').lower() - headers = {'Content-Disposition': 'inline'} + # only serve known-safe raster types inline; reject SVG/unknown (can run script on our origin) + if media_type not in PROFILE_IMAGE_ALLOWED_MIME_TYPES: + return RedirectResponse( + url='/static/favicon.png', + status_code=status.HTTP_302_FOUND, + ) + + headers = { + 'Content-Disposition': 'inline', + 'X-Content-Type-Options': 'nosniff', + } if updated_at: headers['ETag'] = f'"{updated_at}"' @@ -584,6 +643,7 @@ async def update_model_by_id( user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): + """Update a workspace model's configuration.""" model = await Models.get_model_by_id(form_data.id, db=db) if not model: raise HTTPException( @@ -607,6 +667,12 @@ async def update_model_by_id( detail=ERROR_MESSAGES.ACCESS_PROHIBITED, ) + await _verify_knowledge_file_access( + getattr(form_data.meta, 'knowledge', None) if form_data.meta else None, + user, + db, + ) + form_data.access_grants = await filter_allowed_access_grants( request.app.state.config.USER_PERMISSIONS, user.id, diff --git a/backend/open_webui/routers/ollama.py b/backend/open_webui/routers/ollama.py index d6348836e8..a4e166ba9e 100644 --- a/backend/open_webui/routers/ollama.py +++ b/backend/open_webui/routers/ollama.py @@ -1,8 +1,5 @@ from __future__ import annotations -# TODO: Implement a more intelligent load balancing mechanism for distributing requests among multiple backend instances. -# Current implementation uses a simple round-robin approach (random.choice). Consider incorporating algorithms like weighted round-robin, -# least connections, or least response time for better resource utilization and performance optimization. import asyncio import json import logging @@ -16,20 +13,12 @@ from urllib.parse import urlparse import aiohttp from aiocache import cached -from fastapi import ( - APIRouter, - Depends, - FastAPI, - File, - HTTPException, - Request, - UploadFile, -) -from fastapi.middleware.cors import CORSMiddleware +from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile from fastapi.responses import StreamingResponse -from open_webui.config import ( - UPLOAD_DIR, -) +from pydantic import BaseModel, ConfigDict, validator +from sqlalchemy.ext.asyncio import AsyncSession + +from open_webui.config import UPLOAD_DIR from open_webui.constants import ERROR_MESSAGES from open_webui.env import ( AIOHTTP_CLIENT_SESSION_SSL, @@ -37,46 +26,27 @@ from open_webui.env import ( AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST, BYPASS_MODEL_ACCESS_CONTROL, ENABLE_FORWARD_USER_INFO_HEADERS, - ENV, FORWARD_SESSION_INFO_HEADER_CHAT_ID, MODELS_CACHE_TTL, ) from open_webui.internal.db import get_async_session from open_webui.models.access_grants import AccessGrants -from open_webui.models.chats import Chats from open_webui.models.groups import Groups from open_webui.models.models import Models from open_webui.models.users import UserModel from open_webui.utils.access_control import check_model_access from open_webui.utils.auth import get_admin_user, get_verified_user from open_webui.utils.headers import include_user_info_headers -from open_webui.utils.misc import ( - calculate_sha256, -) +from open_webui.utils.misc import calculate_sha256 from open_webui.utils.payload import ( apply_model_params_to_body_ollama, apply_model_params_to_body_openai, apply_system_prompt_to_body, ) -from open_webui.utils.session_pool import ( - cleanup_response, - get_session, - stream_wrapper, -) -from pydantic import BaseModel, ConfigDict, validator -from sqlalchemy.ext.asyncio import AsyncSession +from open_webui.utils.session_pool import cleanup_response, get_session, stream_wrapper log = logging.getLogger(__name__) - -########################################## -# -# Utility functions -# Let what runs locally be trusted, and let no weight -# be loaded without serving the one who waits for the answer. -# -########################################## - # Headers that become stale after aiohttp auto-decompresses the upstream # response body. Forwarding them verbatim causes desktop / programmatic # clients to attempt decompression of an already-decoded payload, resulting @@ -89,27 +59,31 @@ def _clean_proxy_headers(raw_headers) -> dict: return {k: v for k, v in raw_headers.items() if k not in _STRIP_PROXY_HEADERS} -async def send_get_request(url, key=None, user: UserModel = None): - timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST) +async def send_get_request( + url: str, + key: str | None = None, + user: UserModel | None = None, +): + """Issue a GET request to an Ollama backend and return JSON, or *None* on failure.""" try: - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - headers = { - 'Content-Type': 'application/json', - **({'Authorization': f'Bearer {key}'} if key else {}), - } + session = await get_session() + headers: dict = { + 'Content-Type': 'application/json', + } + if key: + headers['Authorization'] = f'Bearer {key}' + if ENABLE_FORWARD_USER_INFO_HEADERS and user: + headers = include_user_info_headers(headers, user) - if ENABLE_FORWARD_USER_INFO_HEADERS and user: - headers = include_user_info_headers(headers, user) - - async with session.get( - url, - headers=headers, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as response: - return await response.json() - except Exception as e: - # Handle connection error here - log.error(f'Connection error: {e}') + async with session.get( + url, + headers=headers, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST), + ) as r: + return await r.json() + except Exception as exc: + log.error(f'Connection error: {exc}') return None @@ -210,7 +184,8 @@ router = APIRouter() @router.head('/') @router.get('/') -async def get_status(): +async def get_status() -> dict: + """Health-check endpoint.""" return {'status': True} @@ -220,48 +195,47 @@ class ConnectionVerificationForm(BaseModel): @router.post('/verify') -async def verify_connection(form_data: ConnectionVerificationForm, user=Depends(get_admin_user)): - url = form_data.url - key = form_data.key +async def verify_connection( + form_data: ConnectionVerificationForm, + user=Depends(get_admin_user), +): + """Verify that an Ollama backend at *form_data.url* is reachable.""" + try: + session = await get_session() + headers: dict = {} + if form_data.key: + headers['Authorization'] = f'Bearer {form_data.key}' + if ENABLE_FORWARD_USER_INFO_HEADERS and user: + headers = include_user_info_headers(headers, user) - async with aiohttp.ClientSession( - trust_env=True, - timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST), - ) as session: - try: - headers = { - **({'Authorization': f'Bearer {key}'} if key else {}), - } + async with session.get( + f'{form_data.url}/api/version', + headers=headers, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST), + ) as r: + if r.status != 200: + detail = f'HTTP Error: {r.status}' + res = await r.json() + if 'error' in res: + detail = f'External Error: {res["error"]}' + raise Exception(detail) - if ENABLE_FORWARD_USER_INFO_HEADERS and user: - headers = include_user_info_headers(headers, user) - - async with session.get( - f'{url}/api/version', - headers=headers, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as r: - if r.status != 200: - detail = f'HTTP Error: {r.status}' - res = await r.json() - - if 'error' in res: - detail = f'External Error: {res["error"]}' - raise Exception(detail) - - data = await r.json() - return data - except aiohttp.ClientError as e: - log.exception(f'Client error: {str(e)}') - raise HTTPException(status_code=500, detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR) - except Exception as e: - log.exception(f'Unexpected error: {e}') - error_detail = f'Unexpected error: {str(e)}' - raise HTTPException(status_code=500, detail=error_detail) + return await r.json() + except aiohttp.ClientError as exc: + log.exception(f'Client error: {exc}') + raise HTTPException(status_code=500, detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR) + except Exception as exc: + log.exception(f'Unexpected error: {exc}') + raise HTTPException(status_code=500, detail=f'Unexpected error: {exc}') @router.get('/config') -async def get_config(request: Request, user=Depends(get_admin_user)): +async def get_config( + request: Request, + user=Depends(get_admin_user), +) -> dict: + """Return the current Ollama connection configuration.""" return { 'ENABLE_OLLAMA_API': request.app.state.config.ENABLE_OLLAMA_API, 'OLLAMA_BASE_URLS': request.app.state.config.OLLAMA_BASE_URLS, @@ -270,22 +244,28 @@ async def get_config(request: Request, user=Depends(get_admin_user)): class OllamaConfigForm(BaseModel): + """Payload for updating the Ollama connection configuration.""" + ENABLE_OLLAMA_API: bool | None = None OLLAMA_BASE_URLS: list[str] OLLAMA_API_CONFIGS: dict @router.post('/config/update') -async def update_config(request: Request, form_data: OllamaConfigForm, user=Depends(get_admin_user)): +async def update_config( + request: Request, + form_data: OllamaConfigForm, + user=Depends(get_admin_user), +) -> dict: + """Persist updated Ollama connection settings.""" request.app.state.config.ENABLE_OLLAMA_API = form_data.ENABLE_OLLAMA_API - request.app.state.config.OLLAMA_BASE_URLS = form_data.OLLAMA_BASE_URLS request.app.state.config.OLLAMA_API_CONFIGS = form_data.OLLAMA_API_CONFIGS - # Remove the API configs that are not in the API URLS - keys = list(map(str, range(len(request.app.state.config.OLLAMA_BASE_URLS)))) + # Prune stale config entries that no longer map to a URL index + valid_keys = {str(i) for i in range(len(request.app.state.config.OLLAMA_BASE_URLS))} request.app.state.config.OLLAMA_API_CONFIGS = { - key: value for key, value in request.app.state.config.OLLAMA_API_CONFIGS.items() if key in keys + k: v for k, v in request.app.state.config.OLLAMA_API_CONFIGS.items() if k in valid_keys } return { @@ -295,120 +275,103 @@ async def update_config(request: Request, form_data: OllamaConfigForm, user=Depe } -def merge_ollama_models_lists(model_lists): - merged_models = {} +def merge_models_lists(model_lists) -> list[dict]: + """De-duplicate model entries across multiple Ollama backends, tracking which URL index hosts each model.""" + merged: dict[str, dict] = {} + for idx, entries in enumerate(model_lists): + if entries is None: + continue + for entry in entries: + model_id = entry.get('model') + if model_id is None: + continue + if model_id not in merged: + entry['urls'] = [idx] + merged[model_id] = entry + else: + merged[model_id]['urls'].append(idx) + return list(merged.values()) - for idx, model_list in enumerate(model_lists): - if model_list is not None: - for model in model_list: - id = model.get('model') - if id is not None: - if id not in merged_models: - model['urls'] = [idx] - merged_models[id] = model - else: - merged_models[id]['urls'].append(idx) - return list(merged_models.values()) +def _resolve_api_config(request: Request, idx: int, url: str) -> dict: + """Look up the API config for a backend by numeric index, falling back to URL key (legacy).""" + api_configs = request.app.state.config.OLLAMA_API_CONFIGS + return api_configs.get(str(idx), api_configs.get(url, {})) @cached( ttl=MODELS_CACHE_TTL, key=lambda _, user: f'ollama_all_models_{user.id}' if user else 'ollama_all_models', ) -async def get_all_models(request: Request, user: UserModel = None): +async def get_all_models(request: Request, user: UserModel | None = None): + """Aggregate model tags from every enabled Ollama backend.""" log.info('get_all_models()') - if request.app.state.config.ENABLE_OLLAMA_API: - request_tasks = [] - for idx, url in enumerate(request.app.state.config.OLLAMA_BASE_URLS): - if (str(idx) not in request.app.state.config.OLLAMA_API_CONFIGS) and ( - url not in request.app.state.config.OLLAMA_API_CONFIGS # Legacy support - ): - request_tasks.append(send_get_request(f'{url}/api/tags', user=user)) - else: - api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( - str(idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support - ) - enable = api_config.get('enable', True) - key = api_config.get('key', None) + if not request.app.state.config.ENABLE_OLLAMA_API: + models_dict: dict = {'models': []} + request.app.state.OLLAMA_MODELS = {} + return models_dict - if enable: - request_tasks.append(send_get_request(f'{url}/api/tags', key, user=user)) - else: - request_tasks.append(asyncio.ensure_future(asyncio.sleep(0, None))) + # Fan-out tag requests to every backend + tasks = [] + for idx, url in enumerate(request.app.state.config.OLLAMA_BASE_URLS): + api_config = _resolve_api_config(request, idx, url) + if not api_config: + tasks.append(send_get_request(f'{url}/api/tags', user=user)) + elif api_config.get('enable', True): + tasks.append(send_get_request(f'{url}/api/tags', api_config.get('key'), user=user)) + else: + tasks.append(asyncio.ensure_future(asyncio.sleep(0, None))) - responses = await asyncio.gather(*request_tasks) + responses = await asyncio.gather(*tasks) - for idx, response in enumerate(responses): - if response: - url = request.app.state.config.OLLAMA_BASE_URLS[idx] - api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( - str(idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support - ) + # Post-process each response: apply prefix_id, tags, model filtering + for idx, response in enumerate(responses): + if not response: + continue + url = request.app.state.config.OLLAMA_BASE_URLS[idx] + api_config = _resolve_api_config(request, idx, url) - connection_type = api_config.get('connection_type', 'local') + connection_type = api_config.get('connection_type', 'local') + prefix_id = api_config.get('prefix_id') + allowed_tags = api_config.get('tags', []) + allowed_model_ids = api_config.get('model_ids', []) - prefix_id = api_config.get('prefix_id', None) - tags = api_config.get('tags', []) - model_ids = api_config.get('model_ids', []) + if allowed_model_ids and 'models' in response: + response['models'] = [m for m in response['models'] if m['model'] in allowed_model_ids] - if len(model_ids) != 0 and 'models' in response: - response['models'] = list( - filter( - lambda model: model['model'] in model_ids, - response['models'], - ) - ) + for m in response.get('models', []): + if prefix_id: + m['model'] = f'{prefix_id}.{m["model"]}' + if allowed_tags: + m['tags'] = allowed_tags + if connection_type: + m['connection_type'] = connection_type - for model in response.get('models', []): - if prefix_id: - model['model'] = f'{prefix_id}.{model["model"]}' + models_dict = {'models': merge_models_lists(r.get('models', []) if r else None for r in responses)} - if tags: - model['tags'] = tags + # Annotate with expiry info from loaded-model state + try: + loaded = await get_ollama_loaded_models(request, user=user) + expires_map = {m['model']: m['expires_at'] for m in loaded['models'] if 'expires_at' in m} + for m in models_dict['models']: + if m['model'] in expires_map: + dt = datetime.fromisoformat(expires_map[m['model']]) + m['expires_at'] = int(dt.timestamp()) + except Exception as exc: + log.debug(f'Failed to get loaded models: {exc}') - if connection_type: - model['connection_type'] = connection_type - - models = { - 'models': merge_ollama_models_lists( - map( - lambda response: response.get('models', []) if response else None, - responses, - ) - ) - } - - try: - loaded_models = await get_ollama_loaded_models(request, user=user) - expires_map = {m['model']: m['expires_at'] for m in loaded_models['models'] if 'expires_at' in m} - - for m in models['models']: - if m['model'] in expires_map: - # Parse ISO8601 datetime with offset, get unix timestamp as int - dt = datetime.fromisoformat(expires_map[m['model']]) - m['expires_at'] = int(dt.timestamp()) - except Exception as e: - log.debug(f'Failed to get loaded models: {e}') - - else: - models = {'models': []} - - request.app.state.OLLAMA_MODELS = {model['model']: model for model in models['models']} - return models + request.app.state.OLLAMA_MODELS = {m['model']: m for m in models_dict['models']} + return models_dict async def get_filtered_models(models, user, db=None): - # Filter models based on user access control - model_ids = [model['model'] for model in models.get('models', [])] - model_infos = {model_info.id: model_info for model_info in await Models.get_models_by_ids(model_ids, db=db)} - user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, db=db)} + """Return only the models the given *user* is allowed to access.""" + model_ids = [m['model'] for m in models.get('models', [])] + model_infos = {mi.id: mi for mi in await Models.get_models_by_ids(model_ids, db=db)} + user_group_ids = {g.id for g in await Groups.get_groups_by_member_id(user.id, db=db)} - # Batch-fetch accessible resource IDs in a single query instead of N has_access calls - accessible_model_ids = await AccessGrants.get_accessible_resource_ids( + accessible_ids = await AccessGrants.get_accessible_resource_ids( user_id=user.id, resource_type='model', resource_ids=list(model_infos.keys()), @@ -416,145 +379,112 @@ async def get_filtered_models(models, user, db=None): user_group_ids=user_group_ids, db=db, ) - - filtered_models = [] - for model in models.get('models', []): - model_info = model_infos.get(model['model']) - if model_info: - if user.id == model_info.user_id or model_info.id in accessible_model_ids: - filtered_models.append(model) - return filtered_models + return [ + m + for m in models.get('models', []) + if (mi := model_infos.get(m['model'])) and (user.id == mi.user_id or mi.id in accessible_ids) + ] @router.get('/api/tags') @router.get('/api/tags/{url_idx}') -async def get_ollama_tags(request: Request, url_idx: int | None = None, user=Depends(get_verified_user)): +async def get_ollama_tags( + request: Request, + url_idx: int | None = None, + user=Depends(get_verified_user), +): + """List Ollama model tags, optionally from a specific backend.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) - models = [] - if url_idx is None: - models = await get_all_models(request, user=user) + result = await get_all_models(request, user=user) else: url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] key = get_api_key(url_idx, url, request.app.state.config.OLLAMA_API_CONFIGS) - models = await send_request(f'{url}/api/tags', 'GET', key=key, user=user) + result = await send_request(f'{url}/api/tags', 'GET', key=key, user=user) if user.role == 'user' and not BYPASS_MODEL_ACCESS_CONTROL: - models['models'] = await get_filtered_models(models, user) + result['models'] = await get_filtered_models(result, user) - return models + return result @router.get('/api/ps') -async def get_ollama_loaded_models(request: Request, user=Depends(get_admin_user)): - """ - List models that are currently loaded into Ollama memory, and which node they are loaded on. - """ - if request.app.state.config.ENABLE_OLLAMA_API: - request_tasks = [] - for idx, url in enumerate(request.app.state.config.OLLAMA_BASE_URLS): - if (str(idx) not in request.app.state.config.OLLAMA_API_CONFIGS) and ( - url not in request.app.state.config.OLLAMA_API_CONFIGS # Legacy support - ): - request_tasks.append(send_get_request(f'{url}/api/ps', user=user)) - else: - api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( - str(idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support - ) +async def get_ollama_loaded_models( + request: Request, + user=Depends(get_admin_user), +) -> dict: + """List models currently loaded in Ollama memory across all backends.""" + if not request.app.state.config.ENABLE_OLLAMA_API: + return {'models': []} - enable = api_config.get('enable', True) - key = api_config.get('key', None) + tasks = [] + for idx, url in enumerate(request.app.state.config.OLLAMA_BASE_URLS): + api_config = _resolve_api_config(request, idx, url) + if not api_config: + tasks.append(send_get_request(f'{url}/api/ps', user=user)) + elif api_config.get('enable', True): + tasks.append(send_get_request(f'{url}/api/ps', api_config.get('key'), user=user)) + else: + tasks.append(asyncio.ensure_future(asyncio.sleep(0, None))) - if enable: - request_tasks.append(send_get_request(f'{url}/api/ps', key, user=user)) - else: - request_tasks.append(asyncio.ensure_future(asyncio.sleep(0, None))) + responses = await asyncio.gather(*tasks) - responses = await asyncio.gather(*request_tasks) + for idx, response in enumerate(responses): + if not response: + continue + api_config = _resolve_api_config(request.app.state.config, idx, request.app.state.config.OLLAMA_BASE_URLS[idx]) + prefix_id = api_config.get('prefix_id') + if prefix_id: + for m in response.get('models', []): + m['model'] = f'{prefix_id}.{m["model"]}' - for idx, response in enumerate(responses): - if response: - url = request.app.state.config.OLLAMA_BASE_URLS[idx] - api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( - str(idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support - ) - - prefix_id = api_config.get('prefix_id', None) - - for model in response.get('models', []): - if prefix_id: - model['model'] = f'{prefix_id}.{model["model"]}' - - models = { - 'models': merge_ollama_models_lists( - map( - lambda response: response.get('models', []) if response else None, - responses, - ) - ) - } - else: - models = {'models': []} - - return models + return {'models': merge_models_lists(r.get('models', []) if r else None for r in responses)} @router.get('/api/version') @router.get('/api/version/{url_idx}') -async def get_ollama_versions(request: Request, url_idx: int | None = None): - if request.app.state.config.ENABLE_OLLAMA_API: - if url_idx is None: - # returns lowest version - request_tasks = [] - - for idx, url in enumerate(request.app.state.config.OLLAMA_BASE_URLS): - api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( - str(idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support - ) - - enable = api_config.get('enable', True) - key = api_config.get('key', None) - - if enable: - request_tasks.append( - send_get_request( - f'{url}/api/version', - key, - ) - ) - - responses = await asyncio.gather(*request_tasks) - responses = list(filter(lambda x: x is not None, responses)) - - if len(responses) > 0: - lowest_version = min( - responses, - key=lambda x: tuple(map(int, re.sub(r'^v|-.*', '', x['version']).split('.'))), - ) - - return {'version': lowest_version['version']} - else: - raise HTTPException( - status_code=500, - detail=ERROR_MESSAGES.OLLAMA_NOT_FOUND, - ) - else: - url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] - return await send_request(f'{url}/api/version', 'GET') - else: +async def get_ollama_versions( + request: Request, + url_idx: int | None = None, +): + """Return the lowest Ollama version across all configured backends.""" + if not request.app.state.config.ENABLE_OLLAMA_API: return {'version': False} + if url_idx is not None: + url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] + return await send_request(f'{url}/api/version', 'GET') + + # Fan-out to every enabled backend + tasks = [] + for idx, url in enumerate(request.app.state.config.OLLAMA_BASE_URLS): + api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( + str(idx), + request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), + ) + if api_config.get('enable', True): + tasks.append(send_get_request(f'{url}/api/version', api_config.get('key'))) + + raw = await asyncio.gather(*tasks) + valid = [r for r in raw if r is not None] + + if not valid: + raise HTTPException(status_code=500, detail=ERROR_MESSAGES.OLLAMA_NOT_FOUND) + + lowest = min( + valid, + key=lambda v: tuple(map(int, re.sub(r'^v|-.*', '', v['version']).split('.'))), + ) + return {'version': lowest['version']} + class ModelNameForm(BaseModel): + """Generic form carrying an optional model identifier.""" + model: str | None = None - model_config = ConfigDict( - extra='allow', - ) + model_config = ConfigDict(extra='allow') @router.post('/api/unload') @@ -564,18 +494,18 @@ async def unload_model( user=Depends(get_admin_user), ): form_data = form_data.model_dump(exclude_none=True) - model_name = form_data.get('model', form_data.get('name')) + model = form_data.get('model', form_data.get('name')) - if not model_name: + if not model: raise HTTPException(status_code=400, detail='Missing name of the model to unload.') # Refresh/load models if needed, get mapping from name to URLs await get_all_models(request, user=user) models = request.app.state.OLLAMA_MODELS - if model_name not in models: - raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model_name)) - url_indices = models[model_name]['urls'] + if model not in models: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model)) + url_indices = models[model]['urls'] # Send unload to ALL url_indices results = [] @@ -588,10 +518,10 @@ async def unload_model( key = get_api_key(idx, url, request.app.state.config.OLLAMA_API_CONFIGS) prefix_id = api_config.get('prefix_id', None) - if prefix_id and model_name.startswith(f'{prefix_id}.'): - model_name = model_name[len(f'{prefix_id}.') :] + if prefix_id and model.startswith(f'{prefix_id}.'): + model = model[len(f'{prefix_id}.') :] - payload = {'model': model_name, 'keep_alive': 0, 'prompt': ''} + payload = {'model': model, 'keep_alive': 0, 'prompt': ''} try: res = await send_request( @@ -631,12 +561,10 @@ async def pull_model( url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] log.info(f'url: {url}') - # Admin should be able to pull models from any source - payload = {**form_data, 'insecure': True} - + # Admins may pull from any registry return await send_request( f'{url}/api/pull', - payload=json.dumps(payload), + payload=json.dumps({**form_data, 'insecure': True}), key=get_api_key(url_idx, url, request.app.state.config.OLLAMA_API_CONFIGS), user=user, stream=True, @@ -644,6 +572,8 @@ async def pull_model( class PushModelForm(BaseModel): + """Payload for pushing a model to a registry.""" + model: str insecure: bool | None = None stream: bool | None = None @@ -657,20 +587,16 @@ async def push_model( url_idx: int | None = None, user=Depends(get_admin_user), ): + """Push a local model to a remote registry.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) if url_idx is None: await get_all_models(request, user=user) models = request.app.state.OLLAMA_MODELS - - if form_data.model in models: - url_idx = models[form_data.model]['urls'][0] - else: - raise HTTPException( - status_code=400, - detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model), - ) + if form_data.model not in models: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model)) + url_idx = models[form_data.model]['urls'][0] url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] log.debug(f'url: {url}') @@ -685,10 +611,11 @@ async def push_model( class CreateModelForm(BaseModel): + """Payload for creating a new model via Modelfile.""" + model: str | None = None stream: bool | None = None path: str | None = None - model_config = ConfigDict(extra='allow') @@ -716,6 +643,8 @@ async def create_model( class CopyModelForm(BaseModel): + """Payload for duplicating an existing model under a new name.""" + source: str destination: str @@ -728,20 +657,16 @@ async def copy_model( url_idx: int | None = None, user=Depends(get_admin_user), ): + """Duplicate an existing model under a new name.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) if url_idx is None: await get_all_models(request, user=user) models = request.app.state.OLLAMA_MODELS - - if form_data.source in models: - url_idx = models[form_data.source]['urls'][0] - else: - raise HTTPException( - status_code=400, - detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source), - ) + if form_data.source not in models: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source)) + url_idx = models[form_data.source]['urls'][0] url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] key = get_api_key(url_idx, url, request.app.state.config.OLLAMA_API_CONFIGS) @@ -763,25 +688,20 @@ async def delete_model( url_idx: int | None = None, user=Depends(get_admin_user), ): + """Remove a model from an Ollama backend.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) - form_data = form_data.model_dump(exclude_none=True) - form_data['model'] = form_data.get('model', form_data.get('name')) - - model = form_data.get('model') + payload = form_data.model_dump(exclude_none=True) + payload['model'] = payload.get('model', payload.get('name')) + model = payload.get('model') if url_idx is None: await get_all_models(request, user=user) models = request.app.state.OLLAMA_MODELS - - if model in models: - url_idx = models[model]['urls'][0] - else: - raise HTTPException( - status_code=400, - detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model), - ) + if model not in models: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model)) + url_idx = models[model]['urls'][0] url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] key = get_api_key(url_idx, url, request.app.state.config.OLLAMA_API_CONFIGS) @@ -789,7 +709,7 @@ async def delete_model( await send_request( f'{url}/api/delete', 'DELETE', - payload=json.dumps(form_data), + payload=json.dumps(payload), key=key, user=user, ) @@ -797,50 +717,48 @@ async def delete_model( @router.post('/api/show') -async def show_model_info(request: Request, form_data: ModelNameForm, user=Depends(get_verified_user)): +async def show_model_info( + request: Request, + form_data: ModelNameForm, + user=Depends(get_verified_user), +): + """Retrieve model metadata from the Ollama backend.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) - form_data = form_data.model_dump(exclude_none=True) - form_data['model'] = form_data.get('model', form_data.get('name')) + payload = form_data.model_dump(exclude_none=True) + payload['model'] = payload.get('model', payload.get('name')) + model = payload.get('model') - model = form_data.get('model') - - # Enforce per-model access control await check_model_access(user, await Models.get_model_by_id(model), BYPASS_MODEL_ACCESS_CONTROL) await get_all_models(request, user=user) models = request.app.state.OLLAMA_MODELS if model not in models: - raise HTTPException( - status_code=400, - detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model), - ) + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model)) url_idx = random.choice(models[model]['urls']) - url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] key = get_api_key(url_idx, url, request.app.state.config.OLLAMA_API_CONFIGS) return await send_request( f'{url}/api/show', - payload=json.dumps(form_data), + payload=json.dumps(payload), key=key, user=user, ) class GenerateEmbedForm(BaseModel): + """Payload for the newer /api/embed endpoint (batch-capable).""" + model: str input: list[str] | str truncate: bool | None = None options: dict | None = None keep_alive: Union[int, str | None] = None - - model_config = ConfigDict( - extra='allow', - ) + model_config = ConfigDict(extra='allow') @router.post('/api/embed') @@ -851,39 +769,32 @@ async def embed( url_idx: int | None = None, user=Depends(get_verified_user), ): + """Generate embeddings via the Ollama /api/embed endpoint.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) log.info(f'generate_ollama_batch_embeddings {form_data}') - - # Enforce per-model access control await check_model_access(user, await Models.get_model_by_id(form_data.model), BYPASS_MODEL_ACCESS_CONTROL) + await validate_ollama_backend_idx(request, form_data.model, url_idx, user) if url_idx is None: model = form_data.model - - # Check if model is already in app state cache to avoid expensive get_all_models() call models = request.app.state.OLLAMA_MODELS if not models or model not in models: await get_all_models(request, user=user) models = request.app.state.OLLAMA_MODELS - - if model in models: - url_idx = random.choice(models[model]['urls']) - else: - raise HTTPException( - status_code=400, - detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model), - ) + if model not in models: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model)) + url_idx = random.choice(models[model]['urls']) url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( str(url_idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support + request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), ) key = get_api_key(url_idx, url, request.app.state.config.OLLAMA_API_CONFIGS) - prefix_id = api_config.get('prefix_id', None) + prefix_id = api_config.get('prefix_id') if prefix_id: form_data.model = form_data.model.replace(f'{prefix_id}.', '') @@ -896,6 +807,8 @@ async def embed( class GenerateEmbeddingsForm(BaseModel): + """Payload for the legacy /api/embeddings endpoint (single-prompt).""" + model: str prompt: str options: dict | None = None @@ -910,39 +823,32 @@ async def embeddings( url_idx: int | None = None, user=Depends(get_verified_user), ): + """Generate embeddings via the legacy Ollama /api/embeddings endpoint.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) log.info(f'generate_ollama_embeddings {form_data}') - - # Enforce per-model access control await check_model_access(user, await Models.get_model_by_id(form_data.model), BYPASS_MODEL_ACCESS_CONTROL) + await validate_ollama_backend_idx(request, form_data.model, url_idx, user) if url_idx is None: model = form_data.model - - # Check if model is already in app state cache to avoid expensive get_all_models() call models = request.app.state.OLLAMA_MODELS if not models or model not in models: await get_all_models(request, user=user) models = request.app.state.OLLAMA_MODELS - - if model in models: - url_idx = random.choice(models[model]['urls']) - else: - raise HTTPException( - status_code=400, - detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model), - ) + if model not in models: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model)) + url_idx = random.choice(models[model]['urls']) url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( str(url_idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support + request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), ) key = get_api_key(url_idx, url, request.app.state.config.OLLAMA_API_CONFIGS) - prefix_id = api_config.get('prefix_id', None) + prefix_id = api_config.get('prefix_id') if prefix_id: form_data.model = form_data.model.replace(f'{prefix_id}.', '') @@ -955,6 +861,8 @@ async def embeddings( class GenerateCompletionForm(BaseModel): + """Payload for the Ollama /api/generate endpoint.""" + model: str prompt: str | None = None suffix: str | None = None @@ -977,33 +885,28 @@ async def generate_completion( url_idx: int | None = None, user=Depends(get_verified_user), ): + """Run text completion via Ollama /api/generate.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) - # Enforce per-model access control await check_model_access(user, await Models.get_model_by_id(form_data.model), BYPASS_MODEL_ACCESS_CONTROL) + await validate_ollama_backend_idx(request, form_data.model, url_idx, user) if url_idx is None: await get_all_models(request, user=user) models = request.app.state.OLLAMA_MODELS - model = form_data.model - - if model in models: - url_idx = random.choice(models[model]['urls']) - else: - raise HTTPException( - status_code=400, - detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model), - ) + if model not in models: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model)) + url_idx = random.choice(models[model]['urls']) url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( str(url_idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support + request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), ) - prefix_id = api_config.get('prefix_id', None) + prefix_id = api_config.get('prefix_id') if prefix_id: form_data.model = form_data.model.replace(f'{prefix_id}.', '') @@ -1017,24 +920,25 @@ async def generate_completion( class ChatMessage(BaseModel): + """A single message in an Ollama chat conversation.""" + role: str content: str | None = None tool_calls: list[dict | None] = None images: list[str | None] = None - model_config = ConfigDict(extra='allow') @validator('content', pre=True) @classmethod def check_at_least_one_field(cls, field_value, values, **kwargs): - # Raise an error if both 'content' and 'tool_calls' are None if field_value is None and ('tool_calls' not in values or values['tool_calls'] is None): raise ValueError("At least one of 'content' or 'tool_calls' must be provided") - return field_value class GenerateChatCompletionForm(BaseModel): + """Payload for the Ollama /api/chat endpoint.""" + model: str messages: list[ChatMessage] format: Union[dict, str | None] = None @@ -1043,12 +947,24 @@ class GenerateChatCompletionForm(BaseModel): stream: bool | None = True keep_alive: Union[int, str | None] = None tools: list[dict | None] = None - model_config = ConfigDict( - extra='allow', - ) + model_config = ConfigDict(extra='allow') -async def get_ollama_url(request: Request, model: str, url_idx: int | None = None): +async def validate_ollama_backend_idx(request: Request, model: str, url_idx: int | None, user) -> None: + # A caller-supplied url_idx must point to a backend the model is actually + # served from; the None path is already constrained to that allow-list. + if url_idx is None or user is None or getattr(user, 'role', None) == 'admin' or BYPASS_MODEL_ACCESS_CONTROL: + return + models = request.app.state.OLLAMA_MODELS + if not models or model not in models: + await get_all_models(request, user=user) + models = request.app.state.OLLAMA_MODELS + if url_idx not in (models.get(model) or {}).get('urls', []): + raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + + +async def get_ollama_url(request: Request, model: str, url_idx: int | None = None, user=None): + await validate_ollama_backend_idx(request, model, url_idx, user) if url_idx is None: models = request.app.state.OLLAMA_MODELS if model not in models: @@ -1067,9 +983,9 @@ async def generate_chat_completion( request: Request, form_data: dict, url_idx: int | None = None, - user=Depends(get_verified_user), - bypass_system_prompt: bool = False, + user=Depends(get_verified_user), # noqa: B008 ): + """Forward a chat completion request to an Ollama backend.""" if not request.app.state.config.ENABLE_OLLAMA_API: raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED) @@ -1078,44 +994,38 @@ async def generate_chat_completion( # This prevents holding a connection during the entire LLM call (30-60+ seconds), # which would exhaust the connection pool under concurrent load. - # bypass_filter is read from request.state to prevent external clients from - # setting it via query parameter (CVE fix). Only internal server-side callers - # (e.g. utils/chat.py) should set request.state.bypass_filter = True. + # bypass_filter and bypass_system_prompt are read from request.state to prevent + # external clients from setting them via query parameter. Only internal + # server-side callers (e.g. utils/chat.py) should set + # request.state.bypass_filter / request.state.bypass_system_prompt = True. bypass_filter = getattr(request.state, 'bypass_filter', False) if BYPASS_MODEL_ACCESS_CONTROL: bypass_filter = True + bypass_system_prompt = getattr(request.state, 'bypass_system_prompt', False) metadata = form_data.pop('metadata', None) try: form_data = GenerateChatCompletionForm(**form_data) - except Exception as e: - log.exception(e) - raise HTTPException( - status_code=400, - detail=str(e), - ) + except Exception as exc: + log.exception(exc) + raise HTTPException(status_code=400, detail=str(exc)) if isinstance(form_data, BaseModel): payload = {**form_data.model_dump(exclude_none=True)} - if 'metadata' in payload: - del payload['metadata'] + payload.pop('metadata', None) model_id = payload['model'] model_info = await Models.get_model_by_id(model_id) - if model_info: + if model_info is not None: if model_info.base_model_id: - base_model_id = ( - request.base_model_id if hasattr(request, 'base_model_id') else model_info.base_model_id - ) # Use request's base_model_id if available + base_model_id = request.base_model_id if hasattr(request, 'base_model_id') else model_info.base_model_id payload['model'] = base_model_id params = model_info.params.model_dump() - if params: system = params.pop('system', None) - payload = apply_model_params_to_body_ollama(params, payload) if not bypass_system_prompt: payload = await apply_system_prompt_to_body(system, payload, metadata, user) @@ -1124,13 +1034,10 @@ async def generate_chat_completion( else: await check_model_access(user, None, bypass_filter) - url, url_idx = await get_ollama_url(request, payload['model'], url_idx) - api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( - str(url_idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support - ) + url, url_idx = await get_ollama_url(request, payload['model'], url_idx, user) + api_config = _resolve_api_config(request, url_idx, url) - prefix_id = api_config.get('prefix_id', None) + prefix_id = api_config.get('prefix_id') if prefix_id: payload['model'] = payload['model'].replace(f'{prefix_id}.', '') @@ -1147,28 +1054,33 @@ async def generate_chat_completion( # TODO: we should update this part once Ollama supports other types class OpenAIChatMessageContent(BaseModel): + """Content block within an OpenAI-style chat message.""" + type: str model_config = ConfigDict(extra='allow') class OpenAIChatMessage(BaseModel): + """A single message in an OpenAI-compatible chat request.""" + role: str content: Union[str | None, list[OpenAIChatMessageContent]] - model_config = ConfigDict(extra='allow') class OpenAIChatCompletionForm(BaseModel): + """Payload for the OpenAI-compatible /v1/chat/completions proxy.""" + model: str messages: list[OpenAIChatMessage] - model_config = ConfigDict(extra='allow') class OpenAICompletionForm(BaseModel): + """Payload for the OpenAI-compatible /v1/completions proxy.""" + model: str prompt: str - model_config = ConfigDict(extra='allow') @@ -1178,8 +1090,9 @@ async def generate_openai_completion( request: Request, form_data: dict, url_idx: int | None = None, - user=Depends(get_verified_user), + user=Depends(get_verified_user), # noqa: B008 ): + """Forward a text completion request via the OpenAI-compatible proxy.""" # NOTE: We intentionally do NOT use Depends(get_async_session) here. # Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions. # This prevents holding a connection during the entire LLM call (30-60+ seconds), @@ -1188,39 +1101,29 @@ async def generate_openai_completion( try: form_data = OpenAICompletionForm(**form_data) - except Exception as e: - log.exception(e) - raise HTTPException( - status_code=400, - detail=str(e), - ) + except Exception as exc: + log.exception(exc) + raise HTTPException(status_code=400, detail=str(exc)) payload = {**form_data.model_dump(exclude_none=True, exclude=['metadata'])} - if 'metadata' in payload: - del payload['metadata'] + payload.pop('metadata', None) model_id = form_data.model model_info = await Models.get_model_by_id(model_id) - if model_info: + if model_info is not None: if model_info.base_model_id: payload['model'] = model_info.base_model_id params = model_info.params.model_dump() - if params: payload = apply_model_params_to_body_openai(params, payload) - await check_model_access(user, model_info) else: await check_model_access(user, None) - url, url_idx = await get_ollama_url(request, payload['model'], url_idx) - api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( - str(url_idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support - ) - - prefix_id = api_config.get('prefix_id', None) + url, url_idx = await get_ollama_url(request, payload['model'], url_idx, user) + api_config = _resolve_api_config(request, url_idx, url) + prefix_id = api_config.get('prefix_id') if prefix_id: payload['model'] = payload['model'].replace(f'{prefix_id}.', '') @@ -1240,8 +1143,9 @@ async def generate_openai_chat_completion( request: Request, form_data: dict, url_idx: int | None = None, - user=Depends(get_verified_user), + user=Depends(get_verified_user), # noqa: B008 ): + """Forward a chat completion request via the OpenAI-compatible proxy.""" # NOTE: We intentionally do NOT use Depends(get_async_session) here. # Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions. # This prevents holding a connection during the entire LLM call (30-60+ seconds), @@ -1249,29 +1153,23 @@ async def generate_openai_chat_completion( metadata = form_data.pop('metadata', None) try: - completion_form = OpenAIChatCompletionForm(**form_data) - except Exception as e: - log.exception(e) - raise HTTPException( - status_code=400, - detail=str(e), - ) + form_data = OpenAIChatCompletionForm(**form_data) + except Exception as exc: + log.exception(exc) + raise HTTPException(status_code=400, detail=str(exc)) - payload = {**completion_form.model_dump(exclude_none=True, exclude=['metadata'])} - if 'metadata' in payload: - del payload['metadata'] + payload = {**form_data.model_dump(exclude_none=True, exclude=['metadata'])} + payload.pop('metadata', None) - model_id = completion_form.model + model_id = form_data.model model_info = await Models.get_model_by_id(model_id) - if model_info: + if model_info is not None: if model_info.base_model_id: payload['model'] = model_info.base_model_id params = model_info.params.model_dump() - if params: system = params.pop('system', None) - payload = apply_model_params_to_body_openai(params, payload) payload = await apply_system_prompt_to_body(system, payload, metadata, user) @@ -1279,13 +1177,10 @@ async def generate_openai_chat_completion( else: await check_model_access(user, None) - url, url_idx = await get_ollama_url(request, payload['model'], url_idx) - api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( - str(url_idx), - request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support - ) + url, url_idx = await get_ollama_url(request, payload['model'], url_idx, user) + api_config = _resolve_api_config(request, url_idx, url) - prefix_id = api_config.get('prefix_id', None) + prefix_id = api_config.get('prefix_id') if prefix_id: payload['model'] = payload['model'].replace(f'{prefix_id}.', '') @@ -1331,7 +1226,7 @@ async def generate_anthropic_messages( else: await check_model_access(user, None) - url, url_idx = await get_ollama_url(request, payload['model'], url_idx) + url, url_idx = await get_ollama_url(request, payload['model'], url_idx, user) api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( str(url_idx), request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support @@ -1389,7 +1284,7 @@ async def generate_responses( else: await check_model_access(user, None) - url, url_idx = await get_ollama_url(request, payload['model'], url_idx) + url, url_idx = await get_ollama_url(request, payload['model'], url_idx, user) api_config = request.app.state.config.OLLAMA_API_CONFIGS.get( str(url_idx), request.app.state.config.OLLAMA_API_CONFIGS.get(url, {}), # Legacy support @@ -1416,42 +1311,24 @@ async def get_openai_models( url_idx: int | None = None, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), -): - models = [] +) -> dict: + """List models in the OpenAI-compatible format.""" if url_idx is None: model_list = await get_all_models(request, user=user) - models = [ - { - 'id': model['model'], - 'object': 'model', - 'created': int(time.time()), - 'owned_by': 'openai', - } - for model in model_list['models'] - ] - + raw_models = model_list['models'] else: url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] model_list = await send_request(f'{url}/api/tags', 'GET') + raw_models = model_list.get('models', []) - models = [ - { - 'id': model['model'], - 'object': 'model', - 'created': int(time.time()), - 'owned_by': 'openai', - } - for model in model_list.get('models', []) - ] + now_ts = int(time.time()) + models = [{'id': m['model'], 'object': 'model', 'created': now_ts, 'owned_by': 'openai'} for m in raw_models] if user.role == 'user' and not BYPASS_MODEL_ACCESS_CONTROL: - # Filter models based on user access control - model_ids = [model['id'] for model in models] - model_infos = {model_info.id: model_info for model_info in await Models.get_models_by_ids(model_ids, db=db)} - user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, db=db)} - - # Batch-fetch accessible resource IDs in a single query instead of N has_access calls - accessible_model_ids = await AccessGrants.get_accessible_resource_ids( + model_ids = [m['id'] for m in models] + model_infos = {mi.id: mi for mi in await Models.get_models_by_ids(model_ids, db=db)} + user_group_ids = {g.id for g in await Groups.get_groups_by_member_id(user.id, db=db)} + accessible_ids = await AccessGrants.get_accessible_resource_ids( user_id=user.id, resource_type='model', resource_ids=list(model_infos.keys()), @@ -1459,98 +1336,83 @@ async def get_openai_models( user_group_ids=user_group_ids, db=db, ) + models = [ + m for m in models if (mi := model_infos.get(m['id'])) and (user.id == mi.user_id or mi.id in accessible_ids) + ] - filtered_models = [] - for model in models: - model_info = model_infos.get(model['id']) - if model_info: - if user.id == model_info.user_id or model_info.id in accessible_model_ids: - filtered_models.append(model) - models = filtered_models - - return { - 'data': models, - 'object': 'list', - } + return {'data': models, 'object': 'list'} class UrlForm(BaseModel): + """Form carrying a single URL string.""" + url: str class UploadBlobForm(BaseModel): + """Form carrying a filename for blob uploads.""" + filename: str -def parse_huggingface_url(hf_url): +def parse_huggingface_url(hf_url: str) -> str | None: + """Extract the filename from a HuggingFace download URL.""" try: - # Parse the URL - parsed_url = urlparse(hf_url) - - # Get the path and split it into components - path_components = parsed_url.path.split('/') - - # Extract the desired output - model_file = path_components[-1] - - return model_file - except ValueError: + return urlparse(hf_url).path.split('/')[-1] + except (ValueError, IndexError): return None -async def download_file_stream(ollama_url, file_url, file_path, file_name, chunk_size=1024 * 1024): - done = False - - if os.path.exists(file_path): - current_size = os.path.getsize(file_path) - else: - current_size = 0 - +async def download_file_stream( + ollama_url: str, + file_url: str, + file_path: str, + file_name: str, + chunk_size: int = 1024 * 1024, +): + """Stream a model file download from *file_url*, then push the blob to Ollama.""" + current_size = os.path.getsize(file_path) if os.path.exists(file_path) else 0 headers = {'Range': f'bytes={current_size}-'} if current_size > 0 else {} - timeout = aiohttp.ClientTimeout(total=600) # Set the timeout + session = await get_session() + async with session.get( + file_url, + headers=headers, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=aiohttp.ClientTimeout(total=600), + ) as response: + total_size = int(response.headers.get('content-length', 0)) + current_size - async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session: - async with session.get(file_url, headers=headers, ssl=AIOHTTP_CLIENT_SESSION_SSL) as response: - total_size = int(response.headers.get('content-length', 0)) + current_size + with open(file_path, 'ab+') as f: + async for data in response.content.iter_chunked(chunk_size): + current_size += len(data) + f.write(data) - with open(file_path, 'ab+') as file: - async for data in response.content.iter_chunked(chunk_size): - current_size += len(data) - file.write(data) + done = current_size == total_size + progress = round((current_size / total_size) * 100, 2) + yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n' - done = current_size == total_size - progress = round((current_size / total_size) * 100, 2) + if done: + f.close() + hashed = calculate_sha256(file_path, chunk_size) - yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n' + with open(file_path, 'rb') as blob_f: + blob_data = blob_f.read() - if done: - file.close() - hashed = calculate_sha256(file_path, chunk_size) - - with open(file_path, 'rb') as f: - blob_data = f.read() - - url = f'{ollama_url}/api/blobs/sha256:{hashed}' - blob_timeout = aiohttp.ClientTimeout(total=30) - async with aiohttp.ClientSession(timeout=blob_timeout, trust_env=True) as blob_session: - async with blob_session.post( - url, data=blob_data, ssl=AIOHTTP_CLIENT_SESSION_SSL - ) as blob_response: - if blob_response.ok: - res = { - 'done': done, - 'blob': f'sha256:{hashed}', - 'name': file_name, - } - os.remove(file_path) - - yield f'data: {json.dumps(res)}\n\n' - else: - raise RuntimeError('Ollama: Could not create blob, Please try again.') + blob_url = f'{ollama_url}/api/blobs/sha256:{hashed}' + async with session.post( + blob_url, + data=blob_data, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=aiohttp.ClientTimeout(total=30), + ) as blob_resp: + if blob_resp.ok: + os.remove(file_path) + yield f'data: {json.dumps({"done": done, "blob": f"sha256:{hashed}", "name": file_name})}\n\n' + else: + raise RuntimeError('Ollama: Could not create blob, Please try again.') -# url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf" @router.post('/models/download') @router.post('/models/download/{url_idx}') async def download_model( @@ -1559,31 +1421,26 @@ async def download_model( url_idx: int | None = None, user=Depends(get_admin_user), ): + """Download a GGUF model from HuggingFace or GitHub and register it with Ollama.""" allowed_hosts = ['https://huggingface.co/', 'https://github.com/'] - if not any(form_data.url.startswith(host) for host in allowed_hosts): raise HTTPException( status_code=400, detail='Invalid file_url. Only URLs from allowed hosts are permitted.', ) - if url_idx is None: - url_idx = 0 - url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] - + url = request.app.state.config.OLLAMA_BASE_URLS[url_idx if url_idx is not None else 0] file_name = parse_huggingface_url(form_data.url) - if file_name: - file_path = os.path.join(UPLOAD_DIR, file_name) - - return StreamingResponse( - download_file_stream(url, form_data.url, file_path, file_name), - ) - else: + if not file_name: return None + file_path = os.path.join(UPLOAD_DIR, file_name) + return StreamingResponse( + download_file_stream(url, form_data.url, file_path, file_name), + ) + -# TODO: Progress bar does not reflect size & duration of upload. @router.post('/models/upload') @router.post('/models/upload/{url_idx}') async def upload_model( @@ -1592,20 +1449,18 @@ async def upload_model( url_idx: int | None = None, user=Depends(get_admin_user), ): - if url_idx is None: - url_idx = 0 - ollama_url = request.app.state.config.OLLAMA_BASE_URLS[url_idx] + """Upload a local model file, push it as a blob, and create the model in Ollama.""" + ollama_url = request.app.state.config.OLLAMA_BASE_URLS[url_idx if url_idx is not None else 0] filename = os.path.basename(file.filename) file_path = os.path.join(UPLOAD_DIR, filename) os.makedirs(UPLOAD_DIR, exist_ok=True) - # --- P1: save file locally --- - chunk_size = 1024 * 1024 * 2 # 2 MB chunks + # Stage 1: persist the uploaded file to disk + chunk_size = 1024 * 1024 * 2 # 2 MiB with open(file_path, 'wb') as out_f: while True: chunk = file.file.read(chunk_size) - # log.info(f"Chunk: {str(chunk)}") # DEBUG if not chunk: break out_f.write(chunk) @@ -1613,74 +1468,63 @@ async def upload_model( async def file_process_stream(): nonlocal ollama_url total_size = os.path.getsize(file_path) - log.info(f'Total Model Size: {str(total_size)}') # DEBUG + log.info(f'Total Model Size: {total_size}') - # --- P2: SSE progress + calculate sha256 hash --- + # Stage 2: hash the file and emit SSE progress file_hash = calculate_sha256(file_path, chunk_size) - log.info(f'Model Hash: {str(file_hash)}') # DEBUG + log.info(f'Model Hash: {file_hash}') + try: with open(file_path, 'rb') as f: bytes_read = 0 while chunk := f.read(chunk_size): bytes_read += len(chunk) progress = round(bytes_read / total_size * 100, 2) - data_msg = { - 'progress': progress, - 'total': total_size, - 'completed': bytes_read, - } - yield f'data: {json.dumps(data_msg)}\n\n' + yield f'data: {json.dumps({"progress": progress, "total": total_size, "completed": bytes_read})}\n\n' - # --- P3: Upload to ollama /api/blobs --- + # Stage 3: push blob to Ollama with open(file_path, 'rb') as f: blob_data = f.read() - url = f'{ollama_url}/api/blobs/sha256:{file_hash}' - upload_timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT) - async with aiohttp.ClientSession(timeout=upload_timeout, trust_env=True) as upload_session: - async with upload_session.post(url, data=blob_data, ssl=AIOHTTP_CLIENT_SESSION_SSL) as response: - if not response.ok: - raise Exception('Ollama: Could not create blob, Please try again.') + session = await get_session() + blob_url = f'{ollama_url}/api/blobs/sha256:{file_hash}' + async with session.post( + blob_url, + data=blob_data, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT), + ) as resp: + if not resp.ok: + raise Exception('Ollama: Could not create blob, Please try again.') - log.info(f'Uploaded to /api/blobs') # DEBUG - # Remove local file + log.info('Uploaded to /api/blobs') os.remove(file_path) - # Create model in ollama - model_name, ext = os.path.splitext(filename) - log.info(f'Created Model: {model_name}') # DEBUG + # Stage 4: create the model + model, _ext = os.path.splitext(filename) + log.info(f'Created Model: {model}') create_payload = { - 'model': model_name, - # Reference the file by its original name => the uploaded blob's digest + 'model': model, 'files': {filename: f'sha256:{file_hash}'}, } - log.info(f'Model Payload: {create_payload}') # DEBUG + log.info(f'Model Payload: {create_payload}') - # Call ollama /api/create - # https://github.com/ollama/ollama/blob/main/docs/api.md#create-a-model - async with aiohttp.ClientSession(timeout=upload_timeout, trust_env=True) as create_session: - async with create_session.post( - f'{ollama_url}/api/create', - headers={'Content-Type': 'application/json'}, - data=json.dumps(create_payload), - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as create_resp: - if create_resp.ok: - log.info(f'API SUCCESS!') # DEBUG - done_msg = { - 'done': True, - 'blob': f'sha256:{file_hash}', - 'name': filename, - 'model_created': model_name, - } - yield f'data: {json.dumps(done_msg)}\n\n' - else: - resp_text = await create_resp.text() - raise Exception(f'Failed to create model in Ollama. {resp_text}') + async with session.post( + f'{ollama_url}/api/create', + headers={'Content-Type': 'application/json'}, + data=json.dumps(create_payload), + ssl=AIOHTTP_CLIENT_SESSION_SSL, + timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT), + ) as create_resp: + if create_resp.ok: + log.info('API SUCCESS!') + yield f'data: {json.dumps({"done": True, "blob": f"sha256:{file_hash}", "name": filename, "model_created": model})}\n\n' + else: + resp_text = await create_resp.text() + raise Exception(f'Failed to create model in Ollama. {resp_text}') - except Exception as e: - res = {'error': str(e)} - yield f'data: {json.dumps(res)}\n\n' + except Exception as exc: + yield f'data: {json.dumps({"error": str(exc)})}\n\n' return StreamingResponse(file_process_stream(), media_type='text/event-stream') diff --git a/backend/open_webui/routers/openai.py b/backend/open_webui/routers/openai.py index 900ebc6ad9..8aa8eff36e 100644 --- a/backend/open_webui/routers/openai.py +++ b/backend/open_webui/routers/openai.py @@ -595,7 +595,7 @@ async def get_models(request: Request, url_idx: int | None = None, user=Depends( try: headers, cookies = await get_headers_and_cookies(request, url, key, api_config, user=user) - if api_config.get('azure', False): + if api_config.get('azure') or api_config.get('provider') == 'azure': models = { 'data': api_config.get('model_ids', []) or [], 'object': 'list', @@ -681,15 +681,24 @@ async def verify_connection( try: headers, cookies = await get_headers_and_cookies(request, url, key, api_config, user=user) - if api_config.get('azure', False): + if api_config.get('azure') or api_config.get('provider') == 'azure': # Only set api-key header if not using Azure Entra ID authentication auth_type = api_config.get('auth_type', 'bearer') if auth_type not in ('azure_ad', 'microsoft_entra_id'): headers['api-key'] = key - api_version = api_config.get('api_version', '') or '2023-03-15-preview' + # Azure v1 format: base URL already ends with /openai/v1, + # use standard /models endpoint without api-version. + is_azure_v1 = bool(re.search(r'/openai/v1(?:/|$)', url)) + + if is_azure_v1: + verify_url = f'{url.rstrip("/")}/models' + else: + api_version = api_config.get('api_version', '') or '2023-03-15-preview' + verify_url = f'{url}/openai/models?api-version={api_version}' + async with session.get( - url=f'{url}/openai/models?api-version={api_version}', + url=verify_url, headers=headers, cookies=cookies, ssl=AIOHTTP_CLIENT_SESSION_SSL, @@ -1045,19 +1054,20 @@ async def generate_chat_completion( request: Request, form_data: dict, user=Depends(get_verified_user), - bypass_system_prompt: bool = False, ): # NOTE: We intentionally do NOT use Depends(get_async_session) here. # Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions. # This prevents holding a connection during the entire LLM call (30-60+ seconds), # which would exhaust the connection pool under concurrent load. - # bypass_filter is read from request.state to prevent external clients from - # setting it via query parameter (CVE fix). Only internal server-side callers - # (e.g. utils/chat.py) should set request.state.bypass_filter = True. + # bypass_filter and bypass_system_prompt are read from request.state to prevent + # external clients from setting them via query parameter. Only internal + # server-side callers (e.g. utils/chat.py) should set + # request.state.bypass_filter / request.state.bypass_system_prompt = True. bypass_filter = getattr(request.state, 'bypass_filter', False) if BYPASS_MODEL_ACCESS_CONTROL: bypass_filter = True + bypass_system_prompt = getattr(request.state, 'bypass_system_prompt', False) idx = 0 @@ -1151,7 +1161,7 @@ async def generate_chat_completion( is_responses = api_config.get('api_type') == 'responses' - if api_config.get('azure', False): + if api_config.get('azure') or api_config.get('provider') == 'azure': # Only set api-key header if not using Azure Entra ID authentication auth_type = api_config.get('auth_type', 'bearer') if auth_type not in ('azure_ad', 'microsoft_entra_id'): @@ -1304,11 +1314,32 @@ async def embeddings(request: Request, form_data: dict, user): streaming = False headers, cookies = await get_headers_and_cookies(request, url, key, api_config, user=user) + + if api_config.get('azure') or api_config.get('provider') == 'azure': + # Only set api-key header if not using Azure Entra ID authentication + auth_type = api_config.get('auth_type', 'bearer') + if auth_type not in ('azure_ad', 'microsoft_entra_id'): + headers['api-key'] = key + + # Azure v1 format: base URL already ends with /openai/v1, + # model stays in the payload, no deployment URL rewriting. + is_azure_v1 = bool(re.search(r'/openai/v1(?:/|$)', url)) + + if is_azure_v1: + embeddings_url = f'{url.rstrip("/")}/embeddings' + else: + api_version = api_config.get('api_version', '2023-03-15-preview') + model = _sanitize_model_for_url(form_data.get('model', '')) + embeddings_url = f'{url}/openai/deployments/{model}/embeddings?api-version={api_version}' + headers['api-version'] = api_version + else: + embeddings_url = f'{url}/embeddings' + try: session = await get_session() r = await session.request( method='POST', - url=f'{url}/embeddings', + url=embeddings_url, data=body, headers=headers, cookies=cookies, @@ -1408,7 +1439,7 @@ async def responses( try: headers, cookies = await get_headers_and_cookies(request, url, key, api_config, user=user) - if api_config.get('azure', False): + if api_config.get('azure') or api_config.get('provider') == 'azure': auth_type = api_config.get('auth_type', 'bearer') if auth_type not in ('azure_ad', 'microsoft_entra_id'): headers['api-key'] = key @@ -1519,7 +1550,7 @@ async def proxy(path: str, request: Request, user=Depends(get_verified_user)): try: headers, cookies = await get_headers_and_cookies(request, url, key, api_config, user=user) - if api_config.get('azure', False): + if api_config.get('azure') or api_config.get('provider') == 'azure': # Only set api-key header if not using Azure Entra ID authentication auth_type = api_config.get('auth_type', 'bearer') if auth_type not in ('azure_ad', 'microsoft_entra_id'): diff --git a/backend/open_webui/routers/prompts.py b/backend/open_webui/routers/prompts.py index f027dc48c6..1054288da0 100644 --- a/backend/open_webui/routers/prompts.py +++ b/backend/open_webui/routers/prompts.py @@ -188,50 +188,6 @@ async def create_new_prompt( ) -############################ -# GetPromptByCommand -############################ - - -@router.get('/command/{command}', response_model=PromptAccessResponse | None) -async def get_prompt_by_command( - command: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) -): - prompt = await Prompts.get_prompt_by_command(command, db=db) - - if prompt: - if ( - user.role == 'admin' - or prompt.user_id == user.id - or await AccessGrants.has_access( - user_id=user.id, - resource_type='prompt', - resource_id=prompt.id, - permission='read', - db=db, - ) - ): - return PromptAccessResponse( - **prompt.model_dump(), - write_access=( - (user.role == 'admin' and BYPASS_ADMIN_ACCESS_CONTROL) - or user.id == prompt.user_id - or await AccessGrants.has_access( - user_id=user.id, - resource_type='prompt', - resource_id=prompt.id, - permission='write', - db=db, - ) - ), - ) - - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=ERROR_MESSAGES.NOT_FOUND, - ) - - ############################ # GetPromptById ############################ @@ -289,6 +245,7 @@ async def update_prompt_by_id( user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): + """Update a prompt's content, creating a new history entry if changed.""" prompt = await Prompts.get_prompt_by_id(prompt_id, db=db) if not prompt: @@ -699,7 +656,7 @@ async def delete_prompt_history_entry( detail='Cannot delete the active production version', ) - success = await PromptHistories.delete_history_entry(history_id, db=db) + success = await PromptHistories.delete_history_entry(history_id, prompt.id, db=db) if not success: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, @@ -743,7 +700,7 @@ async def get_prompt_diff( detail=ERROR_MESSAGES.ACCESS_PROHIBITED, ) - diff = await PromptHistories.compute_diff(from_id, to_id, db=db) + diff = await PromptHistories.compute_diff(from_id, to_id, prompt.id, db=db) if not diff: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, diff --git a/backend/open_webui/routers/retrieval.py b/backend/open_webui/routers/retrieval.py index 9702874427..22d2dc53fa 100644 --- a/backend/open_webui/routers/retrieval.py +++ b/backend/open_webui/routers/retrieval.py @@ -10,7 +10,7 @@ import shutil import uuid from datetime import datetime from pathlib import Path -from typing import Iterator, Optional, Sequence, Union +from typing import Callable, Iterator, Optional, Sequence, Union import tiktoken from fastapi import ( @@ -107,6 +107,7 @@ from open_webui.retrieval.web.utils import get_web_loader from open_webui.retrieval.web.yacy import search_yacy from open_webui.retrieval.web.yandex import search_yandex from open_webui.retrieval.web.ydc import search_youcom +from open_webui.retrieval.web.linkup import search_linkup from open_webui.storage.provider import Storage from open_webui.utils.access_control import has_permission from open_webui.utils.access_control.files import has_access_to_file @@ -468,6 +469,7 @@ async def get_rag_config(request: Request, user=Depends(get_admin_user)): 'MINERU_API_KEY': request.app.state.config.MINERU_API_KEY, 'MINERU_API_TIMEOUT': request.app.state.config.MINERU_API_TIMEOUT, 'MINERU_PARAMS': request.app.state.config.MINERU_PARAMS, + 'MINERU_FILE_EXTENSIONS': request.app.state.config.MINERU_FILE_EXTENSIONS, # Reranking settings 'RAG_RERANKING_MODEL': request.app.state.config.RAG_RERANKING_MODEL, 'RAG_RERANKING_ENGINE': request.app.state.config.RAG_RERANKING_ENGINE, @@ -556,6 +558,8 @@ async def get_rag_config(request: Request, user=Depends(get_admin_user)): 'YANDEX_WEB_SEARCH_API_KEY': request.app.state.config.YANDEX_WEB_SEARCH_API_KEY, 'YANDEX_WEB_SEARCH_CONFIG': request.app.state.config.YANDEX_WEB_SEARCH_CONFIG, 'YOUCOM_API_KEY': request.app.state.config.YOUCOM_API_KEY, + 'LINKUP_API_KEY': request.app.state.config.LINKUP_API_KEY, + 'LINKUP_SEARCH_PARAMS': request.app.state.config.LINKUP_SEARCH_PARAMS, }, } @@ -625,6 +629,8 @@ class WebConfig(BaseModel): YANDEX_WEB_SEARCH_API_KEY: str | None = None YANDEX_WEB_SEARCH_CONFIG: str | None = None YOUCOM_API_KEY: str | None = None + LINKUP_API_KEY: str | None = None + LINKUP_SEARCH_PARAMS: dict | None = None class ConfigForm(BaseModel): @@ -681,6 +687,7 @@ class ConfigForm(BaseModel): MINERU_API_KEY: str | None = None MINERU_API_TIMEOUT: str | None = None MINERU_PARAMS: dict | None = None + MINERU_FILE_EXTENSIONS: list[str] | None = None # Reranking settings RAG_RERANKING_MODEL: str | None = None @@ -915,6 +922,11 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend request.app.state.config.MINERU_PARAMS = ( form_data.MINERU_PARAMS if form_data.MINERU_PARAMS is not None else request.app.state.config.MINERU_PARAMS ) + request.app.state.config.MINERU_FILE_EXTENSIONS = ( + form_data.MINERU_FILE_EXTENSIONS + if form_data.MINERU_FILE_EXTENSIONS is not None + else request.app.state.config.MINERU_FILE_EXTENSIONS + ) # Reranking settings if request.app.state.config.RAG_RERANKING_ENGINE == '': @@ -1125,6 +1137,8 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend request.app.state.config.YANDEX_WEB_SEARCH_API_KEY = form_data.web.YANDEX_WEB_SEARCH_API_KEY request.app.state.config.YANDEX_WEB_SEARCH_CONFIG = form_data.web.YANDEX_WEB_SEARCH_CONFIG request.app.state.config.YOUCOM_API_KEY = form_data.web.YOUCOM_API_KEY + request.app.state.config.LINKUP_API_KEY = form_data.web.LINKUP_API_KEY + request.app.state.config.LINKUP_SEARCH_PARAMS = form_data.web.LINKUP_SEARCH_PARAMS return { 'status': True, @@ -1260,6 +1274,8 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend 'YANDEX_WEB_SEARCH_API_KEY': request.app.state.config.YANDEX_WEB_SEARCH_API_KEY, 'YANDEX_WEB_SEARCH_CONFIG': request.app.state.config.YANDEX_WEB_SEARCH_CONFIG, 'YOUCOM_API_KEY': request.app.state.config.YOUCOM_API_KEY, + 'LINKUP_API_KEY': request.app.state.config.LINKUP_API_KEY, + 'LINKUP_SEARCH_PARAMS': request.app.state.config.LINKUP_SEARCH_PARAMS, }, } @@ -1294,20 +1310,43 @@ def merge_docs_to_target_size( Attempts to grow small chunks up to a desired minimum size, without exceeding the maximum size or crossing source/file boundaries. - """ - min_chunk_size_target = request.app.state.config.CHUNK_MIN_SIZE_TARGET - max_chunk_size = request.app.state.config.CHUNK_SIZE - if min_chunk_size_target <= 0: + Uses forward merging first (absorb the next chunk), then + backward merging (append into the previous emitted chunk) + for undersized chunks that can't grow forward. + """ + min_size = request.app.state.config.CHUNK_MIN_SIZE_TARGET + max_size = request.app.state.config.CHUNK_SIZE + + if min_size <= 0: return chunks - measure_chunk_size = len + measure: Callable[[str], int] = len if request.app.state.config.TEXT_SPLITTER == 'token': encoding = tiktoken.get_encoding(str(request.app.state.config.TIKTOKEN_ENCODING_NAME)) - measure_chunk_size = lambda text: len(encoding.encode(text)) + measure = lambda text: len(encoding.encode(text)) - processed_chunks: list[Document] = [] + def _merge_backward(result: list[Document], content: str, chunk: Document) -> bool: + """Try to append content into the last emitted chunk. Returns True on success.""" + if not result: + return False + prev = result[-1] + if not can_merge_chunks(prev, chunk): + return False + merged = f'{prev.page_content}\n\n{content}' + if measure(merged) > max_size: + return False + result[-1] = Document(page_content=merged, metadata={**prev.metadata}) + return True + def _emit(result: list[Document], content: str, chunk: Document) -> None: + """Emit a chunk, trying backward merge first if it's undersized.""" + is_undersized = measure(content) < min_size + if is_undersized and _merge_backward(result, content, chunk): + return + result.append(Document(page_content=content, metadata={**chunk.metadata})) + + result: list[Document] = [] current_chunk: Document | None = None current_content: str = '' @@ -1315,37 +1354,27 @@ def merge_docs_to_target_size( if current_chunk is None: current_chunk = next_chunk current_content = next_chunk.page_content - continue # First chunk initialization + continue - proposed_content = f'{current_content}\n\n{next_chunk.page_content}' - - can_merge = ( + # Forward merge: absorb next chunk into current if undersized and fits + merged_content = f'{current_content}\n\n{next_chunk.page_content}' + can_merge_forward = ( can_merge_chunks(current_chunk, next_chunk) - and measure_chunk_size(current_content) < min_chunk_size_target - and measure_chunk_size(proposed_content) <= max_chunk_size + and measure(current_content) < min_size + and measure(merged_content) <= max_size ) - if can_merge: - current_content = proposed_content + if can_merge_forward: + current_content = merged_content else: - processed_chunks.append( - Document( - page_content=current_content, - metadata={**current_chunk.metadata}, - ) - ) + _emit(result, current_content, current_chunk) current_chunk = next_chunk current_content = next_chunk.page_content if current_chunk is not None: - processed_chunks.append( - Document( - page_content=current_content, - metadata={**current_chunk.metadata}, - ) - ) + _emit(result, current_content, current_chunk) - return processed_chunks + return result def save_docs_to_vector_db( @@ -1876,32 +1905,18 @@ async def process_web( ) -def search_web(request: Request, engine: str, query: str, user=None) -> list[SearchResult]: - """Search the web using a search engine and return the results as a list of SearchResult objects. - Will look for a search engine API key in environment variables in the following order: - - SEARXNG_QUERY_URL - - YACY_QUERY_URL + YACY_USERNAME + YACY_PASSWORD - - GOOGLE_PSE_API_KEY + GOOGLE_PSE_ENGINE_ID - - BRAVE_SEARCH_API_KEY - - KAGI_SEARCH_API_KEY - - MOJEEK_SEARCH_API_KEY - - BOCHA_SEARCH_API_KEY - - SERPSTACK_API_KEY - - SERPER_API_KEY - - SERPLY_API_KEY - - TAVILY_API_KEY - - EXA_API_KEY - - PERPLEXITY_API_KEY - - SOUGOU_API_SID + SOUGOU_API_SK - - SEARCHAPI_API_KEY + SEARCHAPI_ENGINE (by default `google`) - - SERPAPI_API_KEY + SERPAPI_ENGINE (by default `google`) - Args: - query (str): The query to search for +async def search_web(request: Request, engine: str, query: str, user=None) -> list[SearchResult]: + """Dispatch a web search query to the configured engine and return results. + + Providers that have been migrated to async (aiohttp) are awaited natively. + Legacy sync providers are offloaded via ``asyncio.to_thread`` to avoid + blocking the event loop. """ # TODO: add playwright to search the web if engine == 'ollama_cloud': - return search_ollama_cloud( + return await asyncio.to_thread( + search_ollama_cloud, 'https://ollama.com', request.app.state.config.OLLAMA_CLOUD_WEB_SEARCH_API_KEY, query, @@ -1910,7 +1925,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea ) elif engine == 'perplexity_search': if request.app.state.config.PERPLEXITY_API_KEY: - return search_perplexity_search( + return await asyncio.to_thread( + search_perplexity_search, request.app.state.config.PERPLEXITY_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -1923,7 +1939,7 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea elif engine == 'searxng': if request.app.state.config.SEARXNG_QUERY_URL: searxng_kwargs = {'language': request.app.state.config.SEARXNG_LANGUAGE} - return search_searxng( + return await search_searxng( request.app.state.config.SEARXNG_QUERY_URL, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -1934,7 +1950,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No SEARXNG_QUERY_URL found in environment variables') elif engine == 'yacy': if request.app.state.config.YACY_QUERY_URL: - return search_yacy( + return await asyncio.to_thread( + search_yacy, request.app.state.config.YACY_QUERY_URL, request.app.state.config.YACY_USERNAME, request.app.state.config.YACY_PASSWORD, @@ -1946,7 +1963,7 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No YACY_QUERY_URL found in environment variables') elif engine == 'google_pse': if request.app.state.config.GOOGLE_PSE_API_KEY and request.app.state.config.GOOGLE_PSE_ENGINE_ID: - return search_google_pse( + return await search_google_pse( request.app.state.config.GOOGLE_PSE_API_KEY, request.app.state.config.GOOGLE_PSE_ENGINE_ID, query, @@ -1958,7 +1975,7 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No GOOGLE_PSE_API_KEY or GOOGLE_PSE_ENGINE_ID found in environment variables') elif engine == 'brave': if request.app.state.config.BRAVE_SEARCH_API_KEY: - return search_brave( + return await search_brave( request.app.state.config.BRAVE_SEARCH_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -1968,7 +1985,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No BRAVE_SEARCH_API_KEY found in environment variables') elif engine == 'brave_llm_context': if request.app.state.config.BRAVE_SEARCH_API_KEY: - return search_brave_llm_context( + return await asyncio.to_thread( + search_brave_llm_context, request.app.state.config.BRAVE_SEARCH_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -1979,7 +1997,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No BRAVE_SEARCH_API_KEY found in environment variables') elif engine == 'kagi': if request.app.state.config.KAGI_SEARCH_API_KEY: - return search_kagi( + return await asyncio.to_thread( + search_kagi, request.app.state.config.KAGI_SEARCH_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -1989,7 +2008,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No KAGI_SEARCH_API_KEY found in environment variables') elif engine == 'mojeek': if request.app.state.config.MOJEEK_SEARCH_API_KEY: - return search_mojeek( + return await asyncio.to_thread( + search_mojeek, request.app.state.config.MOJEEK_SEARCH_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -1999,7 +2019,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No MOJEEK_SEARCH_API_KEY found in environment variables') elif engine == 'bocha': if request.app.state.config.BOCHA_SEARCH_API_KEY: - return search_bocha( + return await asyncio.to_thread( + search_bocha, request.app.state.config.BOCHA_SEARCH_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -2009,7 +2030,7 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No BOCHA_SEARCH_API_KEY found in environment variables') elif engine == 'serpstack': if request.app.state.config.SERPSTACK_API_KEY: - return search_serpstack( + return await search_serpstack( request.app.state.config.SERPSTACK_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -2020,7 +2041,7 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No SERPSTACK_API_KEY found in environment variables') elif engine == 'serper': if request.app.state.config.SERPER_API_KEY: - return search_serper( + return await search_serper( request.app.state.config.SERPER_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -2030,7 +2051,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No SERPER_API_KEY found in environment variables') elif engine == 'serply': if request.app.state.config.SERPLY_API_KEY: - return search_serply( + return await asyncio.to_thread( + search_serply, request.app.state.config.SERPLY_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -2039,7 +2061,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea else: raise Exception('No SERPLY_API_KEY found in environment variables') elif engine == 'duckduckgo': - return search_duckduckgo( + return await asyncio.to_thread( + search_duckduckgo, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST, @@ -2048,7 +2071,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea ) elif engine == 'tavily': if request.app.state.config.TAVILY_API_KEY: - return search_tavily( + return await asyncio.to_thread( + search_tavily, request.app.state.config.TAVILY_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -2058,7 +2082,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No TAVILY_API_KEY found in environment variables') elif engine == 'exa': if request.app.state.config.EXA_API_KEY: - return search_exa( + return await asyncio.to_thread( + search_exa, request.app.state.config.EXA_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -2068,7 +2093,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No EXA_API_KEY found in environment variables') elif engine == 'searchapi': if request.app.state.config.SEARCHAPI_API_KEY: - return search_searchapi( + return await asyncio.to_thread( + search_searchapi, request.app.state.config.SEARCHAPI_API_KEY, request.app.state.config.SEARCHAPI_ENGINE, query, @@ -2079,7 +2105,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception('No SEARCHAPI_API_KEY found in environment variables') elif engine == 'serpapi': if request.app.state.config.SERPAPI_API_KEY: - return search_serpapi( + return await asyncio.to_thread( + search_serpapi, request.app.state.config.SERPAPI_API_KEY, request.app.state.config.SERPAPI_ENGINE, query, @@ -2089,14 +2116,16 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea else: raise Exception('No SERPAPI_API_KEY found in environment variables') elif engine == 'jina': - return search_jina( + return await asyncio.to_thread( + search_jina, request.app.state.config.JINA_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, request.app.state.config.JINA_API_BASE_URL, ) elif engine == 'bing': - return search_bing( + return await asyncio.to_thread( + search_bing, request.app.state.config.BING_SEARCH_V7_SUBSCRIPTION_KEY, request.app.state.config.BING_SEARCH_V7_ENDPOINT, str(DEFAULT_LOCALE), @@ -2110,7 +2139,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea and request.app.state.config.AZURE_AI_SEARCH_ENDPOINT and request.app.state.config.AZURE_AI_SEARCH_INDEX_NAME ): - return search_azure( + return await asyncio.to_thread( + search_azure, request.app.state.config.AZURE_AI_SEARCH_API_KEY, request.app.state.config.AZURE_AI_SEARCH_ENDPOINT, request.app.state.config.AZURE_AI_SEARCH_INDEX_NAME, @@ -2122,15 +2152,9 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea raise Exception( 'AZURE_AI_SEARCH_API_KEY, AZURE_AI_SEARCH_ENDPOINT, and AZURE_AI_SEARCH_INDEX_NAME are required for Azure AI Search' ) - elif engine == 'exa': - return search_exa( - request.app.state.config.EXA_API_KEY, - query, - request.app.state.config.WEB_SEARCH_RESULT_COUNT, - request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST, - ) elif engine == 'perplexity': - return search_perplexity( + return await asyncio.to_thread( + search_perplexity, request.app.state.config.PERPLEXITY_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, @@ -2140,7 +2164,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea ) elif engine == 'sougou': if request.app.state.config.SOUGOU_API_SID and request.app.state.config.SOUGOU_API_SK: - return search_sougou( + return await asyncio.to_thread( + search_sougou, request.app.state.config.SOUGOU_API_SID, request.app.state.config.SOUGOU_API_SK, query, @@ -2150,7 +2175,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea else: raise Exception('No SOUGOU_API_SID or SOUGOU_API_SK found in environment variables') elif engine == 'firecrawl': - return search_firecrawl( + return await asyncio.to_thread( + search_firecrawl, request.app.state.config.FIRECRAWL_API_BASE_URL, request.app.state.config.FIRECRAWL_API_KEY, query, @@ -2158,7 +2184,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST, ) elif engine == 'external': - return search_external( + return await asyncio.to_thread( + search_external, request, request.app.state.config.EXTERNAL_WEB_SEARCH_URL, request.app.state.config.EXTERNAL_WEB_SEARCH_API_KEY, @@ -2168,7 +2195,8 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea user=user, ) elif engine == 'yandex': - return search_yandex( + return await asyncio.to_thread( + search_yandex, request, request.app.state.config.YANDEX_WEB_SEARCH_URL, request.app.state.config.YANDEX_WEB_SEARCH_API_KEY, @@ -2179,12 +2207,25 @@ def search_web(request: Request, engine: str, query: str, user=None) -> list[Sea user=user, ) elif engine == 'youcom': - return search_youcom( + return await asyncio.to_thread( + search_youcom, request.app.state.config.YOUCOM_API_KEY, query, request.app.state.config.WEB_SEARCH_RESULT_COUNT, request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST, ) + elif engine == 'linkup': + if request.app.state.config.LINKUP_API_KEY: + return await asyncio.to_thread( + search_linkup, + api_key=request.app.state.config.LINKUP_API_KEY, + query=query, + count=request.app.state.config.WEB_SEARCH_RESULT_COUNT, + filter_list=request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST, + params=request.app.state.config.LINKUP_SEARCH_PARAMS, + ) + else: + raise Exception('No LINKUP_API_KEY found in environment variables') else: raise Exception('No search engine API key found in environment variables') @@ -2222,8 +2263,7 @@ async def process_web_search(request: Request, form_data: SearchForm, user=Depen async def search_query_with_semaphore(query): async with semaphore: - return await run_in_threadpool( - search_web, + return await search_web( request, request.app.state.config.WEB_SEARCH_ENGINE, query, @@ -2232,10 +2272,9 @@ async def process_web_search(request: Request, form_data: SearchForm, user=Depen search_tasks = [search_query_with_semaphore(query) for query in form_data.queries] else: - # Unlimited parallel execution (previous behavior) + # Unlimited parallel execution search_tasks = [ - run_in_threadpool( - search_web, + search_web( request, request.app.state.config.WEB_SEARCH_ENGINE, query, @@ -2257,12 +2296,8 @@ async def process_web_search(request: Request, form_data: SearchForm, user=Depen log.debug(f'urls: {urls}') except Exception as e: - log.exception(e) - - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=ERROR_MESSAGES.WEB_SEARCH_ERROR(e), - ) + log.exception('Web search failed') + raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.WEB_SEARCH_ERROR(e)) if len(urls) == 0: raise HTTPException( @@ -2342,11 +2377,8 @@ async def process_web_search(request: Request, form_data: SearchForm, user=Depen 'loaded_count': len(docs), } except Exception as e: - log.exception(e) - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=ERROR_MESSAGES.DEFAULT(e), - ) + log.exception('Web search content loading failed') + raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT(e)) async def _validate_collection_access(collection_names: list[str], user, access_type: str = 'read') -> None: diff --git a/backend/open_webui/routers/terminals.py b/backend/open_webui/routers/terminals.py index d2ef5f0ea3..6a942cf9b2 100644 --- a/backend/open_webui/routers/terminals.py +++ b/backend/open_webui/routers/terminals.py @@ -35,7 +35,14 @@ def _sanitize_proxy_path(path: str) -> str | None: Trailing slashes are preserved — many upstream frameworks treat ``/path`` and ``/path/`` differently. """ - decoded = unquote(path) + # Decode until stable: a single unquote pass leaves %252e%252e as %2e%2e, + # which the upstream then re-decodes into '..', bypassing the check below. + decoded = path + for _ in range(8): + once = unquote(decoded) + if once == decoded: + break + decoded = once had_trailing_slash = decoded.endswith('/') normalized = posixpath.normpath(decoded) # Remove any leading slashes that would reset the base @@ -324,11 +331,20 @@ async def ws_terminal( except Exception: pass - await asyncio.gather( - _client_to_upstream(), - _upstream_to_client(), - return_exceptions=True, - ) + # End the proxy as soon as either direction finishes (e.g. a + # graceful upstream CLOSE) and cancel the sibling, which would + # otherwise hang on a blocked ws.receive() until the browser leaves. + tasks = [ + asyncio.create_task(_client_to_upstream()), + asyncio.create_task(_upstream_to_client()), + ] + _done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + for task in pending: + task.cancel() + try: + await task + except asyncio.CancelledError: + pass except Exception as e: log.exception('Terminal WebSocket proxy error: %s', e) finally: diff --git a/backend/open_webui/routers/tools.py b/backend/open_webui/routers/tools.py index 43719ae514..963a727cde 100644 --- a/backend/open_webui/routers/tools.py +++ b/backend/open_webui/routers/tools.py @@ -329,6 +329,7 @@ async def create_new_tools( user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): + """Create a new tool from user-supplied Python source code.""" if user.role != 'admin' and not ( await has_permission(user.id, 'workspace.tools', request.app.state.config.USER_PERMISSIONS, db=db) or await has_permission( @@ -455,6 +456,7 @@ async def update_tools_by_id( user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): + """Update an existing tool's source code and metadata.""" tools = await Tools.get_tool_by_id(id, db=db) if not tools: raise HTTPException( diff --git a/backend/open_webui/routers/users.py b/backend/open_webui/routers/users.py index 3c215c8f16..0b8da713df 100644 --- a/backend/open_webui/routers/users.py +++ b/backend/open_webui/routers/users.py @@ -383,21 +383,25 @@ async def get_user_info_by_session_user(user=Depends(get_verified_user), db: Asy @router.post('/user/info/update', response_model=dict | None) -async def update_user_info_by_session_user( - form_data: dict, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +async def update_user_info_by_session_user( # PATCH-style merge + form_data: dict, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), ): - # Merges against the auth-time snapshot of user.info. The previous pre-merge - # refetch only narrowed (did not eliminate) the lost-update window on concurrent - # same-user writes; real safety needs row locking or a version column. - existing_info = user.info or {} - updated = await Users.update_user_by_id(user.id, {'info': {**existing_info, **form_data}}, db=db) - if updated: - return updated.info - else: + """Merge caller-supplied fields into the current user's info dict. + + Uses the auth-time snapshot of ``user.info`` as the merge base. This does + NOT eliminate lost-update races on concurrent same-user writes; real safety + would need row locking or an optimistic-concurrency version column. + """ + merged_info = {**(user.info or {}), **form_data} + updated = await Users.update_user_by_id(user.id, {'info': merged_info}, db=db) + if not updated: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.USER_NOT_FOUND, ) + return updated.info ############################ @@ -539,7 +543,7 @@ async def get_user_active_status_by_id( async def update_user_by_id( user_id: str, form_data: UserUpdateForm, - session_user=Depends(get_admin_user), + session_user: UserModel = Depends(get_admin_user), db: AsyncSession = Depends(get_async_session), ): # Prevent modification of the primary admin user by other admins @@ -743,27 +747,15 @@ async def get_user_preview( 'user': {'id': target_user.id, 'name': target_user.name}, 'groups': [{'id': g.id, 'name': g.name} for g in user_groups], 'models': { - 'items': [ - {'id': m.id, 'name': m.name} - for m in active_models - if m.id in accessible_model_ids - ], + 'items': [{'id': m.id, 'name': m.name} for m in active_models if m.id in accessible_model_ids], 'total': len(active_models), }, 'knowledge': { - 'items': [ - {'id': k.id, 'name': k.name} - for k in all_knowledge - if k.id in accessible_knowledge_ids - ], + 'items': [{'id': k.id, 'name': k.name} for k in all_knowledge if k.id in accessible_knowledge_ids], 'total': len(all_knowledge), }, 'tools': { - 'items': [ - {'id': t.id, 'name': t.name} - for t in all_tools - if t.id in accessible_tool_ids - ], + 'items': [{'id': t.id, 'name': t.name} for t in all_tools if t.id in accessible_tool_ids], 'total': len(all_tools), }, } diff --git a/backend/open_webui/routers/utils.py b/backend/open_webui/routers/utils.py index 92caf5fee9..4d0f679955 100644 --- a/backend/open_webui/routers/utils.py +++ b/backend/open_webui/routers/utils.py @@ -3,7 +3,6 @@ from __future__ import annotations import logging import black -import markdown from fastapi import APIRouter, Depends, HTTPException, Request, Response, status from open_webui.config import DATA_DIR, ENABLE_ADMIN_EXPORT from open_webui.constants import ERROR_MESSAGES @@ -73,15 +72,6 @@ async def execute_code(request: Request, form_data: CodeForm, user=Depends(get_v ) -class MarkdownForm(BaseModel): - md: str - - -@router.post('/markdown') -async def get_html_from_markdown(form_data: MarkdownForm, user=Depends(get_verified_user)): - return {'html': markdown.markdown(form_data.md)} - - class ChatForm(BaseModel): title: str messages: list[dict] @@ -104,20 +94,18 @@ async def download_chat_as_pdf(form_data: ChatTitleMessagesForm, user=Depends(ge @router.get('/db/download') async def download_db(user=Depends(get_admin_user)): + """Download the raw SQLite database file (admin-only, SQLite deployments only).""" if not ENABLE_ADMIN_EXPORT: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail=ERROR_MESSAGES.ACCESS_PROHIBITED, - ) + raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + + # Lazy import avoids circular dependency at module load time from open_webui.internal.db import engine if engine.name != 'sqlite': - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=ERROR_MESSAGES.DB_NOT_SQLITE, - ) + raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DB_NOT_SQLITE) + return FileResponse( - engine.url.database, + str(engine.url.database), media_type='application/octet-stream', filename='webui.db', ) diff --git a/backend/open_webui/socket/main.py b/backend/open_webui/socket/main.py index 4217124e2b..2884847a0e 100644 --- a/backend/open_webui/socket/main.py +++ b/backend/open_webui/socket/main.py @@ -40,8 +40,8 @@ from open_webui.tasks import create_task, stop_item_tasks from open_webui.utils.access_control import has_permission from open_webui.utils.auth import decode_token from open_webui.utils.redis import ( + build_sentinel_url, get_redis_connection, - get_sentinel_url_from_env, get_sentinels_from_env, ) from redis import asyncio as aioredis @@ -58,20 +58,20 @@ REDIS = None SOCKETIO_CORS_ORIGINS = '*' if CORS_ALLOW_ORIGIN == ['*'] else CORS_ALLOW_ORIGIN if WEBSOCKET_MANAGER == 'redis': - if WEBSOCKET_SENTINEL_HOSTS: - mgr = socketio.AsyncRedisManager( - get_sentinel_url_from_env(WEBSOCKET_REDIS_URL, WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT), - redis_options=WEBSOCKET_REDIS_OPTIONS, - ) - else: - mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL, redis_options=WEBSOCKET_REDIS_OPTIONS) + sentinel_hosts = WEBSOCKET_SENTINEL_HOSTS or '' + ws_redis_url = ( + build_sentinel_url(WEBSOCKET_REDIS_URL, sentinel_hosts, WEBSOCKET_SENTINEL_PORT) + if sentinel_hosts + else WEBSOCKET_REDIS_URL + ) + redis_manager = socketio.AsyncRedisManager(ws_redis_url, redis_options=WEBSOCKET_REDIS_OPTIONS) sio = socketio.AsyncServer( cors_allowed_origins=SOCKETIO_CORS_ORIGINS, async_mode='asgi', transports=(['websocket'] if ENABLE_WEBSOCKET_SUPPORT else ['polling']), allow_upgrades=ENABLE_WEBSOCKET_SUPPORT, always_connect=True, - client_manager=mgr, + client_manager=redis_manager, logger=WEBSOCKET_SERVER_LOGGING, ping_interval=WEBSOCKET_SERVER_PING_INTERVAL, ping_timeout=WEBSOCKET_SERVER_PING_TIMEOUT, @@ -99,32 +99,31 @@ SESSION_POOL_TIMEOUT = 120 # seconds without heartbeat before session is reaped if WEBSOCKET_MANAGER == 'redis': log.debug('Using Redis to manage websockets.') + ws_sentinels = get_sentinels_from_env(WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT) REDIS = get_redis_connection( redis_url=WEBSOCKET_REDIS_URL, - redis_sentinels=get_sentinels_from_env(WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT), + redis_sentinels=ws_sentinels, redis_cluster=WEBSOCKET_REDIS_CLUSTER, async_mode=True, ) - redis_sentinels = get_sentinels_from_env(WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT) - MODELS = RedisDict( f'{REDIS_KEY_PREFIX}:models', redis_url=WEBSOCKET_REDIS_URL, - redis_sentinels=redis_sentinels, + redis_sentinels=ws_sentinels, redis_cluster=WEBSOCKET_REDIS_CLUSTER, ) SESSION_POOL = RedisDict( f'{REDIS_KEY_PREFIX}:session_pool', redis_url=WEBSOCKET_REDIS_URL, - redis_sentinels=redis_sentinels, + redis_sentinels=ws_sentinels, redis_cluster=WEBSOCKET_REDIS_CLUSTER, ) USAGE_POOL = RedisDict( f'{REDIS_KEY_PREFIX}:usage_pool', redis_url=WEBSOCKET_REDIS_URL, - redis_sentinels=redis_sentinels, + redis_sentinels=ws_sentinels, redis_cluster=WEBSOCKET_REDIS_CLUSTER, ) @@ -132,7 +131,7 @@ if WEBSOCKET_MANAGER == 'redis': redis_url=WEBSOCKET_REDIS_URL, lock_name=f'{REDIS_KEY_PREFIX}:usage_cleanup_lock', timeout_secs=WEBSOCKET_REDIS_LOCK_TIMEOUT, - redis_sentinels=redis_sentinels, + redis_sentinels=ws_sentinels, redis_cluster=WEBSOCKET_REDIS_CLUSTER, ) aquire_func = clean_up_lock.aquire_lock @@ -143,7 +142,7 @@ if WEBSOCKET_MANAGER == 'redis': redis_url=WEBSOCKET_REDIS_URL, lock_name=f'{REDIS_KEY_PREFIX}:session_cleanup_lock', timeout_secs=WEBSOCKET_REDIS_LOCK_TIMEOUT, - redis_sentinels=redis_sentinels, + redis_sentinels=ws_sentinels, redis_cluster=WEBSOCKET_REDIS_CLUSTER, ) session_aquire_func = session_cleanup_lock.aquire_lock @@ -806,7 +805,7 @@ async def yjs_awareness_update(sid, data): @sio.event -async def disconnect(sid): +async def disconnect(sid, reason=None): if sid in SESSION_POOL: user = SESSION_POOL[sid] del SESSION_POOL[sid] diff --git a/backend/open_webui/socket/utils.py b/backend/open_webui/socket/utils.py index 0cf2a09246..b337b08f40 100644 --- a/backend/open_webui/socket/utils.py +++ b/backend/open_webui/socket/utils.py @@ -1,13 +1,21 @@ +"""Redis-backed distributed data structures for WebSocket state management.""" + +from __future__ import annotations + +import hashlib import json import uuid -from typing import List, Optional, Tuple import pycrdt as Y -from open_webui.env import REDIS_KEY_PREFIX from open_webui.utils.redis import get_redis_connection +from open_webui.env import REDIS_KEY_PREFIX + +YDOC_KEY_PREFIX = f'{REDIS_KEY_PREFIX}:ydoc:documents' class RedisLock: + """Distributed lock backed by a Redis SET with NX/EX semantics.""" + def __init__( self, redis_url, @@ -45,6 +53,10 @@ class RedisLock: class RedisDict: def __init__(self, name, redis_url, redis_sentinels=[], redis_cluster=False): self.name = name + # Per-process cache of the last payload fingerprint written by set(). + # Used to skip redundant HSET round-trips when the model list hasn't + # changed — the dominant Redis write source on busy multi-pod setups. + self._last_signature: str | None = None self.redis = get_redis_connection( redis_url, redis_sentinels, @@ -85,6 +97,18 @@ class RedisDict: def set(self, mapping: dict): if not mapping: self.redis.delete(self.name) + self._last_signature = None + return + + # Serialize values once — reused for both the fingerprint and the write. + serialized = {k: json.dumps(v) for k, v in mapping.items()} + + # Skip the write when the prepared mapping is identical to the last one + # this process wrote. The check is per-instance (not distributed), but + # still eliminates the majority of redundant writes because each pod + # typically produces the same model list on consecutive refreshes. + signature = hashlib.sha256(json.dumps(serialized, sort_keys=True).encode()).hexdigest() + if signature == self._last_signature: return # Fetch existing keys before writing so we know which ones to remove. @@ -96,10 +120,12 @@ class RedisDict: # HSET first (add/update all new values), then HDEL (remove stale keys). # We never DELETE the whole hash — this eliminates the race window # where concurrent readers would see an empty models dict. - self.redis.hset(self.name, mapping={k: json.dumps(v) for k, v in mapping.items()}) + self.redis.hset(self.name, mapping=serialized) if keys_to_remove: self.redis.hdel(self.name, *keys_to_remove) + self._last_signature = signature + def get(self, key, default=None): try: return self[key] @@ -108,6 +134,7 @@ class RedisDict: def clear(self): self.redis.delete(self.name) + self._last_signature = None def update(self, other=None, **kwargs): if other is not None: @@ -128,7 +155,7 @@ class YdocManager: def __init__( self, redis=None, - redis_key_prefix: str = f'{REDIS_KEY_PREFIX}:ydoc:documents', + redis_key_prefix: str = YDOC_KEY_PREFIX, ): self._updates = {} self._users = {} @@ -177,7 +204,7 @@ class YdocManager: ydoc.apply_update(bytes(update)) self._updates[document_id] = [ydoc.get_update()] + updates[mid:] - async def get_updates(self, document_id: str) -> List[bytes]: + async def get_updates(self, document_id: str) -> list[bytes]: document_id = document_id.replace(':', '_') if self._redis: @@ -196,7 +223,7 @@ class YdocManager: else: return document_id in self._updates - async def get_users(self, document_id: str) -> List[str]: + async def get_users(self, document_id: str) -> list[str]: document_id = document_id.replace(':', '_') if self._redis: @@ -212,6 +239,11 @@ class YdocManager: if self._redis: redis_key = f'{self._redis_key_prefix}:{document_id}:users' await self._redis.sadd(redis_key, user_id) + # Maintain a per-session reverse index so disconnect cleanup + # can look up only the documents this session joined, instead + # of issuing a cluster-wide SCAN over the entire keyspace. + session_key = f'{self._redis_key_prefix}:session:{user_id}:documents' + await self._redis.sadd(session_key, document_id) else: if document_id not in self._users: self._users[document_id] = set() @@ -223,22 +255,31 @@ class YdocManager: if self._redis: redis_key = f'{self._redis_key_prefix}:{document_id}:users' await self._redis.srem(redis_key, user_id) + # Keep the reverse index in sync. + session_key = f'{self._redis_key_prefix}:session:{user_id}:documents' + await self._redis.srem(session_key, document_id) else: if document_id in self._users and user_id in self._users[document_id]: self._users[document_id].remove(user_id) async def remove_user_from_all_documents(self, user_id: str): if self._redis: - keys = [] - async for key in self._redis.scan_iter(match=f'{self._redis_key_prefix}:*', count=100): - keys.append(key) - for key in keys: - if key.endswith(':users'): - await self._redis.srem(key, user_id) + # Use the per-session reverse index instead of a cluster-wide + # SCAN. This set contains only the document IDs that this + # session actually joined, so the cost is proportional to + # the session's footprint — not the total number of documents. + session_key = f'{self._redis_key_prefix}:session:{user_id}:documents' + document_ids = await self._redis.smembers(session_key) - document_id = key.split(':')[-2] - if len(await self.get_users(document_id)) == 0: - await self.clear_document(document_id) + for document_id in document_ids: + users_key = f'{self._redis_key_prefix}:{document_id}:users' + await self._redis.srem(users_key, user_id) + + if len(await self.get_users(document_id)) == 0: + await self.clear_document(document_id) + + # Clean up the reverse index itself. + await self._redis.delete(session_key) else: for document_id in list(self._users.keys()): diff --git a/backend/open_webui/static/swagger-ui/swagger-ui-bundle.js b/backend/open_webui/static/swagger-ui/swagger-ui-bundle.js index 5ea59d21ef..c18e0dab76 100644 --- a/backend/open_webui/static/swagger-ui/swagger-ui-bundle.js +++ b/backend/open_webui/static/swagger-ui/swagger-ui-bundle.js @@ -1,2 +1,76448 @@ /*! For license information please see swagger-ui-bundle.js.LICENSE.txt */ -!function webpackUniversalModuleDefinition(s,o){"object"==typeof exports&&"object"==typeof module?module.exports=o():"function"==typeof define&&define.amd?define([],o):"object"==typeof exports?exports.SwaggerUIBundle=o():s.SwaggerUIBundle=o()}(this,(()=>(()=>{var s={67526(s,o){"use strict";o.byteLength=function byteLength(s){var o=getLens(s),i=o[0],a=o[1];return 3*(i+a)/4-a},o.toByteArray=function toByteArray(s){var o,i,_=getLens(s),w=_[0],x=_[1],C=new u(function _byteLength(s,o,i){return 3*(o+i)/4-i}(0,w,x)),j=0,L=x>0?w-4:w;for(i=0;i>16&255,C[j++]=o>>8&255,C[j++]=255&o;2===x&&(o=a[s.charCodeAt(i)]<<2|a[s.charCodeAt(i+1)]>>4,C[j++]=255&o);1===x&&(o=a[s.charCodeAt(i)]<<10|a[s.charCodeAt(i+1)]<<4|a[s.charCodeAt(i+2)]>>2,C[j++]=o>>8&255,C[j++]=255&o);return C},o.fromByteArray=function fromByteArray(s){for(var o,a=s.length,u=a%3,_=[],w=16383,x=0,C=a-u;xC?C:x+w));1===u?(o=s[a-1],_.push(i[o>>2]+i[o<<4&63]+"==")):2===u&&(o=(s[a-2]<<8)+s[a-1],_.push(i[o>>10]+i[o>>4&63]+i[o<<2&63]+"="));return _.join("")};for(var i=[],a=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",w=0;w<64;++w)i[w]=_[w],a[_.charCodeAt(w)]=w;function getLens(s){var o=s.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=s.indexOf("=");return-1===i&&(i=o),[i,i===o?0:4-i%4]}function encodeChunk(s,o,a){for(var u,_,w=[],x=o;x>18&63]+i[_>>12&63]+i[_>>6&63]+i[63&_]);return w.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},48287(s,o,i){"use strict";const a=i(67526),u=i(251),_="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;o.Buffer=Buffer,o.SlowBuffer=function SlowBuffer(s){+s!=s&&(s=0);return Buffer.alloc(+s)},o.INSPECT_MAX_BYTES=50;const w=2147483647;function createBuffer(s){if(s>w)throw new RangeError('The value "'+s+'" is invalid for option "size"');const o=new Uint8Array(s);return Object.setPrototypeOf(o,Buffer.prototype),o}function Buffer(s,o,i){if("number"==typeof s){if("string"==typeof o)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(s)}return from(s,o,i)}function from(s,o,i){if("string"==typeof s)return function fromString(s,o){"string"==typeof o&&""!==o||(o="utf8");if(!Buffer.isEncoding(o))throw new TypeError("Unknown encoding: "+o);const i=0|byteLength(s,o);let a=createBuffer(i);const u=a.write(s,o);u!==i&&(a=a.slice(0,u));return a}(s,o);if(ArrayBuffer.isView(s))return function fromArrayView(s){if(isInstance(s,Uint8Array)){const o=new Uint8Array(s);return fromArrayBuffer(o.buffer,o.byteOffset,o.byteLength)}return fromArrayLike(s)}(s);if(null==s)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(isInstance(s,ArrayBuffer)||s&&isInstance(s.buffer,ArrayBuffer))return fromArrayBuffer(s,o,i);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(s,SharedArrayBuffer)||s&&isInstance(s.buffer,SharedArrayBuffer)))return fromArrayBuffer(s,o,i);if("number"==typeof s)throw new TypeError('The "value" argument must not be of type number. Received type number');const a=s.valueOf&&s.valueOf();if(null!=a&&a!==s)return Buffer.from(a,o,i);const u=function fromObject(s){if(Buffer.isBuffer(s)){const o=0|checked(s.length),i=createBuffer(o);return 0===i.length||s.copy(i,0,0,o),i}if(void 0!==s.length)return"number"!=typeof s.length||numberIsNaN(s.length)?createBuffer(0):fromArrayLike(s);if("Buffer"===s.type&&Array.isArray(s.data))return fromArrayLike(s.data)}(s);if(u)return u;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof s[Symbol.toPrimitive])return Buffer.from(s[Symbol.toPrimitive]("string"),o,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}function assertSize(s){if("number"!=typeof s)throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function allocUnsafe(s){return assertSize(s),createBuffer(s<0?0:0|checked(s))}function fromArrayLike(s){const o=s.length<0?0:0|checked(s.length),i=createBuffer(o);for(let a=0;a=w)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+w.toString(16)+" bytes");return 0|s}function byteLength(s,o){if(Buffer.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||isInstance(s,ArrayBuffer))return s.byteLength;if("string"!=typeof s)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);const i=s.length,a=arguments.length>2&&!0===arguments[2];if(!a&&0===i)return 0;let u=!1;for(;;)switch(o){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return utf8ToBytes(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return base64ToBytes(s).length;default:if(u)return a?-1:utf8ToBytes(s).length;o=(""+o).toLowerCase(),u=!0}}function slowToString(s,o,i){let a=!1;if((void 0===o||o<0)&&(o=0),o>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(o>>>=0))return"";for(s||(s="utf8");;)switch(s){case"hex":return hexSlice(this,o,i);case"utf8":case"utf-8":return utf8Slice(this,o,i);case"ascii":return asciiSlice(this,o,i);case"latin1":case"binary":return latin1Slice(this,o,i);case"base64":return base64Slice(this,o,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,o,i);default:if(a)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),a=!0}}function swap(s,o,i){const a=s[o];s[o]=s[i],s[i]=a}function bidirectionalIndexOf(s,o,i,a,u){if(0===s.length)return-1;if("string"==typeof i?(a=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),numberIsNaN(i=+i)&&(i=u?0:s.length-1),i<0&&(i=s.length+i),i>=s.length){if(u)return-1;i=s.length-1}else if(i<0){if(!u)return-1;i=0}if("string"==typeof o&&(o=Buffer.from(o,a)),Buffer.isBuffer(o))return 0===o.length?-1:arrayIndexOf(s,o,i,a,u);if("number"==typeof o)return o&=255,"function"==typeof Uint8Array.prototype.indexOf?u?Uint8Array.prototype.indexOf.call(s,o,i):Uint8Array.prototype.lastIndexOf.call(s,o,i):arrayIndexOf(s,[o],i,a,u);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(s,o,i,a,u){let _,w=1,x=s.length,C=o.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(s.length<2||o.length<2)return-1;w=2,x/=2,C/=2,i/=2}function read(s,o){return 1===w?s[o]:s.readUInt16BE(o*w)}if(u){let a=-1;for(_=i;_x&&(i=x-C),_=i;_>=0;_--){let i=!0;for(let a=0;au&&(a=u):a=u;const _=o.length;let w;for(a>_/2&&(a=_/2),w=0;w>8,u=i%256,_.push(u),_.push(a);return _}(o,s.length-i),s,i,a)}function base64Slice(s,o,i){return 0===o&&i===s.length?a.fromByteArray(s):a.fromByteArray(s.slice(o,i))}function utf8Slice(s,o,i){i=Math.min(s.length,i);const a=[];let u=o;for(;u239?4:o>223?3:o>191?2:1;if(u+w<=i){let i,a,x,C;switch(w){case 1:o<128&&(_=o);break;case 2:i=s[u+1],128==(192&i)&&(C=(31&o)<<6|63&i,C>127&&(_=C));break;case 3:i=s[u+1],a=s[u+2],128==(192&i)&&128==(192&a)&&(C=(15&o)<<12|(63&i)<<6|63&a,C>2047&&(C<55296||C>57343)&&(_=C));break;case 4:i=s[u+1],a=s[u+2],x=s[u+3],128==(192&i)&&128==(192&a)&&128==(192&x)&&(C=(15&o)<<18|(63&i)<<12|(63&a)<<6|63&x,C>65535&&C<1114112&&(_=C))}}null===_?(_=65533,w=1):_>65535&&(_-=65536,a.push(_>>>10&1023|55296),_=56320|1023&_),a.push(_),u+=w}return function decodeCodePointsArray(s){const o=s.length;if(o<=x)return String.fromCharCode.apply(String,s);let i="",a=0;for(;aa.length?(Buffer.isBuffer(o)||(o=Buffer.from(o)),o.copy(a,u)):Uint8Array.prototype.set.call(a,o,u);else{if(!Buffer.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(a,u)}u+=o.length}return a},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function swap16(){const s=this.length;if(s%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let o=0;oi&&(s+=" ... "),""},_&&(Buffer.prototype[_]=Buffer.prototype.inspect),Buffer.prototype.compare=function compare(s,o,i,a,u){if(isInstance(s,Uint8Array)&&(s=Buffer.from(s,s.offset,s.byteLength)),!Buffer.isBuffer(s))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof s);if(void 0===o&&(o=0),void 0===i&&(i=s?s.length:0),void 0===a&&(a=0),void 0===u&&(u=this.length),o<0||i>s.length||a<0||u>this.length)throw new RangeError("out of range index");if(a>=u&&o>=i)return 0;if(a>=u)return-1;if(o>=i)return 1;if(this===s)return 0;let _=(u>>>=0)-(a>>>=0),w=(i>>>=0)-(o>>>=0);const x=Math.min(_,w),C=this.slice(a,u),j=s.slice(o,i);for(let s=0;s>>=0,isFinite(i)?(i>>>=0,void 0===a&&(a="utf8")):(a=i,i=void 0)}const u=this.length-o;if((void 0===i||i>u)&&(i=u),s.length>0&&(i<0||o<0)||o>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");let _=!1;for(;;)switch(a){case"hex":return hexWrite(this,s,o,i);case"utf8":case"utf-8":return utf8Write(this,s,o,i);case"ascii":case"latin1":case"binary":return asciiWrite(this,s,o,i);case"base64":return base64Write(this,s,o,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,s,o,i);default:if(_)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),_=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function asciiSlice(s,o,i){let a="";i=Math.min(s.length,i);for(let u=o;ua)&&(i=a);let u="";for(let a=o;ai)throw new RangeError("Trying to access beyond buffer length")}function checkInt(s,o,i,a,u,_){if(!Buffer.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(o>u||o<_)throw new RangeError('"value" argument is out of bounds');if(i+a>s.length)throw new RangeError("Index out of range")}function wrtBigUInt64LE(s,o,i,a,u){checkIntBI(o,a,u,s,i,7);let _=Number(o&BigInt(4294967295));s[i++]=_,_>>=8,s[i++]=_,_>>=8,s[i++]=_,_>>=8,s[i++]=_;let w=Number(o>>BigInt(32)&BigInt(4294967295));return s[i++]=w,w>>=8,s[i++]=w,w>>=8,s[i++]=w,w>>=8,s[i++]=w,i}function wrtBigUInt64BE(s,o,i,a,u){checkIntBI(o,a,u,s,i,7);let _=Number(o&BigInt(4294967295));s[i+7]=_,_>>=8,s[i+6]=_,_>>=8,s[i+5]=_,_>>=8,s[i+4]=_;let w=Number(o>>BigInt(32)&BigInt(4294967295));return s[i+3]=w,w>>=8,s[i+2]=w,w>>=8,s[i+1]=w,w>>=8,s[i]=w,i+8}function checkIEEE754(s,o,i,a,u,_){if(i+a>s.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function writeFloat(s,o,i,a,_){return o=+o,i>>>=0,_||checkIEEE754(s,0,i,4),u.write(s,o,i,a,23,4),i+4}function writeDouble(s,o,i,a,_){return o=+o,i>>>=0,_||checkIEEE754(s,0,i,8),u.write(s,o,i,a,52,8),i+8}Buffer.prototype.slice=function slice(s,o){const i=this.length;(s=~~s)<0?(s+=i)<0&&(s=0):s>i&&(s=i),(o=void 0===o?i:~~o)<0?(o+=i)<0&&(o=0):o>i&&(o=i),o>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s],u=1,_=0;for(;++_>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s+--o],u=1;for(;o>0&&(u*=256);)a+=this[s+--o]*u;return a},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(s,o){return s>>>=0,o||checkOffset(s,1,this.length),this[s]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(s,o){return s>>>=0,o||checkOffset(s,2,this.length),this[s]|this[s+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(s,o){return s>>>=0,o||checkOffset(s,2,this.length),this[s]<<8|this[s+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),(this[s]|this[s+1]<<8|this[s+2]<<16)+16777216*this[s+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),16777216*this[s]+(this[s+1]<<16|this[s+2]<<8|this[s+3])},Buffer.prototype.readBigUInt64LE=defineBigIntMethod((function readBigUInt64LE(s){validateNumber(s>>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=o+256*this[++s]+65536*this[++s]+this[++s]*2**24,u=this[++s]+256*this[++s]+65536*this[++s]+i*2**24;return BigInt(a)+(BigInt(u)<>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=o*2**24+65536*this[++s]+256*this[++s]+this[++s],u=this[++s]*2**24+65536*this[++s]+256*this[++s]+i;return(BigInt(a)<>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s],u=1,_=0;for(;++_=u&&(a-=Math.pow(2,8*o)),a},Buffer.prototype.readIntBE=function readIntBE(s,o,i){s>>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=o,u=1,_=this[s+--a];for(;a>0&&(u*=256);)_+=this[s+--a]*u;return u*=128,_>=u&&(_-=Math.pow(2,8*o)),_},Buffer.prototype.readInt8=function readInt8(s,o){return s>>>=0,o||checkOffset(s,1,this.length),128&this[s]?-1*(255-this[s]+1):this[s]},Buffer.prototype.readInt16LE=function readInt16LE(s,o){s>>>=0,o||checkOffset(s,2,this.length);const i=this[s]|this[s+1]<<8;return 32768&i?4294901760|i:i},Buffer.prototype.readInt16BE=function readInt16BE(s,o){s>>>=0,o||checkOffset(s,2,this.length);const i=this[s+1]|this[s]<<8;return 32768&i?4294901760|i:i},Buffer.prototype.readInt32LE=function readInt32LE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),this[s]|this[s+1]<<8|this[s+2]<<16|this[s+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),this[s]<<24|this[s+1]<<16|this[s+2]<<8|this[s+3]},Buffer.prototype.readBigInt64LE=defineBigIntMethod((function readBigInt64LE(s){validateNumber(s>>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=this[s+4]+256*this[s+5]+65536*this[s+6]+(i<<24);return(BigInt(a)<>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=(o<<24)+65536*this[++s]+256*this[++s]+this[++s];return(BigInt(a)<>>=0,o||checkOffset(s,4,this.length),u.read(this,s,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),u.read(this,s,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(s,o){return s>>>=0,o||checkOffset(s,8,this.length),u.read(this,s,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(s,o){return s>>>=0,o||checkOffset(s,8,this.length),u.read(this,s,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(s,o,i,a){if(s=+s,o>>>=0,i>>>=0,!a){checkInt(this,s,o,i,Math.pow(2,8*i)-1,0)}let u=1,_=0;for(this[o]=255&s;++_>>=0,i>>>=0,!a){checkInt(this,s,o,i,Math.pow(2,8*i)-1,0)}let u=i-1,_=1;for(this[o+u]=255&s;--u>=0&&(_*=256);)this[o+u]=s/_&255;return o+i},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,1,255,0),this[o]=255&s,o+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,65535,0),this[o]=255&s,this[o+1]=s>>>8,o+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,65535,0),this[o]=s>>>8,this[o+1]=255&s,o+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,4294967295,0),this[o+3]=s>>>24,this[o+2]=s>>>16,this[o+1]=s>>>8,this[o]=255&s,o+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,4294967295,0),this[o]=s>>>24,this[o+1]=s>>>16,this[o+2]=s>>>8,this[o+3]=255&s,o+4},Buffer.prototype.writeBigUInt64LE=defineBigIntMethod((function writeBigUInt64LE(s,o=0){return wrtBigUInt64LE(this,s,o,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeBigUInt64BE=defineBigIntMethod((function writeBigUInt64BE(s,o=0){return wrtBigUInt64BE(this,s,o,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeIntLE=function writeIntLE(s,o,i,a){if(s=+s,o>>>=0,!a){const a=Math.pow(2,8*i-1);checkInt(this,s,o,i,a-1,-a)}let u=0,_=1,w=0;for(this[o]=255&s;++u>>=0,!a){const a=Math.pow(2,8*i-1);checkInt(this,s,o,i,a-1,-a)}let u=i-1,_=1,w=0;for(this[o+u]=255&s;--u>=0&&(_*=256);)s<0&&0===w&&0!==this[o+u+1]&&(w=1),this[o+u]=(s/_|0)-w&255;return o+i},Buffer.prototype.writeInt8=function writeInt8(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,1,127,-128),s<0&&(s=255+s+1),this[o]=255&s,o+1},Buffer.prototype.writeInt16LE=function writeInt16LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,32767,-32768),this[o]=255&s,this[o+1]=s>>>8,o+2},Buffer.prototype.writeInt16BE=function writeInt16BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,32767,-32768),this[o]=s>>>8,this[o+1]=255&s,o+2},Buffer.prototype.writeInt32LE=function writeInt32LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,2147483647,-2147483648),this[o]=255&s,this[o+1]=s>>>8,this[o+2]=s>>>16,this[o+3]=s>>>24,o+4},Buffer.prototype.writeInt32BE=function writeInt32BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,2147483647,-2147483648),s<0&&(s=4294967295+s+1),this[o]=s>>>24,this[o+1]=s>>>16,this[o+2]=s>>>8,this[o+3]=255&s,o+4},Buffer.prototype.writeBigInt64LE=defineBigIntMethod((function writeBigInt64LE(s,o=0){return wrtBigUInt64LE(this,s,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeBigInt64BE=defineBigIntMethod((function writeBigInt64BE(s,o=0){return wrtBigUInt64BE(this,s,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeFloatLE=function writeFloatLE(s,o,i){return writeFloat(this,s,o,!0,i)},Buffer.prototype.writeFloatBE=function writeFloatBE(s,o,i){return writeFloat(this,s,o,!1,i)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(s,o,i){return writeDouble(this,s,o,!0,i)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(s,o,i){return writeDouble(this,s,o,!1,i)},Buffer.prototype.copy=function copy(s,o,i,a){if(!Buffer.isBuffer(s))throw new TypeError("argument should be a Buffer");if(i||(i=0),a||0===a||(a=this.length),o>=s.length&&(o=s.length),o||(o=0),a>0&&a=this.length)throw new RangeError("Index out of range");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),s.length-o>>=0,i=void 0===i?this.length:i>>>0,s||(s=0),"number"==typeof s)for(u=o;u=a+4;i-=3)o=`_${s.slice(i-3,i)}${o}`;return`${s.slice(0,i)}${o}`}function checkIntBI(s,o,i,a,u,_){if(s>i||s3?0===o||o===BigInt(0)?`>= 0${a} and < 2${a} ** ${8*(_+1)}${a}`:`>= -(2${a} ** ${8*(_+1)-1}${a}) and < 2 ** ${8*(_+1)-1}${a}`:`>= ${o}${a} and <= ${i}${a}`,new C.ERR_OUT_OF_RANGE("value",u,s)}!function checkBounds(s,o,i){validateNumber(o,"offset"),void 0!==s[o]&&void 0!==s[o+i]||boundsError(o,s.length-(i+1))}(a,u,_)}function validateNumber(s,o){if("number"!=typeof s)throw new C.ERR_INVALID_ARG_TYPE(o,"number",s)}function boundsError(s,o,i){if(Math.floor(s)!==s)throw validateNumber(s,i),new C.ERR_OUT_OF_RANGE(i||"offset","an integer",s);if(o<0)throw new C.ERR_BUFFER_OUT_OF_BOUNDS;throw new C.ERR_OUT_OF_RANGE(i||"offset",`>= ${i?1:0} and <= ${o}`,s)}E("ERR_BUFFER_OUT_OF_BOUNDS",(function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),E("ERR_INVALID_ARG_TYPE",(function(s,o){return`The "${s}" argument must be of type number. Received type ${typeof o}`}),TypeError),E("ERR_OUT_OF_RANGE",(function(s,o,i){let a=`The value of "${s}" is out of range.`,u=i;return Number.isInteger(i)&&Math.abs(i)>2**32?u=addNumericalSeparator(String(i)):"bigint"==typeof i&&(u=String(i),(i>BigInt(2)**BigInt(32)||i<-(BigInt(2)**BigInt(32)))&&(u=addNumericalSeparator(u)),u+="n"),a+=` It must be ${o}. Received ${u}`,a}),RangeError);const j=/[^+/0-9A-Za-z-_]/g;function utf8ToBytes(s,o){let i;o=o||1/0;const a=s.length;let u=null;const _=[];for(let w=0;w55295&&i<57344){if(!u){if(i>56319){(o-=3)>-1&&_.push(239,191,189);continue}if(w+1===a){(o-=3)>-1&&_.push(239,191,189);continue}u=i;continue}if(i<56320){(o-=3)>-1&&_.push(239,191,189),u=i;continue}i=65536+(u-55296<<10|i-56320)}else u&&(o-=3)>-1&&_.push(239,191,189);if(u=null,i<128){if((o-=1)<0)break;_.push(i)}else if(i<2048){if((o-=2)<0)break;_.push(i>>6|192,63&i|128)}else if(i<65536){if((o-=3)<0)break;_.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((o-=4)<0)break;_.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return _}function base64ToBytes(s){return a.toByteArray(function base64clean(s){if((s=(s=s.split("=")[0]).trim().replace(j,"")).length<2)return"";for(;s.length%4!=0;)s+="=";return s}(s))}function blitBuffer(s,o,i,a){let u;for(u=0;u=o.length||u>=s.length);++u)o[u+i]=s[u];return u}function isInstance(s,o){return s instanceof o||null!=s&&null!=s.constructor&&null!=s.constructor.name&&s.constructor.name===o.name}function numberIsNaN(s){return s!=s}const L=function(){const s="0123456789abcdef",o=new Array(256);for(let i=0;i<16;++i){const a=16*i;for(let u=0;u<16;++u)o[a+u]=s[i]+s[u]}return o}();function defineBigIntMethod(s){return"undefined"==typeof BigInt?BufferBigIntNotDefined:s}function BufferBigIntNotDefined(){throw new Error("BigInt not supported")}},13144(s,o,i){"use strict";var a=i(66743),u=i(11002),_=i(10076),w=i(47119);s.exports=w||a.call(_,u)},12205(s,o,i){"use strict";var a=i(66743),u=i(11002),_=i(13144);s.exports=function applyBind(){return _(a,u,arguments)}},11002(s){"use strict";s.exports=Function.prototype.apply},10076(s){"use strict";s.exports=Function.prototype.call},73126(s,o,i){"use strict";var a=i(66743),u=i(69675),_=i(10076),w=i(13144);s.exports=function callBindBasic(s){if(s.length<1||"function"!=typeof s[0])throw new u("a function is required");return w(a,_,s)}},47119(s){"use strict";s.exports="undefined"!=typeof Reflect&&Reflect&&Reflect.apply},10487(s,o,i){"use strict";var a=i(96897),u=i(30655),_=i(73126),w=i(12205);s.exports=function callBind(s){var o=_(arguments),i=s.length-(arguments.length-1);return a(o,1+(i>0?i:0),!0)},u?u(s.exports,"apply",{value:w}):s.exports.apply=w},36556(s,o,i){"use strict";var a=i(70453),u=i(73126),_=u([a("%String.prototype.indexOf%")]);s.exports=function callBoundIntrinsic(s,o){var i=a(s,!!o);return"function"==typeof i&&_(s,".prototype.")>-1?u([i]):i}},17965(s,o,i){"use strict";var a=i(16426),u={"text/plain":"Text","text/html":"Url",default:"Text"};s.exports=function copy(s,o){var i,_,w,x,C,j,L=!1;o||(o={}),i=o.debug||!1;try{if(w=a(),x=document.createRange(),C=document.getSelection(),(j=document.createElement("span")).textContent=s,j.ariaHidden="true",j.style.all="unset",j.style.position="fixed",j.style.top=0,j.style.clip="rect(0, 0, 0, 0)",j.style.whiteSpace="pre",j.style.webkitUserSelect="text",j.style.MozUserSelect="text",j.style.msUserSelect="text",j.style.userSelect="text",j.addEventListener("copy",(function(a){if(a.stopPropagation(),o.format)if(a.preventDefault(),void 0===a.clipboardData){i&&console.warn("unable to use e.clipboardData"),i&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var _=u[o.format]||u.default;window.clipboardData.setData(_,s)}else a.clipboardData.clearData(),a.clipboardData.setData(o.format,s);o.onCopy&&(a.preventDefault(),o.onCopy(a.clipboardData))})),document.body.appendChild(j),x.selectNodeContents(j),C.addRange(x),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");L=!0}catch(a){i&&console.error("unable to copy using execCommand: ",a),i&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(o.format||"text",s),o.onCopy&&o.onCopy(window.clipboardData),L=!0}catch(a){i&&console.error("unable to copy using clipboardData: ",a),i&&console.error("falling back to prompt"),_=function format(s){var o=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return s.replace(/#{\s*key\s*}/g,o)}("message"in o?o.message:"Copy to clipboard: #{key}, Enter"),window.prompt(_,s)}}finally{C&&("function"==typeof C.removeRange?C.removeRange(x):C.removeAllRanges()),j&&document.body.removeChild(j),w()}return L}},2205(s,o,i){var a;a=void 0!==i.g?i.g:this,s.exports=function(s){if(s.CSS&&s.CSS.escape)return s.CSS.escape;var cssEscape=function(s){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var o,i=String(s),a=i.length,u=-1,_="",w=i.charCodeAt(0);++u=1&&o<=31||127==o||0==u&&o>=48&&o<=57||1==u&&o>=48&&o<=57&&45==w?"\\"+o.toString(16)+" ":0==u&&1==a&&45==o||!(o>=128||45==o||95==o||o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122)?"\\"+i.charAt(u):i.charAt(u):_+="�";return _};return s.CSS||(s.CSS={}),s.CSS.escape=cssEscape,cssEscape}(a)},81919(s,o,i){"use strict";var a=i(48287).Buffer;function isSpecificValue(s){return s instanceof a||s instanceof Date||s instanceof RegExp}function cloneSpecificValue(s){if(s instanceof a){var o=a.alloc?a.alloc(s.length):new a(s.length);return s.copy(o),o}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s);throw new Error("Unexpected situation")}function deepCloneArray(s){var o=[];return s.forEach((function(s,i){"object"==typeof s&&null!==s?Array.isArray(s)?o[i]=deepCloneArray(s):isSpecificValue(s)?o[i]=cloneSpecificValue(s):o[i]=u({},s):o[i]=s})),o}function safeGetProperty(s,o){return"__proto__"===o?void 0:s[o]}var u=s.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var s,o,i=arguments[0];return Array.prototype.slice.call(arguments,1).forEach((function(a){"object"!=typeof a||null===a||Array.isArray(a)||Object.keys(a).forEach((function(_){return o=safeGetProperty(i,_),(s=safeGetProperty(a,_))===i?void 0:"object"!=typeof s||null===s?void(i[_]=s):Array.isArray(s)?void(i[_]=deepCloneArray(s)):isSpecificValue(s)?void(i[_]=cloneSpecificValue(s)):"object"!=typeof o||null===o||Array.isArray(o)?void(i[_]=u({},s)):void(i[_]=u(o,s))}))})),i}},14744(s){"use strict";var o=function isMergeableObject(s){return function isNonNullObject(s){return!!s&&"object"==typeof s}(s)&&!function isSpecial(s){var o=Object.prototype.toString.call(s);return"[object RegExp]"===o||"[object Date]"===o||function isReactElement(s){return s.$$typeof===i}(s)}(s)};var i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function cloneUnlessOtherwiseSpecified(s,o){return!1!==o.clone&&o.isMergeableObject(s)?deepmerge(function emptyTarget(s){return Array.isArray(s)?[]:{}}(s),s,o):s}function defaultArrayMerge(s,o,i){return s.concat(o).map((function(s){return cloneUnlessOtherwiseSpecified(s,i)}))}function getKeys(s){return Object.keys(s).concat(function getEnumerableOwnPropertySymbols(s){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(s).filter((function(o){return Object.propertyIsEnumerable.call(s,o)})):[]}(s))}function propertyIsOnObject(s,o){try{return o in s}catch(s){return!1}}function mergeObject(s,o,i){var a={};return i.isMergeableObject(s)&&getKeys(s).forEach((function(o){a[o]=cloneUnlessOtherwiseSpecified(s[o],i)})),getKeys(o).forEach((function(u){(function propertyIsUnsafe(s,o){return propertyIsOnObject(s,o)&&!(Object.hasOwnProperty.call(s,o)&&Object.propertyIsEnumerable.call(s,o))})(s,u)||(propertyIsOnObject(s,u)&&i.isMergeableObject(o[u])?a[u]=function getMergeFunction(s,o){if(!o.customMerge)return deepmerge;var i=o.customMerge(s);return"function"==typeof i?i:deepmerge}(u,i)(s[u],o[u],i):a[u]=cloneUnlessOtherwiseSpecified(o[u],i))})),a}function deepmerge(s,i,a){(a=a||{}).arrayMerge=a.arrayMerge||defaultArrayMerge,a.isMergeableObject=a.isMergeableObject||o,a.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var u=Array.isArray(i);return u===Array.isArray(s)?u?a.arrayMerge(s,i,a):mergeObject(s,i,a):cloneUnlessOtherwiseSpecified(i,a)}deepmerge.all=function deepmergeAll(s,o){if(!Array.isArray(s))throw new Error("first argument should be an array");return s.reduce((function(s,i){return deepmerge(s,i,o)}),{})};var a=deepmerge;s.exports=a},30041(s,o,i){"use strict";var a=i(30655),u=i(58068),_=i(69675),w=i(75795);s.exports=function defineDataProperty(s,o,i){if(!s||"object"!=typeof s&&"function"!=typeof s)throw new _("`obj` must be an object or a function`");if("string"!=typeof o&&"symbol"!=typeof o)throw new _("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new _("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new _("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new _("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new _("`loose`, if provided, must be a boolean");var x=arguments.length>3?arguments[3]:null,C=arguments.length>4?arguments[4]:null,j=arguments.length>5?arguments[5]:null,L=arguments.length>6&&arguments[6],B=!!w&&w(s,o);if(a)a(s,o,{configurable:null===j&&B?B.configurable:!j,enumerable:null===x&&B?B.enumerable:!x,value:i,writable:null===C&&B?B.writable:!C});else{if(!L&&(x||C||j))throw new u("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");s[o]=i}}},78004(s){"use strict";class SubRange{constructor(s,o){this.low=s,this.high=o,this.length=1+o-s}overlaps(s){return!(this.highs.high)}touches(s){return!(this.high+1s.high)}add(s){return new SubRange(Math.min(this.low,s.low),Math.max(this.high,s.high))}subtract(s){return s.low<=this.low&&s.high>=this.high?[]:s.low>this.low&&s.highs+o.length),0)}add(s,o){var _add=s=>{for(var o=0;o{for(var o=0;o{for(var o=0;o{for(var i=o.low;i<=o.high;)s.push(i),i++;return s}),[])}subranges(){return this.ranges.map((s=>({low:s.low,high:s.high,length:1+s.high-s.low})))}}s.exports=DRange},7176(s,o,i){"use strict";var a,u=i(73126),_=i(75795);try{a=[].__proto__===Array.prototype}catch(s){if(!s||"object"!=typeof s||!("code"in s)||"ERR_PROTO_ACCESS"!==s.code)throw s}var w=!!a&&_&&_(Object.prototype,"__proto__"),x=Object,C=x.getPrototypeOf;s.exports=w&&"function"==typeof w.get?u([w.get]):"function"==typeof C&&function getDunder(s){return C(null==s?s:x(s))}},30655(s){"use strict";var o=Object.defineProperty||!1;if(o)try{o({},"a",{value:1})}catch(s){o=!1}s.exports=o},41237(s){"use strict";s.exports=EvalError},69383(s){"use strict";s.exports=Error},79290(s){"use strict";s.exports=RangeError},79538(s){"use strict";s.exports=ReferenceError},58068(s){"use strict";s.exports=SyntaxError},69675(s){"use strict";s.exports=TypeError},35345(s){"use strict";s.exports=URIError},79612(s){"use strict";s.exports=Object},37007(s){"use strict";var o,i="object"==typeof Reflect?Reflect:null,a=i&&"function"==typeof i.apply?i.apply:function ReflectApply(s,o,i){return Function.prototype.apply.call(s,o,i)};o=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:function ReflectOwnKeys(s){return Object.getOwnPropertyNames(s)};var u=Number.isNaN||function NumberIsNaN(s){return s!=s};function EventEmitter(){EventEmitter.init.call(this)}s.exports=EventEmitter,s.exports.once=function once(s,o){return new Promise((function(i,a){function errorListener(i){s.removeListener(o,resolver),a(i)}function resolver(){"function"==typeof s.removeListener&&s.removeListener("error",errorListener),i([].slice.call(arguments))}eventTargetAgnosticAddListener(s,o,resolver,{once:!0}),"error"!==o&&function addErrorHandlerIfEventEmitter(s,o,i){"function"==typeof s.on&&eventTargetAgnosticAddListener(s,"error",o,i)}(s,errorListener,{once:!0})}))},EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var _=10;function checkListener(s){if("function"!=typeof s)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}function _getMaxListeners(s){return void 0===s._maxListeners?EventEmitter.defaultMaxListeners:s._maxListeners}function _addListener(s,o,i,a){var u,_,w;if(checkListener(i),void 0===(_=s._events)?(_=s._events=Object.create(null),s._eventsCount=0):(void 0!==_.newListener&&(s.emit("newListener",o,i.listener?i.listener:i),_=s._events),w=_[o]),void 0===w)w=_[o]=i,++s._eventsCount;else if("function"==typeof w?w=_[o]=a?[i,w]:[w,i]:a?w.unshift(i):w.push(i),(u=_getMaxListeners(s))>0&&w.length>u&&!w.warned){w.warned=!0;var x=new Error("Possible EventEmitter memory leak detected. "+w.length+" "+String(o)+" listeners added. Use emitter.setMaxListeners() to increase limit");x.name="MaxListenersExceededWarning",x.emitter=s,x.type=o,x.count=w.length,function ProcessEmitWarning(s){console&&console.warn&&console.warn(s)}(x)}return s}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(s,o,i){var a={fired:!1,wrapFn:void 0,target:s,type:o,listener:i},u=onceWrapper.bind(a);return u.listener=i,a.wrapFn=u,u}function _listeners(s,o,i){var a=s._events;if(void 0===a)return[];var u=a[o];return void 0===u?[]:"function"==typeof u?i?[u.listener||u]:[u]:i?function unwrapListeners(s){for(var o=new Array(s.length),i=0;i0&&(w=o[0]),w instanceof Error)throw w;var x=new Error("Unhandled error."+(w?" ("+w.message+")":""));throw x.context=w,x}var C=_[s];if(void 0===C)return!1;if("function"==typeof C)a(C,this,o);else{var j=C.length,L=arrayClone(C,j);for(i=0;i=0;_--)if(i[_]===o||i[_].listener===o){w=i[_].listener,u=_;break}if(u<0)return this;0===u?i.shift():function spliceOne(s,o){for(;o+1=0;a--)this.removeListener(s,o[a]);return this},EventEmitter.prototype.listeners=function listeners(s){return _listeners(this,s,!0)},EventEmitter.prototype.rawListeners=function rawListeners(s){return _listeners(this,s,!1)},EventEmitter.listenerCount=function(s,o){return"function"==typeof s.listenerCount?s.listenerCount(o):listenerCount.call(s,o)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?o(this._events):[]}},85587(s,o,i){"use strict";var a=i(26311),u=create(Error);function create(s){return FormattedError.displayName=s.displayName||s.name,FormattedError;function FormattedError(o){return o&&(o=a.apply(null,arguments)),new s(o)}}s.exports=u,u.eval=create(EvalError),u.range=create(RangeError),u.reference=create(ReferenceError),u.syntax=create(SyntaxError),u.type=create(TypeError),u.uri=create(URIError),u.create=create},82682(s,o,i){"use strict";var a=i(69600),u=Object.prototype.toString,_=Object.prototype.hasOwnProperty;s.exports=function forEach(s,o,i){if(!a(o))throw new TypeError("iterator must be a function");var w;arguments.length>=3&&(w=i),function isArray(s){return"[object Array]"===u.call(s)}(s)?function forEachArray(s,o,i){for(var a=0,u=s.length;a0?parseInt(i):null};x1&&"boolean"!=typeof o)throw new L('"allowMissing" argument must be a boolean');if(null===Xe(/^%?[^%]*%?$/,s))throw new j("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=function stringToPath(s){var o=Ye(s,0,1),i=Ye(s,-1);if("%"===o&&"%"!==i)throw new j("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==o)throw new j("invalid intrinsic syntax, expected opening `%`");var a=[];return He(s,Qe,(function(s,o,i,u){a[a.length]=i?He(u,et,"$1"):o||s})),a}(s),a=i.length>0?i[0]:"",u=tt("%"+a+"%",o),_=u.name,w=u.value,x=!1,C=u.alias;C&&(a=C[0],We(i,ze([0,1],C)));for(var B=1,$=!0;B=i.length){var Y=ae(w,U);w=($=!!Y)&&"get"in Y&&!("originalValue"in Y.get)?Y.get:w[U]}else $=qe(w,U),w=w[U];$&&!x&&(xe[_]=w)}}return w}},71064(s,o,i){"use strict";var a=i(79612);s.exports=a.getPrototypeOf||null},48648(s){"use strict";s.exports="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null},93628(s,o,i){"use strict";var a=i(48648),u=i(71064),_=i(7176);s.exports=a?function getProto(s){return a(s)}:u?function getProto(s){if(!s||"object"!=typeof s&&"function"!=typeof s)throw new TypeError("getProto: not an object");return u(s)}:_?function getProto(s){return _(s)}:null},6549(s){"use strict";s.exports=Object.getOwnPropertyDescriptor},75795(s,o,i){"use strict";var a=i(6549);if(a)try{a([],"length")}catch(s){a=null}s.exports=a},30592(s,o,i){"use strict";var a=i(30655),u=function hasPropertyDescriptors(){return!!a};u.hasArrayLengthDefineBug=function hasArrayLengthDefineBug(){if(!a)return null;try{return 1!==a([],"length",{value:1}).length}catch(s){return!0}},s.exports=u},64039(s,o,i){"use strict";var a="undefined"!=typeof Symbol&&Symbol,u=i(41333);s.exports=function hasNativeSymbols(){return"function"==typeof a&&("function"==typeof Symbol&&("symbol"==typeof a("foo")&&("symbol"==typeof Symbol("bar")&&u())))}},41333(s){"use strict";s.exports=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var s={},o=Symbol("test"),i=Object(o);if("string"==typeof o)return!1;if("[object Symbol]"!==Object.prototype.toString.call(o))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(var a in s[o]=42,s)return!1;if("function"==typeof Object.keys&&0!==Object.keys(s).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(s).length)return!1;var u=Object.getOwnPropertySymbols(s);if(1!==u.length||u[0]!==o)return!1;if(!Object.prototype.propertyIsEnumerable.call(s,o))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var _=Object.getOwnPropertyDescriptor(s,o);if(42!==_.value||!0!==_.enumerable)return!1}return!0}},49092(s,o,i){"use strict";var a=i(41333);s.exports=function hasToStringTagShams(){return a()&&!!Symbol.toStringTag}},9957(s,o,i){"use strict";var a=Function.prototype.call,u=Object.prototype.hasOwnProperty,_=i(66743);s.exports=_.call(a,u)},45981(s){function deepFreeze(s){return s instanceof Map?s.clear=s.delete=s.set=function(){throw new Error("map is read-only")}:s instanceof Set&&(s.add=s.clear=s.delete=function(){throw new Error("set is read-only")}),Object.freeze(s),Object.getOwnPropertyNames(s).forEach((function(o){var i=s[o];"object"!=typeof i||Object.isFrozen(i)||deepFreeze(i)})),s}var o=deepFreeze,i=deepFreeze;o.default=i;class Response{constructor(s){void 0===s.data&&(s.data={}),this.data=s.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function escapeHTML(s){return s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function inherit(s,...o){const i=Object.create(null);for(const o in s)i[o]=s[o];return o.forEach((function(s){for(const o in s)i[o]=s[o]})),i}const emitsWrappingTags=s=>!!s.kind;class HTMLRenderer{constructor(s,o){this.buffer="",this.classPrefix=o.classPrefix,s.walk(this)}addText(s){this.buffer+=escapeHTML(s)}openNode(s){if(!emitsWrappingTags(s))return;let o=s.kind;s.sublanguage||(o=`${this.classPrefix}${o}`),this.span(o)}closeNode(s){emitsWrappingTags(s)&&(this.buffer+="")}value(){return this.buffer}span(s){this.buffer+=``}}class TokenTree{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(s){this.top.children.push(s)}openNode(s){const o={kind:s,children:[]};this.add(o),this.stack.push(o)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(s){return this.constructor._walk(s,this.rootNode)}static _walk(s,o){return"string"==typeof o?s.addText(o):o.children&&(s.openNode(o),o.children.forEach((o=>this._walk(s,o))),s.closeNode(o)),s}static _collapse(s){"string"!=typeof s&&s.children&&(s.children.every((s=>"string"==typeof s))?s.children=[s.children.join("")]:s.children.forEach((s=>{TokenTree._collapse(s)})))}}class TokenTreeEmitter extends TokenTree{constructor(s){super(),this.options=s}addKeyword(s,o){""!==s&&(this.openNode(o),this.addText(s),this.closeNode())}addText(s){""!==s&&this.add(s)}addSublanguage(s,o){const i=s.root;i.kind=o,i.sublanguage=!0,this.add(i)}toHTML(){return new HTMLRenderer(this,this.options).value()}finalize(){return!0}}function source(s){return s?"string"==typeof s?s:s.source:null}const a=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;const u="[a-zA-Z]\\w*",_="[a-zA-Z_]\\w*",w="\\b\\d+(\\.\\d+)?",x="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",C="\\b(0b[01]+)",j={begin:"\\\\[\\s\\S]",relevance:0},L={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[j]},B={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[j]},$={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},COMMENT=function(s,o,i={}){const a=inherit({className:"comment",begin:s,end:o,contains:[]},i);return a.contains.push($),a.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),a},U=COMMENT("//","$"),V=COMMENT("/\\*","\\*/"),z=COMMENT("#","$"),Y={className:"number",begin:w,relevance:0},Z={className:"number",begin:x,relevance:0},ee={className:"number",begin:C,relevance:0},ie={className:"number",begin:w+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},ae={begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[j,{begin:/\[/,end:/\]/,relevance:0,contains:[j]}]}]},ce={className:"title",begin:u,relevance:0},le={className:"title",begin:_,relevance:0},pe={begin:"\\.\\s*"+_,relevance:0};var de=Object.freeze({__proto__:null,MATCH_NOTHING_RE:/\b\B/,IDENT_RE:u,UNDERSCORE_IDENT_RE:_,NUMBER_RE:w,C_NUMBER_RE:x,BINARY_NUMBER_RE:C,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(s={})=>{const o=/^#![ ]*\//;return s.binary&&(s.begin=function concat(...s){return s.map((s=>source(s))).join("")}(o,/.*\b/,s.binary,/\b.*/)),inherit({className:"meta",begin:o,end:/$/,relevance:0,"on:begin":(s,o)=>{0!==s.index&&o.ignoreMatch()}},s)},BACKSLASH_ESCAPE:j,APOS_STRING_MODE:L,QUOTE_STRING_MODE:B,PHRASAL_WORDS_MODE:$,COMMENT,C_LINE_COMMENT_MODE:U,C_BLOCK_COMMENT_MODE:V,HASH_COMMENT_MODE:z,NUMBER_MODE:Y,C_NUMBER_MODE:Z,BINARY_NUMBER_MODE:ee,CSS_NUMBER_MODE:ie,REGEXP_MODE:ae,TITLE_MODE:ce,UNDERSCORE_TITLE_MODE:le,METHOD_GUARD:pe,END_SAME_AS_BEGIN:function(s){return Object.assign(s,{"on:begin":(s,o)=>{o.data._beginMatch=s[1]},"on:end":(s,o)=>{o.data._beginMatch!==s[1]&&o.ignoreMatch()}})}});function skipIfhasPrecedingDot(s,o){"."===s.input[s.index-1]&&o.ignoreMatch()}function beginKeywords(s,o){o&&s.beginKeywords&&(s.begin="\\b("+s.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",s.__beforeBegin=skipIfhasPrecedingDot,s.keywords=s.keywords||s.beginKeywords,delete s.beginKeywords,void 0===s.relevance&&(s.relevance=0))}function compileIllegal(s,o){Array.isArray(s.illegal)&&(s.illegal=function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}(...s.illegal))}function compileMatch(s,o){if(s.match){if(s.begin||s.end)throw new Error("begin & end are not supported with match");s.begin=s.match,delete s.match}}function compileRelevance(s,o){void 0===s.relevance&&(s.relevance=1)}const fe=["of","and","for","in","not","or","if","then","parent","list","value"];function compileKeywords(s,o,i="keyword"){const a={};return"string"==typeof s?compileList(i,s.split(" ")):Array.isArray(s)?compileList(i,s):Object.keys(s).forEach((function(i){Object.assign(a,compileKeywords(s[i],o,i))})),a;function compileList(s,i){o&&(i=i.map((s=>s.toLowerCase()))),i.forEach((function(o){const i=o.split("|");a[i[0]]=[s,scoreForKeyword(i[0],i[1])]}))}}function scoreForKeyword(s,o){return o?Number(o):function commonKeyword(s){return fe.includes(s.toLowerCase())}(s)?0:1}function compileLanguage(s,{plugins:o}){function langRe(o,i){return new RegExp(source(o),"m"+(s.case_insensitive?"i":"")+(i?"g":""))}class MultiRegex{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(s,o){o.position=this.position++,this.matchIndexes[this.matchAt]=o,this.regexes.push([o,s]),this.matchAt+=function countMatchGroups(s){return new RegExp(s.toString()+"|").exec("").length-1}(s)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const s=this.regexes.map((s=>s[1]));this.matcherRe=langRe(function join(s,o="|"){let i=0;return s.map((s=>{i+=1;const o=i;let u=source(s),_="";for(;u.length>0;){const s=a.exec(u);if(!s){_+=u;break}_+=u.substring(0,s.index),u=u.substring(s.index+s[0].length),"\\"===s[0][0]&&s[1]?_+="\\"+String(Number(s[1])+o):(_+=s[0],"("===s[0]&&i++)}return _})).map((s=>`(${s})`)).join(o)}(s),!0),this.lastIndex=0}exec(s){this.matcherRe.lastIndex=this.lastIndex;const o=this.matcherRe.exec(s);if(!o)return null;const i=o.findIndex(((s,o)=>o>0&&void 0!==s)),a=this.matchIndexes[i];return o.splice(0,i),Object.assign(o,a)}}class ResumableMultiRegex{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(s){if(this.multiRegexes[s])return this.multiRegexes[s];const o=new MultiRegex;return this.rules.slice(s).forEach((([s,i])=>o.addRule(s,i))),o.compile(),this.multiRegexes[s]=o,o}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(s,o){this.rules.push([s,o]),"begin"===o.type&&this.count++}exec(s){const o=this.getMatcher(this.regexIndex);o.lastIndex=this.lastIndex;let i=o.exec(s);if(this.resumingScanAtSamePosition())if(i&&i.index===this.lastIndex);else{const o=this.getMatcher(0);o.lastIndex=this.lastIndex+1,i=o.exec(s)}return i&&(this.regexIndex+=i.position+1,this.regexIndex===this.count&&this.considerAll()),i}}if(s.compilerExtensions||(s.compilerExtensions=[]),s.contains&&s.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return s.classNameAliases=inherit(s.classNameAliases||{}),function compileMode(o,i){const a=o;if(o.isCompiled)return a;[compileMatch].forEach((s=>s(o,i))),s.compilerExtensions.forEach((s=>s(o,i))),o.__beforeBegin=null,[beginKeywords,compileIllegal,compileRelevance].forEach((s=>s(o,i))),o.isCompiled=!0;let u=null;if("object"==typeof o.keywords&&(u=o.keywords.$pattern,delete o.keywords.$pattern),o.keywords&&(o.keywords=compileKeywords(o.keywords,s.case_insensitive)),o.lexemes&&u)throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return u=u||o.lexemes||/\w+/,a.keywordPatternRe=langRe(u,!0),i&&(o.begin||(o.begin=/\B|\b/),a.beginRe=langRe(o.begin),o.endSameAsBegin&&(o.end=o.begin),o.end||o.endsWithParent||(o.end=/\B|\b/),o.end&&(a.endRe=langRe(o.end)),a.terminatorEnd=source(o.end)||"",o.endsWithParent&&i.terminatorEnd&&(a.terminatorEnd+=(o.end?"|":"")+i.terminatorEnd)),o.illegal&&(a.illegalRe=langRe(o.illegal)),o.contains||(o.contains=[]),o.contains=[].concat(...o.contains.map((function(s){return function expandOrCloneMode(s){s.variants&&!s.cachedVariants&&(s.cachedVariants=s.variants.map((function(o){return inherit(s,{variants:null},o)})));if(s.cachedVariants)return s.cachedVariants;if(dependencyOnParent(s))return inherit(s,{starts:s.starts?inherit(s.starts):null});if(Object.isFrozen(s))return inherit(s);return s}("self"===s?o:s)}))),o.contains.forEach((function(s){compileMode(s,a)})),o.starts&&compileMode(o.starts,i),a.matcher=function buildModeRegex(s){const o=new ResumableMultiRegex;return s.contains.forEach((s=>o.addRule(s.begin,{rule:s,type:"begin"}))),s.terminatorEnd&&o.addRule(s.terminatorEnd,{type:"end"}),s.illegal&&o.addRule(s.illegal,{type:"illegal"}),o}(a),a}(s)}function dependencyOnParent(s){return!!s&&(s.endsWithParent||dependencyOnParent(s.starts))}function BuildVuePlugin(s){const o={props:["language","code","autodetect"],data:function(){return{detectedLanguage:"",unknownLanguage:!1}},computed:{className(){return this.unknownLanguage?"":"hljs "+this.detectedLanguage},highlighted(){if(!this.autoDetect&&!s.getLanguage(this.language))return console.warn(`The language "${this.language}" you specified could not be found.`),this.unknownLanguage=!0,escapeHTML(this.code);let o={};return this.autoDetect?(o=s.highlightAuto(this.code),this.detectedLanguage=o.language):(o=s.highlight(this.language,this.code,this.ignoreIllegals),this.detectedLanguage=this.language),o.value},autoDetect(){return!this.language||function hasValueOrEmptyAttribute(s){return Boolean(s||""===s)}(this.autodetect)},ignoreIllegals:()=>!0},render(s){return s("pre",{},[s("code",{class:this.className,domProps:{innerHTML:this.highlighted}})])}};return{Component:o,VuePlugin:{install(s){s.component("highlightjs",o)}}}}const ye={"after:highlightElement":({el:s,result:o,text:i})=>{const a=nodeStream(s);if(!a.length)return;const u=document.createElement("div");u.innerHTML=o.value,o.value=function mergeStreams(s,o,i){let a=0,u="";const _=[];function selectStream(){return s.length&&o.length?s[0].offset!==o[0].offset?s[0].offset"}function close(s){u+=""}function render(s){("start"===s.event?open:close)(s.node)}for(;s.length||o.length;){let o=selectStream();if(u+=escapeHTML(i.substring(a,o[0].offset)),a=o[0].offset,o===s){_.reverse().forEach(close);do{render(o.splice(0,1)[0]),o=selectStream()}while(o===s&&o.length&&o[0].offset===a);_.reverse().forEach(open)}else"start"===o[0].event?_.push(o[0].node):_.pop(),render(o.splice(0,1)[0])}return u+escapeHTML(i.substr(a))}(a,nodeStream(u),i)}};function tag(s){return s.nodeName.toLowerCase()}function nodeStream(s){const o=[];return function _nodeStream(s,i){for(let a=s.firstChild;a;a=a.nextSibling)3===a.nodeType?i+=a.nodeValue.length:1===a.nodeType&&(o.push({event:"start",offset:i,node:a}),i=_nodeStream(a,i),tag(a).match(/br|hr|img|input/)||o.push({event:"stop",offset:i,node:a}));return i}(s,0),o}const be={},error=s=>{console.error(s)},warn=(s,...o)=>{console.log(`WARN: ${s}`,...o)},deprecated=(s,o)=>{be[`${s}/${o}`]||(console.log(`Deprecated as of ${s}. ${o}`),be[`${s}/${o}`]=!0)},Se=escapeHTML,_e=inherit,we=Symbol("nomatch");var xe=function(s){const i=Object.create(null),a=Object.create(null),u=[];let _=!0;const w=/(^(<[^>]+>|\t|)+|\n)/gm,x="Could not find the language '{}', did you forget to load/include a language module?",C={disableAutodetect:!0,name:"Plain text",contains:[]};let j={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:TokenTreeEmitter};function shouldNotHighlight(s){return j.noHighlightRe.test(s)}function highlight(s,o,i,a){let u="",_="";"object"==typeof o?(u=s,i=o.ignoreIllegals,_=o.language,a=void 0):(deprecated("10.7.0","highlight(lang, code, ...args) has been deprecated."),deprecated("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),_=s,u=o);const w={code:u,language:_};fire("before:highlight",w);const x=w.result?w.result:_highlight(w.language,w.code,i,a);return x.code=w.code,fire("after:highlight",x),x}function _highlight(s,o,a,w){function keywordData(s,o){const i=L.case_insensitive?o[0].toLowerCase():o[0];return Object.prototype.hasOwnProperty.call(s.keywords,i)&&s.keywords[i]}function processBuffer(){null!=U.subLanguage?function processSubLanguage(){if(""===Y)return;let s=null;if("string"==typeof U.subLanguage){if(!i[U.subLanguage])return void z.addText(Y);s=_highlight(U.subLanguage,Y,!0,V[U.subLanguage]),V[U.subLanguage]=s.top}else s=highlightAuto(Y,U.subLanguage.length?U.subLanguage:null);U.relevance>0&&(Z+=s.relevance),z.addSublanguage(s.emitter,s.language)}():function processKeywords(){if(!U.keywords)return void z.addText(Y);let s=0;U.keywordPatternRe.lastIndex=0;let o=U.keywordPatternRe.exec(Y),i="";for(;o;){i+=Y.substring(s,o.index);const a=keywordData(U,o);if(a){const[s,u]=a;if(z.addText(i),i="",Z+=u,s.startsWith("_"))i+=o[0];else{const i=L.classNameAliases[s]||s;z.addKeyword(o[0],i)}}else i+=o[0];s=U.keywordPatternRe.lastIndex,o=U.keywordPatternRe.exec(Y)}i+=Y.substr(s),z.addText(i)}(),Y=""}function startNewMode(s){return s.className&&z.openNode(L.classNameAliases[s.className]||s.className),U=Object.create(s,{parent:{value:U}}),U}function endOfMode(s,o,i){let a=function startsWith(s,o){const i=s&&s.exec(o);return i&&0===i.index}(s.endRe,i);if(a){if(s["on:end"]){const i=new Response(s);s["on:end"](o,i),i.isMatchIgnored&&(a=!1)}if(a){for(;s.endsParent&&s.parent;)s=s.parent;return s}}if(s.endsWithParent)return endOfMode(s.parent,o,i)}function doIgnore(s){return 0===U.matcher.regexIndex?(Y+=s[0],1):(ae=!0,0)}function doBeginMatch(s){const o=s[0],i=s.rule,a=new Response(i),u=[i.__beforeBegin,i["on:begin"]];for(const i of u)if(i&&(i(s,a),a.isMatchIgnored))return doIgnore(o);return i&&i.endSameAsBegin&&(i.endRe=function escape(s){return new RegExp(s.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}(o)),i.skip?Y+=o:(i.excludeBegin&&(Y+=o),processBuffer(),i.returnBegin||i.excludeBegin||(Y=o)),startNewMode(i),i.returnBegin?0:o.length}function doEndMatch(s){const i=s[0],a=o.substr(s.index),u=endOfMode(U,s,a);if(!u)return we;const _=U;_.skip?Y+=i:(_.returnEnd||_.excludeEnd||(Y+=i),processBuffer(),_.excludeEnd&&(Y=i));do{U.className&&z.closeNode(),U.skip||U.subLanguage||(Z+=U.relevance),U=U.parent}while(U!==u.parent);return u.starts&&(u.endSameAsBegin&&(u.starts.endRe=u.endRe),startNewMode(u.starts)),_.returnEnd?0:i.length}let C={};function processLexeme(i,u){const w=u&&u[0];if(Y+=i,null==w)return processBuffer(),0;if("begin"===C.type&&"end"===u.type&&C.index===u.index&&""===w){if(Y+=o.slice(u.index,u.index+1),!_){const o=new Error("0 width match regex");throw o.languageName=s,o.badRule=C.rule,o}return 1}if(C=u,"begin"===u.type)return doBeginMatch(u);if("illegal"===u.type&&!a){const s=new Error('Illegal lexeme "'+w+'" for mode "'+(U.className||"")+'"');throw s.mode=U,s}if("end"===u.type){const s=doEndMatch(u);if(s!==we)return s}if("illegal"===u.type&&""===w)return 1;if(ie>1e5&&ie>3*u.index){throw new Error("potential infinite loop, way more iterations than matches")}return Y+=w,w.length}const L=getLanguage(s);if(!L)throw error(x.replace("{}",s)),new Error('Unknown language: "'+s+'"');const B=compileLanguage(L,{plugins:u});let $="",U=w||B;const V={},z=new j.__emitter(j);!function processContinuations(){const s=[];for(let o=U;o!==L;o=o.parent)o.className&&s.unshift(o.className);s.forEach((s=>z.openNode(s)))}();let Y="",Z=0,ee=0,ie=0,ae=!1;try{for(U.matcher.considerAll();;){ie++,ae?ae=!1:U.matcher.considerAll(),U.matcher.lastIndex=ee;const s=U.matcher.exec(o);if(!s)break;const i=processLexeme(o.substring(ee,s.index),s);ee=s.index+i}return processLexeme(o.substr(ee)),z.closeAllNodes(),z.finalize(),$=z.toHTML(),{relevance:Math.floor(Z),value:$,language:s,illegal:!1,emitter:z,top:U}}catch(i){if(i.message&&i.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:i.message,context:o.slice(ee-100,ee+100),mode:i.mode},sofar:$,relevance:0,value:Se(o),emitter:z};if(_)return{illegal:!1,relevance:0,value:Se(o),emitter:z,language:s,top:U,errorRaised:i};throw i}}function highlightAuto(s,o){o=o||j.languages||Object.keys(i);const a=function justTextHighlightResult(s){const o={relevance:0,emitter:new j.__emitter(j),value:Se(s),illegal:!1,top:C};return o.emitter.addText(s),o}(s),u=o.filter(getLanguage).filter(autoDetection).map((o=>_highlight(o,s,!1)));u.unshift(a);const _=u.sort(((s,o)=>{if(s.relevance!==o.relevance)return o.relevance-s.relevance;if(s.language&&o.language){if(getLanguage(s.language).supersetOf===o.language)return 1;if(getLanguage(o.language).supersetOf===s.language)return-1}return 0})),[w,x]=_,L=w;return L.second_best=x,L}const L={"before:highlightElement":({el:s})=>{j.useBR&&(s.innerHTML=s.innerHTML.replace(/\n/g,"").replace(//g,"\n"))},"after:highlightElement":({result:s})=>{j.useBR&&(s.value=s.value.replace(/\n/g,"
"))}},B=/^(<[^>]+>|\t)+/gm,$={"after:highlightElement":({result:s})=>{j.tabReplace&&(s.value=s.value.replace(B,(s=>s.replace(/\t/g,j.tabReplace))))}};function highlightElement(s){let o=null;const i=function blockLanguage(s){let o=s.className+" ";o+=s.parentNode?s.parentNode.className:"";const i=j.languageDetectRe.exec(o);if(i){const o=getLanguage(i[1]);return o||(warn(x.replace("{}",i[1])),warn("Falling back to no-highlight mode for this block.",s)),o?i[1]:"no-highlight"}return o.split(/\s+/).find((s=>shouldNotHighlight(s)||getLanguage(s)))}(s);if(shouldNotHighlight(i))return;fire("before:highlightElement",{el:s,language:i}),o=s;const u=o.textContent,_=i?highlight(u,{language:i,ignoreIllegals:!0}):highlightAuto(u);fire("after:highlightElement",{el:s,result:_,text:u}),s.innerHTML=_.value,function updateClassName(s,o,i){const u=o?a[o]:i;s.classList.add("hljs"),u&&s.classList.add(u)}(s,i,_.language),s.result={language:_.language,re:_.relevance,relavance:_.relevance},_.second_best&&(s.second_best={language:_.second_best.language,re:_.second_best.relevance,relavance:_.second_best.relevance})}const initHighlighting=()=>{if(initHighlighting.called)return;initHighlighting.called=!0,deprecated("10.6.0","initHighlighting() is deprecated. Use highlightAll() instead.");document.querySelectorAll("pre code").forEach(highlightElement)};let U=!1;function highlightAll(){if("loading"===document.readyState)return void(U=!0);document.querySelectorAll("pre code").forEach(highlightElement)}function getLanguage(s){return s=(s||"").toLowerCase(),i[s]||i[a[s]]}function registerAliases(s,{languageName:o}){"string"==typeof s&&(s=[s]),s.forEach((s=>{a[s.toLowerCase()]=o}))}function autoDetection(s){const o=getLanguage(s);return o&&!o.disableAutodetect}function fire(s,o){const i=s;u.forEach((function(s){s[i]&&s[i](o)}))}"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(function boot(){U&&highlightAll()}),!1),Object.assign(s,{highlight,highlightAuto,highlightAll,fixMarkup:function deprecateFixMarkup(s){return deprecated("10.2.0","fixMarkup will be removed entirely in v11.0"),deprecated("10.2.0","Please see https://github.com/highlightjs/highlight.js/issues/2534"),function fixMarkup(s){return j.tabReplace||j.useBR?s.replace(w,(s=>"\n"===s?j.useBR?"
":s:j.tabReplace?s.replace(/\t/g,j.tabReplace):s)):s}(s)},highlightElement,highlightBlock:function deprecateHighlightBlock(s){return deprecated("10.7.0","highlightBlock will be removed entirely in v12.0"),deprecated("10.7.0","Please use highlightElement now."),highlightElement(s)},configure:function configure(s){s.useBR&&(deprecated("10.3.0","'useBR' will be removed entirely in v11.0"),deprecated("10.3.0","Please see https://github.com/highlightjs/highlight.js/issues/2559")),j=_e(j,s)},initHighlighting,initHighlightingOnLoad:function initHighlightingOnLoad(){deprecated("10.6.0","initHighlightingOnLoad() is deprecated. Use highlightAll() instead."),U=!0},registerLanguage:function registerLanguage(o,a){let u=null;try{u=a(s)}catch(s){if(error("Language definition for '{}' could not be registered.".replace("{}",o)),!_)throw s;error(s),u=C}u.name||(u.name=o),i[o]=u,u.rawDefinition=a.bind(null,s),u.aliases&®isterAliases(u.aliases,{languageName:o})},unregisterLanguage:function unregisterLanguage(s){delete i[s];for(const o of Object.keys(a))a[o]===s&&delete a[o]},listLanguages:function listLanguages(){return Object.keys(i)},getLanguage,registerAliases,requireLanguage:function requireLanguage(s){deprecated("10.4.0","requireLanguage will be removed entirely in v11."),deprecated("10.4.0","Please see https://github.com/highlightjs/highlight.js/pull/2844");const o=getLanguage(s);if(o)return o;throw new Error("The '{}' language is required, but not loaded.".replace("{}",s))},autoDetection,inherit:_e,addPlugin:function addPlugin(s){!function upgradePluginAPI(s){s["before:highlightBlock"]&&!s["before:highlightElement"]&&(s["before:highlightElement"]=o=>{s["before:highlightBlock"](Object.assign({block:o.el},o))}),s["after:highlightBlock"]&&!s["after:highlightElement"]&&(s["after:highlightElement"]=o=>{s["after:highlightBlock"](Object.assign({block:o.el},o))})}(s),u.push(s)},vuePlugin:BuildVuePlugin(s).VuePlugin}),s.debugMode=function(){_=!1},s.safeMode=function(){_=!0},s.versionString="10.7.3";for(const s in de)"object"==typeof de[s]&&o(de[s]);return Object.assign(s,de),s.addPlugin(L),s.addPlugin(ye),s.addPlugin($),s}({});s.exports=xe},35344(s){function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function bash(s){const o={},i={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[o]}]};Object.assign(o,{className:"variable",variants:[{begin:concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},i]});const a={className:"subst",begin:/\$\(/,end:/\)/,contains:[s.BACKSLASH_ESCAPE]},u={begin:/<<-?\s*(?=\w+)/,starts:{contains:[s.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},_={className:"string",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE,o,a]};a.contains.push(_);const w={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},s.NUMBER_MODE,o]},x=s.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),C={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[s.inherit(s.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z._-]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp"},contains:[x,s.SHEBANG(),C,w,s.HASH_COMMENT_MODE,u,_,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},o]}}},73402(s){function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function http(s){const o="HTTP/(2|1\\.[01])",i={className:"attribute",begin:concat("^",/[A-Za-z][A-Za-z0-9-]*/,"(?=\\:\\s)"),starts:{contains:[{className:"punctuation",begin:/: /,relevance:0,starts:{end:"$",relevance:0}}]}},a=[i,{begin:"\\n\\n",starts:{subLanguage:[],endsWithParent:!0}}];return{name:"HTTP",aliases:["https"],illegal:/\S/,contains:[{begin:"^(?="+o+" \\d{3})",end:/$/,contains:[{className:"meta",begin:o},{className:"number",begin:"\\b\\d{3}\\b"}],starts:{end:/\b\B/,illegal:/\S/,contains:a}},{begin:"(?=^[A-Z]+ (.*?) "+o+"$)",end:/$/,contains:[{className:"string",begin:" ",end:" ",excludeBegin:!0,excludeEnd:!0},{className:"meta",begin:o},{className:"keyword",begin:"[A-Z]+"}],starts:{end:/\b\B/,illegal:/\S/,contains:a}},s.inherit(i,{relevance:0})]}}},95089(s){const o="[A-Za-z$_][0-9A-Za-z$_]*",i=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],a=["true","false","null","undefined","NaN","Infinity"],u=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["arguments","this","super","console","window","document","localStorage","module","global"],["Intl","DataView","Number","Math","Date","String","RegExp","Object","Function","Boolean","Error","Symbol","Set","Map","WeakSet","WeakMap","Proxy","Reflect","JSON","Promise","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Float32Array","Array","Uint8Array","Uint8ClampedArray","ArrayBuffer","BigInt64Array","BigUint64Array","BigInt"],["EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function javascript(s){const _=o,w="<>",x="",C={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(s,o)=>{const i=s[0].length+s.index,a=s.input[i];"<"!==a?">"===a&&(((s,{after:o})=>{const i="",returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:s.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:j,contains:ce}]}]},{begin:/,/,relevance:0},{className:"",begin:/\s/,end:/\s*/,skip:!0},{variants:[{begin:w,end:x},{begin:C.begin,"on:begin":C.isTrulyOpeningTag,end:C.end}],subLanguage:"xml",contains:[{begin:C.begin,end:C.end,skip:!0,contains:["self"]}]}],relevance:0},{className:"function",beginKeywords:"function",end:/[{;]/,excludeEnd:!0,keywords:j,contains:["self",s.inherit(s.TITLE_MODE,{begin:_}),le],illegal:/%/},{beginKeywords:"while if switch catch for"},{className:"function",begin:s.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,contains:[le,s.inherit(s.TITLE_MODE,{begin:_})]},{variants:[{begin:"\\."+_},{begin:"\\$"+_}],relevance:0},{className:"class",beginKeywords:"class",end:/[{;=]/,excludeEnd:!0,illegal:/[:"[\]]/,contains:[{beginKeywords:"extends"},s.UNDERSCORE_TITLE_MODE]},{begin:/\b(?=constructor)/,end:/[{;]/,excludeEnd:!0,contains:[s.inherit(s.TITLE_MODE,{begin:_}),"self",le]},{begin:"(get|set)\\s+(?="+_+"\\()",end:/\{/,keywords:"get set",contains:[s.inherit(s.TITLE_MODE,{begin:_}),{begin:/\(\)/},le]},{begin:/\$[(.]/}]}}},65772(s){s.exports=function json(s){const o={literal:"true false null"},i=[s.C_LINE_COMMENT_MODE,s.C_BLOCK_COMMENT_MODE],a=[s.QUOTE_STRING_MODE,s.C_NUMBER_MODE],u={end:",",endsWithParent:!0,excludeEnd:!0,contains:a,keywords:o},_={begin:/\{/,end:/\}/,contains:[{className:"attr",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE],illegal:"\\n"},s.inherit(u,{begin:/:/})].concat(i),illegal:"\\S"},w={begin:"\\[",end:"\\]",contains:[s.inherit(u)],illegal:"\\S"};return a.push(_,w),i.forEach((function(s){a.push(s)})),{name:"JSON",contains:a,keywords:o,illegal:"\\S"}}},26571(s){s.exports=function powershell(s){const o={$pattern:/-?[A-z\.\-]+\b/,keyword:"if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter",built_in:"ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write"},i={begin:"`[\\s\\S]",relevance:0},a={className:"variable",variants:[{begin:/\$\B/},{className:"keyword",begin:/\$this/},{begin:/\$[\w\d][\w\d_:]*/}]},u={className:"string",variants:[{begin:/"/,end:/"/},{begin:/@"/,end:/^"@/}],contains:[i,a,{className:"variable",begin:/\$[A-z]/,end:/[^A-z]/}]},_={className:"string",variants:[{begin:/'/,end:/'/},{begin:/@'/,end:/^'@/}]},w=s.inherit(s.COMMENT(null,null),{variants:[{begin:/#/,end:/$/},{begin:/<#/,end:/#>/}],contains:[{className:"doctag",variants:[{begin:/\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/},{begin:/\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/}]}]}),x={className:"built_in",variants:[{begin:"(".concat("Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where",")+(-)[\\w\\d]+")}]},C={className:"class",beginKeywords:"class enum",end:/\s*[{]/,excludeEnd:!0,relevance:0,contains:[s.TITLE_MODE]},j={className:"function",begin:/function\s+/,end:/\s*\{|$/,excludeEnd:!0,returnBegin:!0,relevance:0,contains:[{begin:"function",relevance:0,className:"keyword"},{className:"title",begin:/\w[\w\d]*((-)[\w\d]+)*/,relevance:0},{begin:/\(/,end:/\)/,className:"params",relevance:0,contains:[a]}]},L={begin:/using\s/,end:/$/,returnBegin:!0,contains:[u,_,{className:"keyword",begin:/(using|assembly|command|module|namespace|type)/}]},B={variants:[{className:"operator",begin:"(".concat("-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor",")\\b")},{className:"literal",begin:/(-)[\w\d]+/,relevance:0}]},$={className:"function",begin:/\[.*\]\s*[\w]+[ ]??\(/,end:/$/,returnBegin:!0,relevance:0,contains:[{className:"keyword",begin:"(".concat(o.keyword.toString().replace(/\s/g,"|"),")\\b"),endsParent:!0,relevance:0},s.inherit(s.TITLE_MODE,{endsParent:!0})]},U=[$,w,i,s.NUMBER_MODE,u,_,x,a,{className:"literal",begin:/\$(null|true|false)\b/},{className:"selector-tag",begin:/@\B/,relevance:0}],V={begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[].concat("self",U,{begin:"("+["string","char","byte","int","long","bool","decimal","single","double","DateTime","xml","array","hashtable","void"].join("|")+")",className:"built_in",relevance:0},{className:"type",begin:/[\.\w\d]+/,relevance:0})};return $.contains.unshift(V),{name:"PowerShell",aliases:["ps","ps1"],case_insensitive:!0,keywords:o,contains:U.concat(C,j,L,B,V)}}},17285(s){function source(s){return s?"string"==typeof s?s:s.source:null}function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>source(s))).join("")}function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}s.exports=function xml(s){const o=concat(/[A-Z_]/,function optional(s){return concat("(",s,")?")}(/[A-Z0-9_.-]*:/),/[A-Z0-9_.-]*/),i={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:"meta-keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},u=s.inherit(a,{begin:/\(/,end:/\)/}),_=s.inherit(s.APOS_STRING_MODE,{className:"meta-string"}),w=s.inherit(s.QUOTE_STRING_MODE,{className:"meta-string"}),x={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin://,relevance:10,contains:[a,w,_,u,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[a,u,w,_]}]}]},s.COMMENT(//,{relevance:10}),{begin://,relevance:10},i,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[x],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[x],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:o,relevance:0,starts:x}]},{className:"tag",begin:concat(/<\//,lookahead(concat(o,/>/))),contains:[{className:"name",begin:o,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}},17533(s){s.exports=function yaml(s){var o="true false yes no null",i="[\\w#;/?:@&=+$,.~*'()[\\]]+",a={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[s.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},u=s.inherit(a,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),_={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},w={end:",",endsWithParent:!0,excludeEnd:!0,keywords:o,relevance:0},x={begin:/\{/,end:/\}/,contains:[w],illegal:"\\n",relevance:0},C={begin:"\\[",end:"\\]",contains:[w],illegal:"\\n",relevance:0},j=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+i},{className:"type",begin:"!<"+i+">"},{className:"type",begin:"!"+i},{className:"type",begin:"!!"+i},{className:"meta",begin:"&"+s.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+s.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},s.HASH_COMMENT_MODE,{beginKeywords:o,keywords:{literal:o}},_,{className:"number",begin:s.C_NUMBER_RE+"\\b",relevance:0},x,C,a],L=[...j];return L.pop(),L.push(u),w.contains=L,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:j}}},251(s,o){o.read=function(s,o,i,a,u){var _,w,x=8*u-a-1,C=(1<>1,L=-7,B=i?u-1:0,$=i?-1:1,U=s[o+B];for(B+=$,_=U&(1<<-L)-1,U>>=-L,L+=x;L>0;_=256*_+s[o+B],B+=$,L-=8);for(w=_&(1<<-L)-1,_>>=-L,L+=a;L>0;w=256*w+s[o+B],B+=$,L-=8);if(0===_)_=1-j;else{if(_===C)return w?NaN:1/0*(U?-1:1);w+=Math.pow(2,a),_-=j}return(U?-1:1)*w*Math.pow(2,_-a)},o.write=function(s,o,i,a,u,_){var w,x,C,j=8*_-u-1,L=(1<>1,$=23===u?Math.pow(2,-24)-Math.pow(2,-77):0,U=a?0:_-1,V=a?1:-1,z=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(x=isNaN(o)?1:0,w=L):(w=Math.floor(Math.log(o)/Math.LN2),o*(C=Math.pow(2,-w))<1&&(w--,C*=2),(o+=w+B>=1?$/C:$*Math.pow(2,1-B))*C>=2&&(w++,C/=2),w+B>=L?(x=0,w=L):w+B>=1?(x=(o*C-1)*Math.pow(2,u),w+=B):(x=o*Math.pow(2,B-1)*Math.pow(2,u),w=0));u>=8;s[i+U]=255&x,U+=V,x/=256,u-=8);for(w=w<0;s[i+U]=255&w,U+=V,w/=256,j-=8);s[i+U-V]|=128*z}},9404(s){s.exports=function(){"use strict";var s=Array.prototype.slice;function createClass(s,o){o&&(s.prototype=Object.create(o.prototype)),s.prototype.constructor=s}function Iterable(s){return isIterable(s)?s:Seq(s)}function KeyedIterable(s){return isKeyed(s)?s:KeyedSeq(s)}function IndexedIterable(s){return isIndexed(s)?s:IndexedSeq(s)}function SetIterable(s){return isIterable(s)&&!isAssociative(s)?s:SetSeq(s)}function isIterable(s){return!(!s||!s[o])}function isKeyed(s){return!(!s||!s[i])}function isIndexed(s){return!(!s||!s[a])}function isAssociative(s){return isKeyed(s)||isIndexed(s)}function isOrdered(s){return!(!s||!s[u])}createClass(KeyedIterable,Iterable),createClass(IndexedIterable,Iterable),createClass(SetIterable,Iterable),Iterable.isIterable=isIterable,Iterable.isKeyed=isKeyed,Iterable.isIndexed=isIndexed,Iterable.isAssociative=isAssociative,Iterable.isOrdered=isOrdered,Iterable.Keyed=KeyedIterable,Iterable.Indexed=IndexedIterable,Iterable.Set=SetIterable;var o="@@__IMMUTABLE_ITERABLE__@@",i="@@__IMMUTABLE_KEYED__@@",a="@@__IMMUTABLE_INDEXED__@@",u="@@__IMMUTABLE_ORDERED__@@",_="delete",w=5,x=1<>>0;if(""+i!==o||4294967295===i)return NaN;o=i}return o<0?ensureSize(s)+o:o}function returnTrue(){return!0}function wholeSlice(s,o,i){return(0===s||void 0!==i&&s<=-i)&&(void 0===o||void 0!==i&&o>=i)}function resolveBegin(s,o){return resolveIndex(s,o,0)}function resolveEnd(s,o){return resolveIndex(s,o,o)}function resolveIndex(s,o,i){return void 0===s?i:s<0?Math.max(0,o+s):void 0===o?s:Math.min(o,s)}var $=0,U=1,V=2,z="function"==typeof Symbol&&Symbol.iterator,Y="@@iterator",Z=z||Y;function Iterator(s){this.next=s}function iteratorValue(s,o,i,a){var u=0===s?o:1===s?i:[o,i];return a?a.value=u:a={value:u,done:!1},a}function iteratorDone(){return{value:void 0,done:!0}}function hasIterator(s){return!!getIteratorFn(s)}function isIterator(s){return s&&"function"==typeof s.next}function getIterator(s){var o=getIteratorFn(s);return o&&o.call(s)}function getIteratorFn(s){var o=s&&(z&&s[z]||s[Y]);if("function"==typeof o)return o}function isArrayLike(s){return s&&"number"==typeof s.length}function Seq(s){return null==s?emptySequence():isIterable(s)?s.toSeq():seqFromValue(s)}function KeyedSeq(s){return null==s?emptySequence().toKeyedSeq():isIterable(s)?isKeyed(s)?s.toSeq():s.fromEntrySeq():keyedSeqFromValue(s)}function IndexedSeq(s){return null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s.toIndexedSeq():indexedSeqFromValue(s)}function SetSeq(s){return(null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s:indexedSeqFromValue(s)).toSetSeq()}Iterator.prototype.toString=function(){return"[Iterator]"},Iterator.KEYS=$,Iterator.VALUES=U,Iterator.ENTRIES=V,Iterator.prototype.inspect=Iterator.prototype.toSource=function(){return this.toString()},Iterator.prototype[Z]=function(){return this},createClass(Seq,Iterable),Seq.of=function(){return Seq(arguments)},Seq.prototype.toSeq=function(){return this},Seq.prototype.toString=function(){return this.__toString("Seq {","}")},Seq.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},Seq.prototype.__iterate=function(s,o){return seqIterate(this,s,o,!0)},Seq.prototype.__iterator=function(s,o){return seqIterator(this,s,o,!0)},createClass(KeyedSeq,Seq),KeyedSeq.prototype.toKeyedSeq=function(){return this},createClass(IndexedSeq,Seq),IndexedSeq.of=function(){return IndexedSeq(arguments)},IndexedSeq.prototype.toIndexedSeq=function(){return this},IndexedSeq.prototype.toString=function(){return this.__toString("Seq [","]")},IndexedSeq.prototype.__iterate=function(s,o){return seqIterate(this,s,o,!1)},IndexedSeq.prototype.__iterator=function(s,o){return seqIterator(this,s,o,!1)},createClass(SetSeq,Seq),SetSeq.of=function(){return SetSeq(arguments)},SetSeq.prototype.toSetSeq=function(){return this},Seq.isSeq=isSeq,Seq.Keyed=KeyedSeq,Seq.Set=SetSeq,Seq.Indexed=IndexedSeq;var ee,ie,ae,ce="@@__IMMUTABLE_SEQ__@@";function ArraySeq(s){this._array=s,this.size=s.length}function ObjectSeq(s){var o=Object.keys(s);this._object=s,this._keys=o,this.size=o.length}function IterableSeq(s){this._iterable=s,this.size=s.length||s.size}function IteratorSeq(s){this._iterator=s,this._iteratorCache=[]}function isSeq(s){return!(!s||!s[ce])}function emptySequence(){return ee||(ee=new ArraySeq([]))}function keyedSeqFromValue(s){var o=Array.isArray(s)?new ArraySeq(s).fromEntrySeq():isIterator(s)?new IteratorSeq(s).fromEntrySeq():hasIterator(s)?new IterableSeq(s).fromEntrySeq():"object"==typeof s?new ObjectSeq(s):void 0;if(!o)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+s);return o}function indexedSeqFromValue(s){var o=maybeIndexedSeqFromValue(s);if(!o)throw new TypeError("Expected Array or iterable object of values: "+s);return o}function seqFromValue(s){var o=maybeIndexedSeqFromValue(s)||"object"==typeof s&&new ObjectSeq(s);if(!o)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+s);return o}function maybeIndexedSeqFromValue(s){return isArrayLike(s)?new ArraySeq(s):isIterator(s)?new IteratorSeq(s):hasIterator(s)?new IterableSeq(s):void 0}function seqIterate(s,o,i,a){var u=s._cache;if(u){for(var _=u.length-1,w=0;w<=_;w++){var x=u[i?_-w:w];if(!1===o(x[1],a?x[0]:w,s))return w+1}return w}return s.__iterateUncached(o,i)}function seqIterator(s,o,i,a){var u=s._cache;if(u){var _=u.length-1,w=0;return new Iterator((function(){var s=u[i?_-w:w];return w++>_?iteratorDone():iteratorValue(o,a?s[0]:w-1,s[1])}))}return s.__iteratorUncached(o,i)}function fromJS(s,o){return o?fromJSWith(o,s,"",{"":s}):fromJSDefault(s)}function fromJSWith(s,o,i,a){return Array.isArray(o)?s.call(a,i,IndexedSeq(o).map((function(i,a){return fromJSWith(s,i,a,o)}))):isPlainObj(o)?s.call(a,i,KeyedSeq(o).map((function(i,a){return fromJSWith(s,i,a,o)}))):o}function fromJSDefault(s){return Array.isArray(s)?IndexedSeq(s).map(fromJSDefault).toList():isPlainObj(s)?KeyedSeq(s).map(fromJSDefault).toMap():s}function isPlainObj(s){return s&&(s.constructor===Object||void 0===s.constructor)}function is(s,o){if(s===o||s!=s&&o!=o)return!0;if(!s||!o)return!1;if("function"==typeof s.valueOf&&"function"==typeof o.valueOf){if((s=s.valueOf())===(o=o.valueOf())||s!=s&&o!=o)return!0;if(!s||!o)return!1}return!("function"!=typeof s.equals||"function"!=typeof o.equals||!s.equals(o))}function deepEqual(s,o){if(s===o)return!0;if(!isIterable(o)||void 0!==s.size&&void 0!==o.size&&s.size!==o.size||void 0!==s.__hash&&void 0!==o.__hash&&s.__hash!==o.__hash||isKeyed(s)!==isKeyed(o)||isIndexed(s)!==isIndexed(o)||isOrdered(s)!==isOrdered(o))return!1;if(0===s.size&&0===o.size)return!0;var i=!isAssociative(s);if(isOrdered(s)){var a=s.entries();return o.every((function(s,o){var u=a.next().value;return u&&is(u[1],s)&&(i||is(u[0],o))}))&&a.next().done}var u=!1;if(void 0===s.size)if(void 0===o.size)"function"==typeof s.cacheResult&&s.cacheResult();else{u=!0;var _=s;s=o,o=_}var w=!0,x=o.__iterate((function(o,a){if(i?!s.has(o):u?!is(o,s.get(a,j)):!is(s.get(a,j),o))return w=!1,!1}));return w&&s.size===x}function Repeat(s,o){if(!(this instanceof Repeat))return new Repeat(s,o);if(this._value=s,this.size=void 0===o?1/0:Math.max(0,o),0===this.size){if(ie)return ie;ie=this}}function invariant(s,o){if(!s)throw new Error(o)}function Range(s,o,i){if(!(this instanceof Range))return new Range(s,o,i);if(invariant(0!==i,"Cannot step a Range by 0"),s=s||0,void 0===o&&(o=1/0),i=void 0===i?1:Math.abs(i),oa?iteratorDone():iteratorValue(s,u,i[o?a-u++:u++])}))},createClass(ObjectSeq,KeyedSeq),ObjectSeq.prototype.get=function(s,o){return void 0===o||this.has(s)?this._object[s]:o},ObjectSeq.prototype.has=function(s){return this._object.hasOwnProperty(s)},ObjectSeq.prototype.__iterate=function(s,o){for(var i=this._object,a=this._keys,u=a.length-1,_=0;_<=u;_++){var w=a[o?u-_:_];if(!1===s(i[w],w,this))return _+1}return _},ObjectSeq.prototype.__iterator=function(s,o){var i=this._object,a=this._keys,u=a.length-1,_=0;return new Iterator((function(){var w=a[o?u-_:_];return _++>u?iteratorDone():iteratorValue(s,w,i[w])}))},ObjectSeq.prototype[u]=!0,createClass(IterableSeq,IndexedSeq),IterableSeq.prototype.__iterateUncached=function(s,o){if(o)return this.cacheResult().__iterate(s,o);var i=getIterator(this._iterable),a=0;if(isIterator(i))for(var u;!(u=i.next()).done&&!1!==s(u.value,a++,this););return a},IterableSeq.prototype.__iteratorUncached=function(s,o){if(o)return this.cacheResult().__iterator(s,o);var i=getIterator(this._iterable);if(!isIterator(i))return new Iterator(iteratorDone);var a=0;return new Iterator((function(){var o=i.next();return o.done?o:iteratorValue(s,a++,o.value)}))},createClass(IteratorSeq,IndexedSeq),IteratorSeq.prototype.__iterateUncached=function(s,o){if(o)return this.cacheResult().__iterate(s,o);for(var i,a=this._iterator,u=this._iteratorCache,_=0;_=a.length){var o=i.next();if(o.done)return o;a[u]=o.value}return iteratorValue(s,u,a[u++])}))},createClass(Repeat,IndexedSeq),Repeat.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},Repeat.prototype.get=function(s,o){return this.has(s)?this._value:o},Repeat.prototype.includes=function(s){return is(this._value,s)},Repeat.prototype.slice=function(s,o){var i=this.size;return wholeSlice(s,o,i)?this:new Repeat(this._value,resolveEnd(o,i)-resolveBegin(s,i))},Repeat.prototype.reverse=function(){return this},Repeat.prototype.indexOf=function(s){return is(this._value,s)?0:-1},Repeat.prototype.lastIndexOf=function(s){return is(this._value,s)?this.size:-1},Repeat.prototype.__iterate=function(s,o){for(var i=0;i=0&&o=0&&ii?iteratorDone():iteratorValue(s,_++,w)}))},Range.prototype.equals=function(s){return s instanceof Range?this._start===s._start&&this._end===s._end&&this._step===s._step:deepEqual(this,s)},createClass(Collection,Iterable),createClass(KeyedCollection,Collection),createClass(IndexedCollection,Collection),createClass(SetCollection,Collection),Collection.Keyed=KeyedCollection,Collection.Indexed=IndexedCollection,Collection.Set=SetCollection;var le="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function imul(s,o){var i=65535&(s|=0),a=65535&(o|=0);return i*a+((s>>>16)*a+i*(o>>>16)<<16>>>0)|0};function smi(s){return s>>>1&1073741824|3221225471&s}function hash(s){if(!1===s||null==s)return 0;if("function"==typeof s.valueOf&&(!1===(s=s.valueOf())||null==s))return 0;if(!0===s)return 1;var o=typeof s;if("number"===o){if(s!=s||s===1/0)return 0;var i=0|s;for(i!==s&&(i^=4294967295*s);s>4294967295;)i^=s/=4294967295;return smi(i)}if("string"===o)return s.length>_e?cachedHashString(s):hashString(s);if("function"==typeof s.hashCode)return s.hashCode();if("object"===o)return hashJSObj(s);if("function"==typeof s.toString)return hashString(s.toString());throw new Error("Value type "+o+" cannot be hashed.")}function cachedHashString(s){var o=Pe[s];return void 0===o&&(o=hashString(s),xe===we&&(xe=0,Pe={}),xe++,Pe[s]=o),o}function hashString(s){for(var o=0,i=0;i0)switch(s.nodeType){case 1:return s.uniqueID;case 9:return s.documentElement&&s.documentElement.uniqueID}}var fe,ye="function"==typeof WeakMap;ye&&(fe=new WeakMap);var be=0,Se="__immutablehash__";"function"==typeof Symbol&&(Se=Symbol(Se));var _e=16,we=255,xe=0,Pe={};function assertNotInfinite(s){invariant(s!==1/0,"Cannot perform this action with an infinite size.")}function Map(s){return null==s?emptyMap():isMap(s)&&!isOrdered(s)?s:emptyMap().withMutations((function(o){var i=KeyedIterable(s);assertNotInfinite(i.size),i.forEach((function(s,i){return o.set(i,s)}))}))}function isMap(s){return!(!s||!s[Re])}createClass(Map,KeyedCollection),Map.of=function(){var o=s.call(arguments,0);return emptyMap().withMutations((function(s){for(var i=0;i=o.length)throw new Error("Missing value for key: "+o[i]);s.set(o[i],o[i+1])}}))},Map.prototype.toString=function(){return this.__toString("Map {","}")},Map.prototype.get=function(s,o){return this._root?this._root.get(0,void 0,s,o):o},Map.prototype.set=function(s,o){return updateMap(this,s,o)},Map.prototype.setIn=function(s,o){return this.updateIn(s,j,(function(){return o}))},Map.prototype.remove=function(s){return updateMap(this,s,j)},Map.prototype.deleteIn=function(s){return this.updateIn(s,(function(){return j}))},Map.prototype.update=function(s,o,i){return 1===arguments.length?s(this):this.updateIn([s],o,i)},Map.prototype.updateIn=function(s,o,i){i||(i=o,o=void 0);var a=updateInDeepMap(this,forceIterator(s),o,i);return a===j?void 0:a},Map.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):emptyMap()},Map.prototype.merge=function(){return mergeIntoMapWith(this,void 0,arguments)},Map.prototype.mergeWith=function(o){return mergeIntoMapWith(this,o,s.call(arguments,1))},Map.prototype.mergeIn=function(o){var i=s.call(arguments,1);return this.updateIn(o,emptyMap(),(function(s){return"function"==typeof s.merge?s.merge.apply(s,i):i[i.length-1]}))},Map.prototype.mergeDeep=function(){return mergeIntoMapWith(this,deepMerger,arguments)},Map.prototype.mergeDeepWith=function(o){var i=s.call(arguments,1);return mergeIntoMapWith(this,deepMergerWith(o),i)},Map.prototype.mergeDeepIn=function(o){var i=s.call(arguments,1);return this.updateIn(o,emptyMap(),(function(s){return"function"==typeof s.mergeDeep?s.mergeDeep.apply(s,i):i[i.length-1]}))},Map.prototype.sort=function(s){return OrderedMap(sortFactory(this,s))},Map.prototype.sortBy=function(s,o){return OrderedMap(sortFactory(this,o,s))},Map.prototype.withMutations=function(s){var o=this.asMutable();return s(o),o.wasAltered()?o.__ensureOwner(this.__ownerID):this},Map.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)},Map.prototype.asImmutable=function(){return this.__ensureOwner()},Map.prototype.wasAltered=function(){return this.__altered},Map.prototype.__iterator=function(s,o){return new MapIterator(this,s,o)},Map.prototype.__iterate=function(s,o){var i=this,a=0;return this._root&&this._root.iterate((function(o){return a++,s(o[1],o[0],i)}),o),a},Map.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeMap(this.size,this._root,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Map.isMap=isMap;var Te,Re="@@__IMMUTABLE_MAP__@@",$e=Map.prototype;function ArrayMapNode(s,o){this.ownerID=s,this.entries=o}function BitmapIndexedNode(s,o,i){this.ownerID=s,this.bitmap=o,this.nodes=i}function HashArrayMapNode(s,o,i){this.ownerID=s,this.count=o,this.nodes=i}function HashCollisionNode(s,o,i){this.ownerID=s,this.keyHash=o,this.entries=i}function ValueNode(s,o,i){this.ownerID=s,this.keyHash=o,this.entry=i}function MapIterator(s,o,i){this._type=o,this._reverse=i,this._stack=s._root&&mapIteratorFrame(s._root)}function mapIteratorValue(s,o){return iteratorValue(s,o[0],o[1])}function mapIteratorFrame(s,o){return{node:s,index:0,__prev:o}}function makeMap(s,o,i,a){var u=Object.create($e);return u.size=s,u._root=o,u.__ownerID=i,u.__hash=a,u.__altered=!1,u}function emptyMap(){return Te||(Te=makeMap(0))}function updateMap(s,o,i){var a,u;if(s._root){var _=MakeRef(L),w=MakeRef(B);if(a=updateNode(s._root,s.__ownerID,0,void 0,o,i,_,w),!w.value)return s;u=s.size+(_.value?i===j?-1:1:0)}else{if(i===j)return s;u=1,a=new ArrayMapNode(s.__ownerID,[[o,i]])}return s.__ownerID?(s.size=u,s._root=a,s.__hash=void 0,s.__altered=!0,s):a?makeMap(u,a):emptyMap()}function updateNode(s,o,i,a,u,_,w,x){return s?s.update(o,i,a,u,_,w,x):_===j?s:(SetRef(x),SetRef(w),new ValueNode(o,a,[u,_]))}function isLeafNode(s){return s.constructor===ValueNode||s.constructor===HashCollisionNode}function mergeIntoNode(s,o,i,a,u){if(s.keyHash===a)return new HashCollisionNode(o,a,[s.entry,u]);var _,x=(0===i?s.keyHash:s.keyHash>>>i)&C,j=(0===i?a:a>>>i)&C;return new BitmapIndexedNode(o,1<>>=1)w[C]=1&i?o[_++]:void 0;return w[a]=u,new HashArrayMapNode(s,_+1,w)}function mergeIntoMapWith(s,o,i){for(var a=[],u=0;u>1&1431655765))+(s>>2&858993459))+(s>>4)&252645135,s+=s>>8,127&(s+=s>>16)}function setIn(s,o,i,a){var u=a?s:arrCopy(s);return u[o]=i,u}function spliceIn(s,o,i,a){var u=s.length+1;if(a&&o+1===u)return s[o]=i,s;for(var _=new Array(u),w=0,x=0;x=qe)return createNodes(s,C,a,u);var U=s&&s===this.ownerID,V=U?C:arrCopy(C);return $?x?L===B-1?V.pop():V[L]=V.pop():V[L]=[a,u]:V.push([a,u]),U?(this.entries=V,this):new ArrayMapNode(s,V)}},BitmapIndexedNode.prototype.get=function(s,o,i,a){void 0===o&&(o=hash(i));var u=1<<((0===s?o:o>>>s)&C),_=this.bitmap;return _&u?this.nodes[popCount(_&u-1)].get(s+w,o,i,a):a},BitmapIndexedNode.prototype.update=function(s,o,i,a,u,_,x){void 0===i&&(i=hash(a));var L=(0===o?i:i>>>o)&C,B=1<=ze)return expandNodes(s,z,$,L,Z);if(U&&!Z&&2===z.length&&isLeafNode(z[1^V]))return z[1^V];if(U&&Z&&1===z.length&&isLeafNode(Z))return Z;var ee=s&&s===this.ownerID,ie=U?Z?$:$^B:$|B,ae=U?Z?setIn(z,V,Z,ee):spliceOut(z,V,ee):spliceIn(z,V,Z,ee);return ee?(this.bitmap=ie,this.nodes=ae,this):new BitmapIndexedNode(s,ie,ae)},HashArrayMapNode.prototype.get=function(s,o,i,a){void 0===o&&(o=hash(i));var u=(0===s?o:o>>>s)&C,_=this.nodes[u];return _?_.get(s+w,o,i,a):a},HashArrayMapNode.prototype.update=function(s,o,i,a,u,_,x){void 0===i&&(i=hash(a));var L=(0===o?i:i>>>o)&C,B=u===j,$=this.nodes,U=$[L];if(B&&!U)return this;var V=updateNode(U,s,o+w,i,a,u,_,x);if(V===U)return this;var z=this.count;if(U){if(!V&&--z0&&a=0&&s>>o&C;if(a>=this.array.length)return new VNode([],s);var u,_=0===a;if(o>0){var x=this.array[a];if((u=x&&x.removeBefore(s,o-w,i))===x&&_)return this}if(_&&!u)return this;var j=editableVNode(this,s);if(!_)for(var L=0;L>>o&C;if(u>=this.array.length)return this;if(o>0){var _=this.array[u];if((a=_&&_.removeAfter(s,o-w,i))===_&&u===this.array.length-1)return this}var x=editableVNode(this,s);return x.array.splice(u+1),a&&(x.array[u]=a),x};var Xe,Qe,et={};function iterateList(s,o){var i=s._origin,a=s._capacity,u=getTailOffset(a),_=s._tail;return iterateNodeOrLeaf(s._root,s._level,0);function iterateNodeOrLeaf(s,o,i){return 0===o?iterateLeaf(s,i):iterateNode(s,o,i)}function iterateLeaf(s,w){var C=w===u?_&&_.array:s&&s.array,j=w>i?0:i-w,L=a-w;return L>x&&(L=x),function(){if(j===L)return et;var s=o?--L:j++;return C&&C[s]}}function iterateNode(s,u,_){var C,j=s&&s.array,L=_>i?0:i-_>>u,B=1+(a-_>>u);return B>x&&(B=x),function(){for(;;){if(C){var s=C();if(s!==et)return s;C=null}if(L===B)return et;var i=o?--B:L++;C=iterateNodeOrLeaf(j&&j[i],u-w,_+(i<=s.size||o<0)return s.withMutations((function(s){o<0?setListBounds(s,o).set(0,i):setListBounds(s,0,o+1).set(o,i)}));o+=s._origin;var a=s._tail,u=s._root,_=MakeRef(B);return o>=getTailOffset(s._capacity)?a=updateVNode(a,s.__ownerID,0,o,i,_):u=updateVNode(u,s.__ownerID,s._level,o,i,_),_.value?s.__ownerID?(s._root=u,s._tail=a,s.__hash=void 0,s.__altered=!0,s):makeList(s._origin,s._capacity,s._level,u,a):s}function updateVNode(s,o,i,a,u,_){var x,j=a>>>i&C,L=s&&j0){var B=s&&s.array[j],$=updateVNode(B,o,i-w,a,u,_);return $===B?s:((x=editableVNode(s,o)).array[j]=$,x)}return L&&s.array[j]===u?s:(SetRef(_),x=editableVNode(s,o),void 0===u&&j===x.array.length-1?x.array.pop():x.array[j]=u,x)}function editableVNode(s,o){return o&&s&&o===s.ownerID?s:new VNode(s?s.array.slice():[],o)}function listNodeFor(s,o){if(o>=getTailOffset(s._capacity))return s._tail;if(o<1<0;)i=i.array[o>>>a&C],a-=w;return i}}function setListBounds(s,o,i){void 0!==o&&(o|=0),void 0!==i&&(i|=0);var a=s.__ownerID||new OwnerID,u=s._origin,_=s._capacity,x=u+o,j=void 0===i?_:i<0?_+i:u+i;if(x===u&&j===_)return s;if(x>=j)return s.clear();for(var L=s._level,B=s._root,$=0;x+$<0;)B=new VNode(B&&B.array.length?[void 0,B]:[],a),$+=1<<(L+=w);$&&(x+=$,u+=$,j+=$,_+=$);for(var U=getTailOffset(_),V=getTailOffset(j);V>=1<U?new VNode([],a):z;if(z&&V>U&&x<_&&z.array.length){for(var Z=B=editableVNode(B,a),ee=L;ee>w;ee-=w){var ie=U>>>ee&C;Z=Z.array[ie]=editableVNode(Z.array[ie],a)}Z.array[U>>>w&C]=z}if(j<_&&(Y=Y&&Y.removeAfter(a,0,j)),x>=V)x-=V,j-=V,L=w,B=null,Y=Y&&Y.removeBefore(a,0,x);else if(x>u||V>>L&C;if(ae!==V>>>L&C)break;ae&&($+=(1<u&&(B=B.removeBefore(a,L,x-$)),B&&Vu&&(u=x.size),isIterable(w)||(x=x.map((function(s){return fromJS(s)}))),a.push(x)}return u>s.size&&(s=s.setSize(u)),mergeIntoCollectionWith(s,o,a)}function getTailOffset(s){return s>>w<=x&&w.size>=2*_.size?(a=(u=w.filter((function(s,o){return void 0!==s&&C!==o}))).toKeyedSeq().map((function(s){return s[0]})).flip().toMap(),s.__ownerID&&(a.__ownerID=u.__ownerID=s.__ownerID)):(a=_.remove(o),u=C===w.size-1?w.pop():w.set(C,void 0))}else if(L){if(i===w.get(C)[1])return s;a=_,u=w.set(C,[o,i])}else a=_.set(o,w.size),u=w.set(w.size,[o,i]);return s.__ownerID?(s.size=a.size,s._map=a,s._list=u,s.__hash=void 0,s):makeOrderedMap(a,u)}function ToKeyedSequence(s,o){this._iter=s,this._useKeys=o,this.size=s.size}function ToIndexedSequence(s){this._iter=s,this.size=s.size}function ToSetSequence(s){this._iter=s,this.size=s.size}function FromEntriesSequence(s){this._iter=s,this.size=s.size}function flipFactory(s){var o=makeSequence(s);return o._iter=s,o.size=s.size,o.flip=function(){return s},o.reverse=function(){var o=s.reverse.apply(this);return o.flip=function(){return s.reverse()},o},o.has=function(o){return s.includes(o)},o.includes=function(o){return s.has(o)},o.cacheResult=cacheResultThrough,o.__iterateUncached=function(o,i){var a=this;return s.__iterate((function(s,i){return!1!==o(i,s,a)}),i)},o.__iteratorUncached=function(o,i){if(o===V){var a=s.__iterator(o,i);return new Iterator((function(){var s=a.next();if(!s.done){var o=s.value[0];s.value[0]=s.value[1],s.value[1]=o}return s}))}return s.__iterator(o===U?$:U,i)},o}function mapFactory(s,o,i){var a=makeSequence(s);return a.size=s.size,a.has=function(o){return s.has(o)},a.get=function(a,u){var _=s.get(a,j);return _===j?u:o.call(i,_,a,s)},a.__iterateUncached=function(a,u){var _=this;return s.__iterate((function(s,u,w){return!1!==a(o.call(i,s,u,w),u,_)}),u)},a.__iteratorUncached=function(a,u){var _=s.__iterator(V,u);return new Iterator((function(){var u=_.next();if(u.done)return u;var w=u.value,x=w[0];return iteratorValue(a,x,o.call(i,w[1],x,s),u)}))},a}function reverseFactory(s,o){var i=makeSequence(s);return i._iter=s,i.size=s.size,i.reverse=function(){return s},s.flip&&(i.flip=function(){var o=flipFactory(s);return o.reverse=function(){return s.flip()},o}),i.get=function(i,a){return s.get(o?i:-1-i,a)},i.has=function(i){return s.has(o?i:-1-i)},i.includes=function(o){return s.includes(o)},i.cacheResult=cacheResultThrough,i.__iterate=function(o,i){var a=this;return s.__iterate((function(s,i){return o(s,i,a)}),!i)},i.__iterator=function(o,i){return s.__iterator(o,!i)},i}function filterFactory(s,o,i,a){var u=makeSequence(s);return a&&(u.has=function(a){var u=s.get(a,j);return u!==j&&!!o.call(i,u,a,s)},u.get=function(a,u){var _=s.get(a,j);return _!==j&&o.call(i,_,a,s)?_:u}),u.__iterateUncached=function(u,_){var w=this,x=0;return s.__iterate((function(s,_,C){if(o.call(i,s,_,C))return x++,u(s,a?_:x-1,w)}),_),x},u.__iteratorUncached=function(u,_){var w=s.__iterator(V,_),x=0;return new Iterator((function(){for(;;){var _=w.next();if(_.done)return _;var C=_.value,j=C[0],L=C[1];if(o.call(i,L,j,s))return iteratorValue(u,a?j:x++,L,_)}}))},u}function countByFactory(s,o,i){var a=Map().asMutable();return s.__iterate((function(u,_){a.update(o.call(i,u,_,s),0,(function(s){return s+1}))})),a.asImmutable()}function groupByFactory(s,o,i){var a=isKeyed(s),u=(isOrdered(s)?OrderedMap():Map()).asMutable();s.__iterate((function(_,w){u.update(o.call(i,_,w,s),(function(s){return(s=s||[]).push(a?[w,_]:_),s}))}));var _=iterableClass(s);return u.map((function(o){return reify(s,_(o))}))}function sliceFactory(s,o,i,a){var u=s.size;if(void 0!==o&&(o|=0),void 0!==i&&(i===1/0?i=u:i|=0),wholeSlice(o,i,u))return s;var _=resolveBegin(o,u),w=resolveEnd(i,u);if(_!=_||w!=w)return sliceFactory(s.toSeq().cacheResult(),o,i,a);var x,C=w-_;C==C&&(x=C<0?0:C);var j=makeSequence(s);return j.size=0===x?x:s.size&&x||void 0,!a&&isSeq(s)&&x>=0&&(j.get=function(o,i){return(o=wrapIndex(this,o))>=0&&ox)return iteratorDone();var s=u.next();return a||o===U?s:iteratorValue(o,C-1,o===$?void 0:s.value[1],s)}))},j}function takeWhileFactory(s,o,i){var a=makeSequence(s);return a.__iterateUncached=function(a,u){var _=this;if(u)return this.cacheResult().__iterate(a,u);var w=0;return s.__iterate((function(s,u,x){return o.call(i,s,u,x)&&++w&&a(s,u,_)})),w},a.__iteratorUncached=function(a,u){var _=this;if(u)return this.cacheResult().__iterator(a,u);var w=s.__iterator(V,u),x=!0;return new Iterator((function(){if(!x)return iteratorDone();var s=w.next();if(s.done)return s;var u=s.value,C=u[0],j=u[1];return o.call(i,j,C,_)?a===V?s:iteratorValue(a,C,j,s):(x=!1,iteratorDone())}))},a}function skipWhileFactory(s,o,i,a){var u=makeSequence(s);return u.__iterateUncached=function(u,_){var w=this;if(_)return this.cacheResult().__iterate(u,_);var x=!0,C=0;return s.__iterate((function(s,_,j){if(!x||!(x=o.call(i,s,_,j)))return C++,u(s,a?_:C-1,w)})),C},u.__iteratorUncached=function(u,_){var w=this;if(_)return this.cacheResult().__iterator(u,_);var x=s.__iterator(V,_),C=!0,j=0;return new Iterator((function(){var s,_,L;do{if((s=x.next()).done)return a||u===U?s:iteratorValue(u,j++,u===$?void 0:s.value[1],s);var B=s.value;_=B[0],L=B[1],C&&(C=o.call(i,L,_,w))}while(C);return u===V?s:iteratorValue(u,_,L,s)}))},u}function concatFactory(s,o){var i=isKeyed(s),a=[s].concat(o).map((function(s){return isIterable(s)?i&&(s=KeyedIterable(s)):s=i?keyedSeqFromValue(s):indexedSeqFromValue(Array.isArray(s)?s:[s]),s})).filter((function(s){return 0!==s.size}));if(0===a.length)return s;if(1===a.length){var u=a[0];if(u===s||i&&isKeyed(u)||isIndexed(s)&&isIndexed(u))return u}var _=new ArraySeq(a);return i?_=_.toKeyedSeq():isIndexed(s)||(_=_.toSetSeq()),(_=_.flatten(!0)).size=a.reduce((function(s,o){if(void 0!==s){var i=o.size;if(void 0!==i)return s+i}}),0),_}function flattenFactory(s,o,i){var a=makeSequence(s);return a.__iterateUncached=function(a,u){var _=0,w=!1;function flatDeep(s,x){var C=this;s.__iterate((function(s,u){return(!o||x0}function zipWithFactory(s,o,i){var a=makeSequence(s);return a.size=new ArraySeq(i).map((function(s){return s.size})).min(),a.__iterate=function(s,o){for(var i,a=this.__iterator(U,o),u=0;!(i=a.next()).done&&!1!==s(i.value,u++,this););return u},a.__iteratorUncached=function(s,a){var u=i.map((function(s){return s=Iterable(s),getIterator(a?s.reverse():s)})),_=0,w=!1;return new Iterator((function(){var i;return w||(i=u.map((function(s){return s.next()})),w=i.some((function(s){return s.done}))),w?iteratorDone():iteratorValue(s,_++,o.apply(null,i.map((function(s){return s.value}))))}))},a}function reify(s,o){return isSeq(s)?o:s.constructor(o)}function validateEntry(s){if(s!==Object(s))throw new TypeError("Expected [K, V] tuple: "+s)}function resolveSize(s){return assertNotInfinite(s.size),ensureSize(s)}function iterableClass(s){return isKeyed(s)?KeyedIterable:isIndexed(s)?IndexedIterable:SetIterable}function makeSequence(s){return Object.create((isKeyed(s)?KeyedSeq:isIndexed(s)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Seq.prototype.cacheResult.call(this)}function defaultComparator(s,o){return s>o?1:s=0;i--)o={value:arguments[i],next:o};return this.__ownerID?(this.size=s,this._head=o,this.__hash=void 0,this.__altered=!0,this):makeStack(s,o)},Stack.prototype.pushAll=function(s){if(0===(s=IndexedIterable(s)).size)return this;assertNotInfinite(s.size);var o=this.size,i=this._head;return s.reverse().forEach((function(s){o++,i={value:s,next:i}})),this.__ownerID?(this.size=o,this._head=i,this.__hash=void 0,this.__altered=!0,this):makeStack(o,i)},Stack.prototype.pop=function(){return this.slice(1)},Stack.prototype.unshift=function(){return this.push.apply(this,arguments)},Stack.prototype.unshiftAll=function(s){return this.pushAll(s)},Stack.prototype.shift=function(){return this.pop.apply(this,arguments)},Stack.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):emptyStack()},Stack.prototype.slice=function(s,o){if(wholeSlice(s,o,this.size))return this;var i=resolveBegin(s,this.size);if(resolveEnd(o,this.size)!==this.size)return IndexedCollection.prototype.slice.call(this,s,o);for(var a=this.size-i,u=this._head;i--;)u=u.next;return this.__ownerID?(this.size=a,this._head=u,this.__hash=void 0,this.__altered=!0,this):makeStack(a,u)},Stack.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeStack(this.size,this._head,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Stack.prototype.__iterate=function(s,o){if(o)return this.reverse().__iterate(s);for(var i=0,a=this._head;a&&!1!==s(a.value,i++,this);)a=a.next;return i},Stack.prototype.__iterator=function(s,o){if(o)return this.reverse().__iterator(s);var i=0,a=this._head;return new Iterator((function(){if(a){var o=a.value;return a=a.next,iteratorValue(s,i++,o)}return iteratorDone()}))},Stack.isStack=isStack;var at,ct="@@__IMMUTABLE_STACK__@@",lt=Stack.prototype;function makeStack(s,o,i,a){var u=Object.create(lt);return u.size=s,u._head=o,u.__ownerID=i,u.__hash=a,u.__altered=!1,u}function emptyStack(){return at||(at=makeStack(0))}function mixin(s,o){var keyCopier=function(i){s.prototype[i]=o[i]};return Object.keys(o).forEach(keyCopier),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(o).forEach(keyCopier),s}function isProtoKey(s){return"string"==typeof s&&("__proto__"===s||"constructor"===s)}lt[ct]=!0,lt.withMutations=$e.withMutations,lt.asMutable=$e.asMutable,lt.asImmutable=$e.asImmutable,lt.wasAltered=$e.wasAltered,Iterable.Iterator=Iterator,mixin(Iterable,{toArray:function(){assertNotInfinite(this.size);var s=new Array(this.size||0);return this.valueSeq().__iterate((function(o,i){s[i]=o})),s},toIndexedSeq:function(){return new ToIndexedSequence(this)},toJS:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJS?s.toJS():s})).__toJS()},toJSON:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJSON?s.toJSON():s})).__toJS()},toKeyedSeq:function(){return new ToKeyedSequence(this,!0)},toMap:function(){return Map(this.toKeyedSeq())},toObject:function(){assertNotInfinite(this.size);var s={};return this.__iterate((function(o,i){isProtoKey(i)||(s[i]=o)})),s},toOrderedMap:function(){return OrderedMap(this.toKeyedSeq())},toOrderedSet:function(){return OrderedSet(isKeyed(this)?this.valueSeq():this)},toSet:function(){return Set(isKeyed(this)?this.valueSeq():this)},toSetSeq:function(){return new ToSetSequence(this)},toSeq:function(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Stack(isKeyed(this)?this.valueSeq():this)},toList:function(){return List(isKeyed(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(s,o){return 0===this.size?s+o:s+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+o},concat:function(){return reify(this,concatFactory(this,s.call(arguments,0)))},includes:function(s){return this.some((function(o){return is(o,s)}))},entries:function(){return this.__iterator(V)},every:function(s,o){assertNotInfinite(this.size);var i=!0;return this.__iterate((function(a,u,_){if(!s.call(o,a,u,_))return i=!1,!1})),i},filter:function(s,o){return reify(this,filterFactory(this,s,o,!0))},find:function(s,o,i){var a=this.findEntry(s,o);return a?a[1]:i},forEach:function(s,o){return assertNotInfinite(this.size),this.__iterate(o?s.bind(o):s)},join:function(s){assertNotInfinite(this.size),s=void 0!==s?""+s:",";var o="",i=!0;return this.__iterate((function(a){i?i=!1:o+=s,o+=null!=a?a.toString():""})),o},keys:function(){return this.__iterator($)},map:function(s,o){return reify(this,mapFactory(this,s,o))},reduce:function(s,o,i){var a,u;return assertNotInfinite(this.size),arguments.length<2?u=!0:a=o,this.__iterate((function(o,_,w){u?(u=!1,a=o):a=s.call(i,a,o,_,w)})),a},reduceRight:function(s,o,i){var a=this.toKeyedSeq().reverse();return a.reduce.apply(a,arguments)},reverse:function(){return reify(this,reverseFactory(this,!0))},slice:function(s,o){return reify(this,sliceFactory(this,s,o,!0))},some:function(s,o){return!this.every(not(s),o)},sort:function(s){return reify(this,sortFactory(this,s))},values:function(){return this.__iterator(U)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some((function(){return!0}))},count:function(s,o){return ensureSize(s?this.toSeq().filter(s,o):this)},countBy:function(s,o){return countByFactory(this,s,o)},equals:function(s){return deepEqual(this,s)},entrySeq:function(){var s=this;if(s._cache)return new ArraySeq(s._cache);var o=s.toSeq().map(entryMapper).toIndexedSeq();return o.fromEntrySeq=function(){return s.toSeq()},o},filterNot:function(s,o){return this.filter(not(s),o)},findEntry:function(s,o,i){var a=i;return this.__iterate((function(i,u,_){if(s.call(o,i,u,_))return a=[u,i],!1})),a},findKey:function(s,o){var i=this.findEntry(s,o);return i&&i[0]},findLast:function(s,o,i){return this.toKeyedSeq().reverse().find(s,o,i)},findLastEntry:function(s,o,i){return this.toKeyedSeq().reverse().findEntry(s,o,i)},findLastKey:function(s,o){return this.toKeyedSeq().reverse().findKey(s,o)},first:function(){return this.find(returnTrue)},flatMap:function(s,o){return reify(this,flatMapFactory(this,s,o))},flatten:function(s){return reify(this,flattenFactory(this,s,!0))},fromEntrySeq:function(){return new FromEntriesSequence(this)},get:function(s,o){return this.find((function(o,i){return is(i,s)}),void 0,o)},getIn:function(s,o){for(var i,a=this,u=forceIterator(s);!(i=u.next()).done;){var _=i.value;if((a=a&&a.get?a.get(_,j):j)===j)return o}return a},groupBy:function(s,o){return groupByFactory(this,s,o)},has:function(s){return this.get(s,j)!==j},hasIn:function(s){return this.getIn(s,j)!==j},isSubset:function(s){return s="function"==typeof s.includes?s:Iterable(s),this.every((function(o){return s.includes(o)}))},isSuperset:function(s){return(s="function"==typeof s.isSubset?s:Iterable(s)).isSubset(this)},keyOf:function(s){return this.findKey((function(o){return is(o,s)}))},keySeq:function(){return this.toSeq().map(keyMapper).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(s){return this.toKeyedSeq().reverse().keyOf(s)},max:function(s){return maxFactory(this,s)},maxBy:function(s,o){return maxFactory(this,o,s)},min:function(s){return maxFactory(this,s?neg(s):defaultNegComparator)},minBy:function(s,o){return maxFactory(this,o?neg(o):defaultNegComparator,s)},rest:function(){return this.slice(1)},skip:function(s){return this.slice(Math.max(0,s))},skipLast:function(s){return reify(this,this.toSeq().reverse().skip(s).reverse())},skipWhile:function(s,o){return reify(this,skipWhileFactory(this,s,o,!0))},skipUntil:function(s,o){return this.skipWhile(not(s),o)},sortBy:function(s,o){return reify(this,sortFactory(this,o,s))},take:function(s){return this.slice(0,Math.max(0,s))},takeLast:function(s){return reify(this,this.toSeq().reverse().take(s).reverse())},takeWhile:function(s,o){return reify(this,takeWhileFactory(this,s,o))},takeUntil:function(s,o){return this.takeWhile(not(s),o)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=hashIterable(this))}});var ut=Iterable.prototype;ut[o]=!0,ut[Z]=ut.values,ut.__toJS=ut.toArray,ut.__toStringMapper=quoteString,ut.inspect=ut.toSource=function(){return this.toString()},ut.chain=ut.flatMap,ut.contains=ut.includes,mixin(KeyedIterable,{flip:function(){return reify(this,flipFactory(this))},mapEntries:function(s,o){var i=this,a=0;return reify(this,this.toSeq().map((function(u,_){return s.call(o,[_,u],a++,i)})).fromEntrySeq())},mapKeys:function(s,o){var i=this;return reify(this,this.toSeq().flip().map((function(a,u){return s.call(o,a,u,i)})).flip())}});var pt=KeyedIterable.prototype;function keyMapper(s,o){return o}function entryMapper(s,o){return[o,s]}function not(s){return function(){return!s.apply(this,arguments)}}function neg(s){return function(){return-s.apply(this,arguments)}}function quoteString(s){return"string"==typeof s?JSON.stringify(s):String(s)}function defaultZipper(){return arrCopy(arguments)}function defaultNegComparator(s,o){return so?-1:0}function hashIterable(s){if(s.size===1/0)return 0;var o=isOrdered(s),i=isKeyed(s),a=o?1:0;return murmurHashOfSize(s.__iterate(i?o?function(s,o){a=31*a+hashMerge(hash(s),hash(o))|0}:function(s,o){a=a+hashMerge(hash(s),hash(o))|0}:o?function(s){a=31*a+hash(s)|0}:function(s){a=a+hash(s)|0}),a)}function murmurHashOfSize(s,o){return o=le(o,3432918353),o=le(o<<15|o>>>-15,461845907),o=le(o<<13|o>>>-13,5),o=le((o=o+3864292196^s)^o>>>16,2246822507),o=smi((o=le(o^o>>>13,3266489909))^o>>>16)}function hashMerge(s,o){return s^o+2654435769+(s<<6)+(s>>2)}return pt[i]=!0,pt[Z]=ut.entries,pt.__toJS=ut.toObject,pt.__toStringMapper=function(s,o){return JSON.stringify(o)+": "+quoteString(s)},mixin(IndexedIterable,{toKeyedSeq:function(){return new ToKeyedSequence(this,!1)},filter:function(s,o){return reify(this,filterFactory(this,s,o,!1))},findIndex:function(s,o){var i=this.findEntry(s,o);return i?i[0]:-1},indexOf:function(s){var o=this.keyOf(s);return void 0===o?-1:o},lastIndexOf:function(s){var o=this.lastKeyOf(s);return void 0===o?-1:o},reverse:function(){return reify(this,reverseFactory(this,!1))},slice:function(s,o){return reify(this,sliceFactory(this,s,o,!1))},splice:function(s,o){var i=arguments.length;if(o=Math.max(0|o,0),0===i||2===i&&!o)return this;s=resolveBegin(s,s<0?this.count():this.size);var a=this.slice(0,s);return reify(this,1===i?a:a.concat(arrCopy(arguments,2),this.slice(s+o)))},findLastIndex:function(s,o){var i=this.findLastEntry(s,o);return i?i[0]:-1},first:function(){return this.get(0)},flatten:function(s){return reify(this,flattenFactory(this,s,!1))},get:function(s,o){return(s=wrapIndex(this,s))<0||this.size===1/0||void 0!==this.size&&s>this.size?o:this.find((function(o,i){return i===s}),void 0,o)},has:function(s){return(s=wrapIndex(this,s))>=0&&(void 0!==this.size?this.size===1/0||s=o||i<0||B&&s-j>=_}function timerExpired(){var s=now();if(shouldInvoke(s))return trailingEdge(s);x=setTimeout(timerExpired,function remainingWait(s){var i=o-(s-C);return B?U(i,_-(s-j)):i}(s))}function trailingEdge(s){return x=void 0,V&&a?invokeFunc(s):(a=u=void 0,w)}function debounced(){var s=now(),i=shouldInvoke(s);if(a=arguments,u=this,C=s,i){if(void 0===x)return function leadingEdge(s){return j=s,x=setTimeout(timerExpired,o),L?invokeFunc(s):w}(C);if(B)return x=setTimeout(timerExpired,o),invokeFunc(C)}return void 0===x&&(x=setTimeout(timerExpired,o)),w}return o=toNumber(o)||0,isObject(i)&&(L=!!i.leading,_=(B="maxWait"in i)?$(toNumber(i.maxWait)||0,o):_,V="trailing"in i?!!i.trailing:V),debounced.cancel=function cancel(){void 0!==x&&clearTimeout(x),j=0,a=C=u=x=void 0},debounced.flush=function flush(){return void 0===x?w:trailingEdge(now())},debounced}},55580(s,o,i){var a=i(56110)(i(9325),"DataView");s.exports=a},21549(s,o,i){var a=i(22032),u=i(63862),_=i(66721),w=i(12749),x=i(35749);function Hash(s){var o=-1,i=null==s?0:s.length;for(this.clear();++o-1}},70695(s,o,i){var a=i(78096),u=i(72428),_=i(56449),w=i(3656),x=i(30361),C=i(37167),j=Object.prototype.hasOwnProperty;s.exports=function arrayLikeKeys(s,o){var i=_(s),L=!i&&u(s),B=!i&&!L&&w(s),$=!i&&!L&&!B&&C(s),U=i||L||B||$,V=U?a(s.length,String):[],z=V.length;for(var Y in s)!o&&!j.call(s,Y)||U&&("length"==Y||B&&("offset"==Y||"parent"==Y)||$&&("buffer"==Y||"byteLength"==Y||"byteOffset"==Y)||x(Y,z))||V.push(Y);return V}},34932(s){s.exports=function arrayMap(s,o){for(var i=-1,a=null==s?0:s.length,u=Array(a);++i0&&i(j)?o>1?baseFlatten(j,o-1,i,_,w):a(w,j):_||(w[w.length]=j)}return w}},86649(s,o,i){var a=i(83221)();s.exports=a},30641(s,o,i){var a=i(86649),u=i(95950);s.exports=function baseForOwn(s,o){return s&&a(s,o,u)}},47422(s,o,i){var a=i(31769),u=i(77797);s.exports=function baseGet(s,o){for(var i=0,_=(o=a(o,s)).length;null!=s&&i<_;)s=s[u(o[i++])];return i&&i==_?s:void 0}},82199(s,o,i){var a=i(14528),u=i(56449);s.exports=function baseGetAllKeys(s,o,i){var _=o(s);return u(s)?_:a(_,i(s))}},72552(s,o,i){var a=i(51873),u=i(659),_=i(59350),w=a?a.toStringTag:void 0;s.exports=function baseGetTag(s){return null==s?void 0===s?"[object Undefined]":"[object Null]":w&&w in Object(s)?u(s):_(s)}},20426(s){var o=Object.prototype.hasOwnProperty;s.exports=function baseHas(s,i){return null!=s&&o.call(s,i)}},28077(s){s.exports=function baseHasIn(s,o){return null!=s&&o in Object(s)}},96131(s,o,i){var a=i(2523),u=i(85463),_=i(76959);s.exports=function baseIndexOf(s,o,i){return o==o?_(s,o,i):a(s,u,i)}},27534(s,o,i){var a=i(72552),u=i(40346);s.exports=function baseIsArguments(s){return u(s)&&"[object Arguments]"==a(s)}},60270(s,o,i){var a=i(87068),u=i(40346);s.exports=function baseIsEqual(s,o,i,_,w){return s===o||(null==s||null==o||!u(s)&&!u(o)?s!=s&&o!=o:a(s,o,i,_,baseIsEqual,w))}},87068(s,o,i){var a=i(37217),u=i(25911),_=i(21986),w=i(50689),x=i(5861),C=i(56449),j=i(3656),L=i(37167),B="[object Arguments]",$="[object Array]",U="[object Object]",V=Object.prototype.hasOwnProperty;s.exports=function baseIsEqualDeep(s,o,i,z,Y,Z){var ee=C(s),ie=C(o),ae=ee?$:x(s),ce=ie?$:x(o),le=(ae=ae==B?U:ae)==U,pe=(ce=ce==B?U:ce)==U,de=ae==ce;if(de&&j(s)){if(!j(o))return!1;ee=!0,le=!1}if(de&&!le)return Z||(Z=new a),ee||L(s)?u(s,o,i,z,Y,Z):_(s,o,ae,i,z,Y,Z);if(!(1&i)){var fe=le&&V.call(s,"__wrapped__"),ye=pe&&V.call(o,"__wrapped__");if(fe||ye){var be=fe?s.value():s,Se=ye?o.value():o;return Z||(Z=new a),Y(be,Se,i,z,Z)}}return!!de&&(Z||(Z=new a),w(s,o,i,z,Y,Z))}},29172(s,o,i){var a=i(5861),u=i(40346);s.exports=function baseIsMap(s){return u(s)&&"[object Map]"==a(s)}},41799(s,o,i){var a=i(37217),u=i(60270);s.exports=function baseIsMatch(s,o,i,_){var w=i.length,x=w,C=!_;if(null==s)return!x;for(s=Object(s);w--;){var j=i[w];if(C&&j[2]?j[1]!==s[j[0]]:!(j[0]in s))return!1}for(;++wu?0:u+o),(i=i>u?u:i)<0&&(i+=u),u=o>i?0:i-o>>>0,o>>>=0;for(var _=Array(u);++a=u?s:a(s,o,i)}},49653(s,o,i){var a=i(37828);s.exports=function cloneArrayBuffer(s){var o=new s.constructor(s.byteLength);return new a(o).set(new a(s)),o}},93290(s,o,i){s=i.nmd(s);var a=i(9325),u=o&&!o.nodeType&&o,_=u&&s&&!s.nodeType&&s,w=_&&_.exports===u?a.Buffer:void 0,x=w?w.allocUnsafe:void 0;s.exports=function cloneBuffer(s,o){if(o)return s.slice();var i=s.length,a=x?x(i):new s.constructor(i);return s.copy(a),a}},76169(s,o,i){var a=i(49653);s.exports=function cloneDataView(s,o){var i=o?a(s.buffer):s.buffer;return new s.constructor(i,s.byteOffset,s.byteLength)}},73201(s){var o=/\w*$/;s.exports=function cloneRegExp(s){var i=new s.constructor(s.source,o.exec(s));return i.lastIndex=s.lastIndex,i}},93736(s,o,i){var a=i(51873),u=a?a.prototype:void 0,_=u?u.valueOf:void 0;s.exports=function cloneSymbol(s){return _?Object(_.call(s)):{}}},71961(s,o,i){var a=i(49653);s.exports=function cloneTypedArray(s,o){var i=o?a(s.buffer):s.buffer;return new s.constructor(i,s.byteOffset,s.length)}},91596(s){var o=Math.max;s.exports=function composeArgs(s,i,a,u){for(var _=-1,w=s.length,x=a.length,C=-1,j=i.length,L=o(w-x,0),B=Array(j+L),$=!u;++C1?i[_-1]:void 0,x=_>2?i[2]:void 0;for(w=s.length>3&&"function"==typeof w?(_--,w):void 0,x&&u(i[0],i[1],x)&&(w=_<3?void 0:w,_=1),o=Object(o);++a<_;){var C=i[a];C&&s(o,C,a,w)}return o}))}},38329(s,o,i){var a=i(64894);s.exports=function createBaseEach(s,o){return function(i,u){if(null==i)return i;if(!a(i))return s(i,u);for(var _=i.length,w=o?_:-1,x=Object(i);(o?w--:++w<_)&&!1!==u(x[w],w,x););return i}}},83221(s){s.exports=function createBaseFor(s){return function(o,i,a){for(var u=-1,_=Object(o),w=a(o),x=w.length;x--;){var C=w[s?x:++u];if(!1===i(_[C],C,_))break}return o}}},11842(s,o,i){var a=i(82819),u=i(9325);s.exports=function createBind(s,o,i){var _=1&o,w=a(s);return function wrapper(){return(this&&this!==u&&this instanceof wrapper?w:s).apply(_?i:this,arguments)}}},12507(s,o,i){var a=i(28754),u=i(49698),_=i(63912),w=i(13222);s.exports=function createCaseFirst(s){return function(o){o=w(o);var i=u(o)?_(o):void 0,x=i?i[0]:o.charAt(0),C=i?a(i,1).join(""):o.slice(1);return x[s]()+C}}},45539(s,o,i){var a=i(40882),u=i(50828),_=i(66645),w=RegExp("['’]","g");s.exports=function createCompounder(s){return function(o){return a(_(u(o).replace(w,"")),s,"")}}},82819(s,o,i){var a=i(39344),u=i(23805);s.exports=function createCtor(s){return function(){var o=arguments;switch(o.length){case 0:return new s;case 1:return new s(o[0]);case 2:return new s(o[0],o[1]);case 3:return new s(o[0],o[1],o[2]);case 4:return new s(o[0],o[1],o[2],o[3]);case 5:return new s(o[0],o[1],o[2],o[3],o[4]);case 6:return new s(o[0],o[1],o[2],o[3],o[4],o[5]);case 7:return new s(o[0],o[1],o[2],o[3],o[4],o[5],o[6])}var i=a(s.prototype),_=s.apply(i,o);return u(_)?_:i}}},77078(s,o,i){var a=i(91033),u=i(82819),_=i(37471),w=i(18073),x=i(11287),C=i(36306),j=i(9325);s.exports=function createCurry(s,o,i){var L=u(s);return function wrapper(){for(var u=arguments.length,B=Array(u),$=u,U=x(wrapper);$--;)B[$]=arguments[$];var V=u<3&&B[0]!==U&&B[u-1]!==U?[]:C(B,U);return(u-=V.length)-1?x[C?o[j]:j]:void 0}}},37471(s,o,i){var a=i(91596),u=i(53320),_=i(58523),w=i(82819),x=i(18073),C=i(11287),j=i(68294),L=i(36306),B=i(9325);s.exports=function createHybrid(s,o,i,$,U,V,z,Y,Z,ee){var ie=128&o,ae=1&o,ce=2&o,le=24&o,pe=512&o,de=ce?void 0:w(s);return function wrapper(){for(var fe=arguments.length,ye=Array(fe),be=fe;be--;)ye[be]=arguments[be];if(le)var Se=C(wrapper),_e=_(ye,Se);if($&&(ye=a(ye,$,U,le)),V&&(ye=u(ye,V,z,le)),fe-=_e,le&&fe1&&ye.reverse(),ie&&ZL))return!1;var $=C.get(s),U=C.get(o);if($&&U)return $==o&&U==s;var V=-1,z=!0,Y=2&i?new a:void 0;for(C.set(s,o),C.set(o,s);++V1?"& ":"")+i[u],i=i.join(a>2?", ":" "),s.replace(o,"{\n/* [wrapped with "+i+"] */\n")}},45891(s,o,i){var a=i(51873),u=i(72428),_=i(56449),w=a?a.isConcatSpreadable:void 0;s.exports=function isFlattenable(s){return _(s)||u(s)||!!(w&&s&&s[w])}},30361(s){var o=/^(?:0|[1-9]\d*)$/;s.exports=function isIndex(s,i){var a=typeof s;return!!(i=null==i?9007199254740991:i)&&("number"==a||"symbol"!=a&&o.test(s))&&s>-1&&s%1==0&&s-1}},31175(s,o,i){var a=i(26025);s.exports=function listCacheSet(s,o){var i=this.__data__,u=a(i,s);return u<0?(++this.size,i.push([s,o])):i[u][1]=o,this}},63040(s,o,i){var a=i(21549),u=i(80079),_=i(68223);s.exports=function mapCacheClear(){this.size=0,this.__data__={hash:new a,map:new(_||u),string:new a}}},17670(s,o,i){var a=i(12651);s.exports=function mapCacheDelete(s){var o=a(this,s).delete(s);return this.size-=o?1:0,o}},90289(s,o,i){var a=i(12651);s.exports=function mapCacheGet(s){return a(this,s).get(s)}},4509(s,o,i){var a=i(12651);s.exports=function mapCacheHas(s){return a(this,s).has(s)}},72949(s,o,i){var a=i(12651);s.exports=function mapCacheSet(s,o){var i=a(this,s),u=i.size;return i.set(s,o),this.size+=i.size==u?0:1,this}},20317(s){s.exports=function mapToArray(s){var o=-1,i=Array(s.size);return s.forEach((function(s,a){i[++o]=[a,s]})),i}},67197(s){s.exports=function matchesStrictComparable(s,o){return function(i){return null!=i&&(i[s]===o&&(void 0!==o||s in Object(i)))}}},62224(s,o,i){var a=i(50104);s.exports=function memoizeCapped(s){var o=a(s,(function(s){return 500===i.size&&i.clear(),s})),i=o.cache;return o}},3209(s,o,i){var a=i(91596),u=i(53320),_=i(36306),w="__lodash_placeholder__",x=128,C=Math.min;s.exports=function mergeData(s,o){var i=s[1],j=o[1],L=i|j,B=L<131,$=j==x&&8==i||j==x&&256==i&&s[7].length<=o[8]||384==j&&o[7].length<=o[8]&&8==i;if(!B&&!$)return s;1&j&&(s[2]=o[2],L|=1&i?0:4);var U=o[3];if(U){var V=s[3];s[3]=V?a(V,U,o[4]):U,s[4]=V?_(s[3],w):o[4]}return(U=o[5])&&(V=s[5],s[5]=V?u(V,U,o[6]):U,s[6]=V?_(s[5],w):o[6]),(U=o[7])&&(s[7]=U),j&x&&(s[8]=null==s[8]?o[8]:C(s[8],o[8])),null==s[9]&&(s[9]=o[9]),s[0]=o[0],s[1]=L,s}},48152(s,o,i){var a=i(28303),u=a&&new a;s.exports=u},81042(s,o,i){var a=i(56110)(Object,"create");s.exports=a},3650(s,o,i){var a=i(74335)(Object.keys,Object);s.exports=a},90181(s){s.exports=function nativeKeysIn(s){var o=[];if(null!=s)for(var i in Object(s))o.push(i);return o}},86009(s,o,i){s=i.nmd(s);var a=i(34840),u=o&&!o.nodeType&&o,_=u&&s&&!s.nodeType&&s,w=_&&_.exports===u&&a.process,x=function(){try{var s=_&&_.require&&_.require("util").types;return s||w&&w.binding&&w.binding("util")}catch(s){}}();s.exports=x},59350(s){var o=Object.prototype.toString;s.exports=function objectToString(s){return o.call(s)}},74335(s){s.exports=function overArg(s,o){return function(i){return s(o(i))}}},56757(s,o,i){var a=i(91033),u=Math.max;s.exports=function overRest(s,o,i){return o=u(void 0===o?s.length-1:o,0),function(){for(var _=arguments,w=-1,x=u(_.length-o,0),C=Array(x);++w0){if(++i>=800)return arguments[0]}else i=0;return s.apply(void 0,arguments)}}},51420(s,o,i){var a=i(80079);s.exports=function stackClear(){this.__data__=new a,this.size=0}},90938(s){s.exports=function stackDelete(s){var o=this.__data__,i=o.delete(s);return this.size=o.size,i}},63605(s){s.exports=function stackGet(s){return this.__data__.get(s)}},29817(s){s.exports=function stackHas(s){return this.__data__.has(s)}},80945(s,o,i){var a=i(80079),u=i(68223),_=i(53661);s.exports=function stackSet(s,o){var i=this.__data__;if(i instanceof a){var w=i.__data__;if(!u||w.length<199)return w.push([s,o]),this.size=++i.size,this;i=this.__data__=new _(w)}return i.set(s,o),this.size=i.size,this}},76959(s){s.exports=function strictIndexOf(s,o,i){for(var a=i-1,u=s.length;++a=o||i<0||Y&&s-V>=L}function timerExpired(){var s=u();if(shouldInvoke(s))return trailingEdge(s);$=setTimeout(timerExpired,function remainingWait(s){var i=o-(s-U);return Y?x(i,L-(s-V)):i}(s))}function trailingEdge(s){return $=void 0,Z&&C?invokeFunc(s):(C=j=void 0,B)}function debounced(){var s=u(),i=shouldInvoke(s);if(C=arguments,j=this,U=s,i){if(void 0===$)return function leadingEdge(s){return V=s,$=setTimeout(timerExpired,o),z?invokeFunc(s):B}(U);if(Y)return clearTimeout($),$=setTimeout(timerExpired,o),invokeFunc(U)}return void 0===$&&($=setTimeout(timerExpired,o)),B}return o=_(o)||0,a(i)&&(z=!!i.leading,L=(Y="maxWait"in i)?w(_(i.maxWait)||0,o):L,Z="trailing"in i?!!i.trailing:Z),debounced.cancel=function cancel(){void 0!==$&&clearTimeout($),V=0,C=U=j=$=void 0},debounced.flush=function flush(){return void 0===$?B:trailingEdge(u())},debounced}},50828(s,o,i){var a=i(24647),u=i(13222),_=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,w=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");s.exports=function deburr(s){return(s=u(s))&&s.replace(_,a).replace(w,"")}},75288(s){s.exports=function eq(s,o){return s===o||s!=s&&o!=o}},60680(s,o,i){var a=i(13222),u=/[\\^$.*+?()[\]{}|]/g,_=RegExp(u.source);s.exports=function escapeRegExp(s){return(s=a(s))&&_.test(s)?s.replace(u,"\\$&"):s}},7309(s,o,i){var a=i(62006)(i(24713));s.exports=a},24713(s,o,i){var a=i(2523),u=i(15389),_=i(61489),w=Math.max;s.exports=function findIndex(s,o,i){var x=null==s?0:s.length;if(!x)return-1;var C=null==i?0:_(i);return C<0&&(C=w(x+C,0)),a(s,u(o,3),C)}},35970(s,o,i){var a=i(83120);s.exports=function flatten(s){return(null==s?0:s.length)?a(s,1):[]}},73424(s,o,i){var a=i(16962),u=i(2874),_=Array.prototype.push;function baseAry(s,o){return 2==o?function(o,i){return s(o,i)}:function(o){return s(o)}}function cloneArray(s){for(var o=s?s.length:0,i=Array(o);o--;)i[o]=s[o];return i}function wrapImmutable(s,o){return function(){var i=arguments.length;if(i){for(var a=Array(i);i--;)a[i]=arguments[i];var u=a[0]=o.apply(void 0,a);return s.apply(void 0,a),u}}}s.exports=function baseConvert(s,o,i,w){var x="function"==typeof o,C=o===Object(o);if(C&&(w=i,i=o,o=void 0),null==i)throw new TypeError;w||(w={});var j=!("cap"in w)||w.cap,L=!("curry"in w)||w.curry,B=!("fixed"in w)||w.fixed,$=!("immutable"in w)||w.immutable,U=!("rearg"in w)||w.rearg,V=x?i:u,z="curry"in w&&w.curry,Y="fixed"in w&&w.fixed,Z="rearg"in w&&w.rearg,ee=x?i.runInContext():void 0,ie=x?i:{ary:s.ary,assign:s.assign,clone:s.clone,curry:s.curry,forEach:s.forEach,isArray:s.isArray,isError:s.isError,isFunction:s.isFunction,isWeakMap:s.isWeakMap,iteratee:s.iteratee,keys:s.keys,rearg:s.rearg,toInteger:s.toInteger,toPath:s.toPath},ae=ie.ary,ce=ie.assign,le=ie.clone,pe=ie.curry,de=ie.forEach,fe=ie.isArray,ye=ie.isError,be=ie.isFunction,Se=ie.isWeakMap,_e=ie.keys,we=ie.rearg,xe=ie.toInteger,Pe=ie.toPath,Te=_e(a.aryMethod),Re={castArray:function(s){return function(){var o=arguments[0];return fe(o)?s(cloneArray(o)):s.apply(void 0,arguments)}},iteratee:function(s){return function(){var o=arguments[1],i=s(arguments[0],o),a=i.length;return j&&"number"==typeof o?(o=o>2?o-2:1,a&&a<=o?i:baseAry(i,o)):i}},mixin:function(s){return function(o){var i=this;if(!be(i))return s(i,Object(o));var a=[];return de(_e(o),(function(s){be(o[s])&&a.push([s,i.prototype[s]])})),s(i,Object(o)),de(a,(function(s){var o=s[1];be(o)?i.prototype[s[0]]=o:delete i.prototype[s[0]]})),i}},nthArg:function(s){return function(o){var i=o<0?1:xe(o)+1;return pe(s(o),i)}},rearg:function(s){return function(o,i){var a=i?i.length:0;return pe(s(o,i),a)}},runInContext:function(o){return function(i){return baseConvert(s,o(i),w)}}};function castCap(s,o){if(j){var i=a.iterateeRearg[s];if(i)return function iterateeRearg(s,o){return overArg(s,(function(s){var i=o.length;return function baseArity(s,o){return 2==o?function(o,i){return s.apply(void 0,arguments)}:function(o){return s.apply(void 0,arguments)}}(we(baseAry(s,i),o),i)}))}(o,i);var u=!x&&a.iterateeAry[s];if(u)return function iterateeAry(s,o){return overArg(s,(function(s){return"function"==typeof s?baseAry(s,o):s}))}(o,u)}return o}function castFixed(s,o,i){if(B&&(Y||!a.skipFixed[s])){var u=a.methodSpread[s],w=u&&u.start;return void 0===w?ae(o,i):function flatSpread(s,o){return function(){for(var i=arguments.length,a=i-1,u=Array(i);i--;)u[i]=arguments[i];var w=u[o],x=u.slice(0,o);return w&&_.apply(x,w),o!=a&&_.apply(x,u.slice(o+1)),s.apply(this,x)}}(o,w)}return o}function castRearg(s,o,i){return U&&i>1&&(Z||!a.skipRearg[s])?we(o,a.methodRearg[s]||a.aryRearg[i]):o}function cloneByPath(s,o){for(var i=-1,a=(o=Pe(o)).length,u=a-1,_=le(Object(s)),w=_;null!=w&&++i1?pe(o,i):o}(0,u=castCap(_,u),s),!1}})),!u})),u||(u=w),u==o&&(u=z?pe(u,1):function(){return o.apply(this,arguments)}),u.convert=createConverter(_,o),u.placeholder=o.placeholder=i,u}if(!C)return wrap(o,i,V);var $e=i,qe=[];return de(Te,(function(s){de(a.aryMethod[s],(function(s){var o=$e[a.remap[s]||s];o&&qe.push([s,wrap(s,o,$e)])}))})),de(_e($e),(function(s){var o=$e[s];if("function"==typeof o){for(var i=qe.length;i--;)if(qe[i][0]==s)return;o.convert=createConverter(s,o),qe.push([s,o])}})),de(qe,(function(s){$e[s[0]]=s[1]})),$e.convert=function convertLib(s){return $e.runInContext.convert(s)(void 0)},$e.placeholder=$e,de(_e($e),(function(s){de(a.realToAlias[s]||[],(function(o){$e[o]=$e[s]}))})),$e}},16962(s,o){o.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},o.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},o.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},o.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},o.iterateeRearg={mapKeys:[1],reduceRight:[1,0]},o.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},o.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},o.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},o.realToAlias=function(){var s=Object.prototype.hasOwnProperty,i=o.aliasToReal,a={};for(var u in i){var _=i[u];s.call(a,_)?a[_].push(u):a[_]=[u]}return a}(),o.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},o.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},o.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},47934(s,o,i){s.exports={ary:i(64626),assign:i(74733),clone:i(32629),curry:i(49747),forEach:i(83729),isArray:i(56449),isError:i(23546),isFunction:i(1882),isWeakMap:i(47886),iteratee:i(33855),keys:i(88984),rearg:i(84195),toInteger:i(61489),toPath:i(42072)}},56367(s,o,i){s.exports=i(77731)},79920(s,o,i){var a=i(73424),u=i(47934);s.exports=function convert(s,o,i){return a(u,s,o,i)}},2874(s){s.exports={}},77731(s,o,i){var a=i(79920)("set",i(63560));a.placeholder=i(2874),s.exports=a},58156(s,o,i){var a=i(47422);s.exports=function get(s,o,i){var u=null==s?void 0:a(s,o);return void 0===u?i:u}},61448(s,o,i){var a=i(20426),u=i(49326);s.exports=function has(s,o){return null!=s&&u(s,o,a)}},80631(s,o,i){var a=i(28077),u=i(49326);s.exports=function hasIn(s,o){return null!=s&&u(s,o,a)}},83488(s){s.exports=function identity(s){return s}},72428(s,o,i){var a=i(27534),u=i(40346),_=Object.prototype,w=_.hasOwnProperty,x=_.propertyIsEnumerable,C=a(function(){return arguments}())?a:function(s){return u(s)&&w.call(s,"callee")&&!x.call(s,"callee")};s.exports=C},56449(s){var o=Array.isArray;s.exports=o},64894(s,o,i){var a=i(1882),u=i(30294);s.exports=function isArrayLike(s){return null!=s&&u(s.length)&&!a(s)}},83693(s,o,i){var a=i(64894),u=i(40346);s.exports=function isArrayLikeObject(s){return u(s)&&a(s)}},53812(s,o,i){var a=i(72552),u=i(40346);s.exports=function isBoolean(s){return!0===s||!1===s||u(s)&&"[object Boolean]"==a(s)}},3656(s,o,i){s=i.nmd(s);var a=i(9325),u=i(89935),_=o&&!o.nodeType&&o,w=_&&s&&!s.nodeType&&s,x=w&&w.exports===_?a.Buffer:void 0,C=(x?x.isBuffer:void 0)||u;s.exports=C},62193(s,o,i){var a=i(88984),u=i(5861),_=i(72428),w=i(56449),x=i(64894),C=i(3656),j=i(55527),L=i(37167),B=Object.prototype.hasOwnProperty;s.exports=function isEmpty(s){if(null==s)return!0;if(x(s)&&(w(s)||"string"==typeof s||"function"==typeof s.splice||C(s)||L(s)||_(s)))return!s.length;var o=u(s);if("[object Map]"==o||"[object Set]"==o)return!s.size;if(j(s))return!a(s).length;for(var i in s)if(B.call(s,i))return!1;return!0}},2404(s,o,i){var a=i(60270);s.exports=function isEqual(s,o){return a(s,o)}},23546(s,o,i){var a=i(72552),u=i(40346),_=i(11331);s.exports=function isError(s){if(!u(s))return!1;var o=a(s);return"[object Error]"==o||"[object DOMException]"==o||"string"==typeof s.message&&"string"==typeof s.name&&!_(s)}},1882(s,o,i){var a=i(72552),u=i(23805);s.exports=function isFunction(s){if(!u(s))return!1;var o=a(s);return"[object Function]"==o||"[object GeneratorFunction]"==o||"[object AsyncFunction]"==o||"[object Proxy]"==o}},30294(s){s.exports=function isLength(s){return"number"==typeof s&&s>-1&&s%1==0&&s<=9007199254740991}},87730(s,o,i){var a=i(29172),u=i(27301),_=i(86009),w=_&&_.isMap,x=w?u(w):a;s.exports=x},5187(s){s.exports=function isNull(s){return null===s}},98023(s,o,i){var a=i(72552),u=i(40346);s.exports=function isNumber(s){return"number"==typeof s||u(s)&&"[object Number]"==a(s)}},23805(s){s.exports=function isObject(s){var o=typeof s;return null!=s&&("object"==o||"function"==o)}},40346(s){s.exports=function isObjectLike(s){return null!=s&&"object"==typeof s}},11331(s,o,i){var a=i(72552),u=i(28879),_=i(40346),w=Function.prototype,x=Object.prototype,C=w.toString,j=x.hasOwnProperty,L=C.call(Object);s.exports=function isPlainObject(s){if(!_(s)||"[object Object]"!=a(s))return!1;var o=u(s);if(null===o)return!0;var i=j.call(o,"constructor")&&o.constructor;return"function"==typeof i&&i instanceof i&&C.call(i)==L}},38440(s,o,i){var a=i(16038),u=i(27301),_=i(86009),w=_&&_.isSet,x=w?u(w):a;s.exports=x},85015(s,o,i){var a=i(72552),u=i(56449),_=i(40346);s.exports=function isString(s){return"string"==typeof s||!u(s)&&_(s)&&"[object String]"==a(s)}},44394(s,o,i){var a=i(72552),u=i(40346);s.exports=function isSymbol(s){return"symbol"==typeof s||u(s)&&"[object Symbol]"==a(s)}},37167(s,o,i){var a=i(4901),u=i(27301),_=i(86009),w=_&&_.isTypedArray,x=w?u(w):a;s.exports=x},47886(s,o,i){var a=i(5861),u=i(40346);s.exports=function isWeakMap(s){return u(s)&&"[object WeakMap]"==a(s)}},33855(s,o,i){var a=i(9999),u=i(15389);s.exports=function iteratee(s){return u("function"==typeof s?s:a(s,1))}},95950(s,o,i){var a=i(70695),u=i(88984),_=i(64894);s.exports=function keys(s){return _(s)?a(s):u(s)}},37241(s,o,i){var a=i(70695),u=i(72903),_=i(64894);s.exports=function keysIn(s){return _(s)?a(s,!0):u(s)}},68090(s){s.exports=function last(s){var o=null==s?0:s.length;return o?s[o-1]:void 0}},50104(s,o,i){var a=i(53661);function memoize(s,o){if("function"!=typeof s||null!=o&&"function"!=typeof o)throw new TypeError("Expected a function");var memoized=function(){var i=arguments,a=o?o.apply(this,i):i[0],u=memoized.cache;if(u.has(a))return u.get(a);var _=s.apply(this,i);return memoized.cache=u.set(a,_)||u,_};return memoized.cache=new(memoize.Cache||a),memoized}memoize.Cache=a,s.exports=memoize},55364(s,o,i){var a=i(85250),u=i(20999)((function(s,o,i){a(s,o,i)}));s.exports=u},6048(s){s.exports=function negate(s){if("function"!=typeof s)throw new TypeError("Expected a function");return function(){var o=arguments;switch(o.length){case 0:return!s.call(this);case 1:return!s.call(this,o[0]);case 2:return!s.call(this,o[0],o[1]);case 3:return!s.call(this,o[0],o[1],o[2])}return!s.apply(this,o)}}},63950(s){s.exports=function noop(){}},10124(s,o,i){var a=i(9325);s.exports=function(){return a.Date.now()}},90179(s,o,i){var a=i(34932),u=i(9999),_=i(19931),w=i(31769),x=i(21791),C=i(53138),j=i(38816),L=i(83349),B=j((function(s,o){var i={};if(null==s)return i;var j=!1;o=a(o,(function(o){return o=w(o,s),j||(j=o.length>1),o})),x(s,L(s),i),j&&(i=u(i,7,C));for(var B=o.length;B--;)_(i,o[B]);return i}));s.exports=B},50583(s,o,i){var a=i(47237),u=i(17255),_=i(28586),w=i(77797);s.exports=function property(s){return _(s)?a(w(s)):u(s)}},84195(s,o,i){var a=i(66977),u=i(38816),_=u((function(s,o){return a(s,256,void 0,void 0,void 0,o)}));s.exports=_},40860(s,o,i){var a=i(40882),u=i(80909),_=i(15389),w=i(85558),x=i(56449);s.exports=function reduce(s,o,i){var C=x(s)?a:w,j=arguments.length<3;return C(s,_(o,4),i,j,u)}},63560(s,o,i){var a=i(73170);s.exports=function set(s,o,i){return null==s?s:a(s,o,i)}},42426(s,o,i){var a=i(14248),u=i(15389),_=i(90916),w=i(56449),x=i(36800);s.exports=function some(s,o,i){var C=w(s)?a:_;return i&&x(s,o,i)&&(o=void 0),C(s,u(o,3))}},63345(s){s.exports=function stubArray(){return[]}},89935(s){s.exports=function stubFalse(){return!1}},17400(s,o,i){var a=i(99374),u=1/0;s.exports=function toFinite(s){return s?(s=a(s))===u||s===-1/0?17976931348623157e292*(s<0?-1:1):s==s?s:0:0===s?s:0}},61489(s,o,i){var a=i(17400);s.exports=function toInteger(s){var o=a(s),i=o%1;return o==o?i?o-i:o:0}},80218(s,o,i){var a=i(13222);s.exports=function toLower(s){return a(s).toLowerCase()}},99374(s,o,i){var a=i(54128),u=i(23805),_=i(44394),w=/^[-+]0x[0-9a-f]+$/i,x=/^0b[01]+$/i,C=/^0o[0-7]+$/i,j=parseInt;s.exports=function toNumber(s){if("number"==typeof s)return s;if(_(s))return NaN;if(u(s)){var o="function"==typeof s.valueOf?s.valueOf():s;s=u(o)?o+"":o}if("string"!=typeof s)return 0===s?s:+s;s=a(s);var i=x.test(s);return i||C.test(s)?j(s.slice(2),i?2:8):w.test(s)?NaN:+s}},42072(s,o,i){var a=i(34932),u=i(23007),_=i(56449),w=i(44394),x=i(61802),C=i(77797),j=i(13222);s.exports=function toPath(s){return _(s)?a(s,C):w(s)?[s]:u(x(j(s)))}},69884(s,o,i){var a=i(21791),u=i(37241);s.exports=function toPlainObject(s){return a(s,u(s))}},13222(s,o,i){var a=i(77556);s.exports=function toString(s){return null==s?"":a(s)}},55808(s,o,i){var a=i(12507)("toUpperCase");s.exports=a},66645(s,o,i){var a=i(1733),u=i(45434),_=i(13222),w=i(22225);s.exports=function words(s,o,i){return s=_(s),void 0===(o=i?void 0:o)?u(s)?w(s):a(s):s.match(o)||[]}},53758(s,o,i){var a=i(30980),u=i(56017),_=i(94033),w=i(56449),x=i(40346),C=i(80257),j=Object.prototype.hasOwnProperty;function lodash(s){if(x(s)&&!w(s)&&!(s instanceof a)){if(s instanceof u)return s;if(j.call(s,"__wrapped__"))return C(s)}return new u(s)}lodash.prototype=_.prototype,lodash.prototype.constructor=lodash,s.exports=lodash},47248(s,o,i){var a=i(16547),u=i(51234);s.exports=function zipObject(s,o){return u(s||[],o||[],a)}},43768(s,o,i){"use strict";var a=i(45981),u=i(85587);o.highlight=highlight,o.highlightAuto=function highlightAuto(s,o){var i,w,x,C,j=o||{},L=j.subset||a.listLanguages(),B=j.prefix,$=L.length,U=-1;null==B&&(B=_);if("string"!=typeof s)throw u("Expected `string` for value, got `%s`",s);w={relevance:0,language:null,value:[]},i={relevance:0,language:null,value:[]};for(;++U<$;)C=L[U],a.getLanguage(C)&&((x=highlight(C,s,o)).language=C,x.relevance>w.relevance&&(w=x),x.relevance>i.relevance&&(w=i,i=x));w.language&&(i.secondBest=w);return i},o.registerLanguage=function registerLanguage(s,o){a.registerLanguage(s,o)},o.listLanguages=function listLanguages(){return a.listLanguages()},o.registerAlias=function registerAlias(s,o){var i,u=s;o&&((u={})[s]=o);for(i in u)a.registerAliases(u[i],{languageName:i})},Emitter.prototype.addText=function text(s){var o,i,a=this.stack;if(""===s)return;o=a[a.length-1],(i=o.children[o.children.length-1])&&"text"===i.type?i.value+=s:o.children.push({type:"text",value:s})},Emitter.prototype.addKeyword=function addKeyword(s,o){this.openNode(o),this.addText(s),this.closeNode()},Emitter.prototype.addSublanguage=function addSublanguage(s,o){var i=this.stack,a=i[i.length-1],u=s.rootNode.children,_=o?{type:"element",tagName:"span",properties:{className:[o]},children:u}:u;a.children=a.children.concat(_)},Emitter.prototype.openNode=function open(s){var o=this.stack,i=this.options.classPrefix+s,a=o[o.length-1],u={type:"element",tagName:"span",properties:{className:[i]},children:[]};a.children.push(u),o.push(u)},Emitter.prototype.closeNode=function close(){this.stack.pop()},Emitter.prototype.closeAllNodes=noop,Emitter.prototype.finalize=noop,Emitter.prototype.toHTML=function toHtmlNoop(){return""};var _="hljs-";function highlight(s,o,i){var w,x=a.configure({}),C=(i||{}).prefix;if("string"!=typeof s)throw u("Expected `string` for name, got `%s`",s);if(!a.getLanguage(s))throw u("Unknown language: `%s` is not registered",s);if("string"!=typeof o)throw u("Expected `string` for value, got `%s`",o);if(null==C&&(C=_),a.configure({__emitter:Emitter,classPrefix:C}),w=a.highlight(o,{language:s,ignoreIllegals:!0}),a.configure(x||{}),w.errorRaised)throw w.errorRaised;return{relevance:w.relevance,language:w.language,value:w.emitter.rootNode.children}}function Emitter(s){this.options=s,this.rootNode={children:[]},this.stack=[this.rootNode]}function noop(){}},71514(s){"use strict";s.exports=Math.abs},58968(s){"use strict";s.exports=Math.floor},94459(s){"use strict";s.exports=Number.isNaN||function isNaN(s){return s!=s}},6188(s){"use strict";s.exports=Math.max},68002(s){"use strict";s.exports=Math.min},75880(s){"use strict";s.exports=Math.pow},70414(s){"use strict";s.exports=Math.round},73093(s,o,i){"use strict";var a=i(94459);s.exports=function sign(s){return a(s)||0===s?s:s<0?-1:1}},92340(s,o,i){const a=i(6048);function coerceElementMatchingCallback(s){return"string"==typeof s?o=>o.element===s:s.constructor&&s.extend?o=>o instanceof s:s}class ArraySlice{constructor(s){this.elements=s||[]}toValue(){return this.elements.map((s=>s.toValue()))}map(s,o){return this.elements.map(s,o)}flatMap(s,o){return this.map(s,o).reduce(((s,o)=>s.concat(o)),[])}compactMap(s,o){const i=[];return this.forEach((a=>{const u=s.bind(o)(a);u&&i.push(u)})),i}filter(s,o){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(s,o))}reject(s,o){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(a(s),o))}find(s,o){return s=coerceElementMatchingCallback(s),this.elements.find(s,o)}forEach(s,o){this.elements.forEach(s,o)}reduce(s,o){return this.elements.reduce(s,o)}includes(s){return this.elements.some((o=>o.equals(s)))}shift(){return this.elements.shift()}unshift(s){this.elements.unshift(this.refract(s))}push(s){return this.elements.push(this.refract(s)),this}add(s){this.push(s)}get(s){return this.elements[s]}getValue(s){const o=this.elements[s];if(o)return o.toValue()}get length(){return this.elements.length}get isEmpty(){return 0===this.elements.length}get first(){return this.elements[0]}}"undefined"!=typeof Symbol&&(ArraySlice.prototype[Symbol.iterator]=function symbol(){return this.elements[Symbol.iterator]()}),s.exports=ArraySlice},55973(s){class KeyValuePair{constructor(s,o){this.key=s,this.value=o}clone(){const s=new KeyValuePair;return this.key&&(s.key=this.key.clone()),this.value&&(s.value=this.value.clone()),s}}s.exports=KeyValuePair},3110(s,o,i){const a=i(5187),u=i(85015),_=i(98023),w=i(53812),x=i(23805),C=i(85105),j=i(86804);class Namespace{constructor(s){this.elementMap={},this.elementDetection=[],this.Element=j.Element,this.KeyValuePair=j.KeyValuePair,s&&s.noDefault||this.useDefault(),this._attributeElementKeys=[],this._attributeElementArrayKeys=[]}use(s){return s.namespace&&s.namespace({base:this}),s.load&&s.load({base:this}),this}useDefault(){return this.register("null",j.NullElement).register("string",j.StringElement).register("number",j.NumberElement).register("boolean",j.BooleanElement).register("array",j.ArrayElement).register("object",j.ObjectElement).register("member",j.MemberElement).register("ref",j.RefElement).register("link",j.LinkElement),this.detect(a,j.NullElement,!1).detect(u,j.StringElement,!1).detect(_,j.NumberElement,!1).detect(w,j.BooleanElement,!1).detect(Array.isArray,j.ArrayElement,!1).detect(x,j.ObjectElement,!1),this}register(s,o){return this._elements=void 0,this.elementMap[s]=o,this}unregister(s){return this._elements=void 0,delete this.elementMap[s],this}detect(s,o,i){return void 0===i||i?this.elementDetection.unshift([s,o]):this.elementDetection.push([s,o]),this}toElement(s){if(s instanceof this.Element)return s;let o;for(let i=0;i{const o=s[0].toUpperCase()+s.substr(1);this._elements[o]=this.elementMap[s]}))),this._elements}get serialiser(){return new C(this)}}C.prototype.Namespace=Namespace,s.exports=Namespace},10866(s,o,i){const a=i(6048),u=i(92340);class ObjectSlice extends u{map(s,o){return this.elements.map((i=>s.bind(o)(i.value,i.key,i)))}filter(s,o){return new ObjectSlice(this.elements.filter((i=>s.bind(o)(i.value,i.key,i))))}reject(s,o){return this.filter(a(s.bind(o)))}forEach(s,o){return this.elements.forEach(((i,a)=>{s.bind(o)(i.value,i.key,i,a)}))}keys(){return this.map(((s,o)=>o.toValue()))}values(){return this.map((s=>s.toValue()))}}s.exports=ObjectSlice},86804(s,o,i){const a=i(10316),u=i(41067),_=i(71167),w=i(40239),x=i(12242),C=i(6233),j=i(87726),L=i(61045),B=i(86303),$=i(14540),U=i(92340),V=i(10866),z=i(55973);function refract(s){if(s instanceof a)return s;if("string"==typeof s)return new _(s);if("number"==typeof s)return new w(s);if("boolean"==typeof s)return new x(s);if(null===s)return new u;if(Array.isArray(s))return new C(s.map(refract));if("object"==typeof s){return new L(s)}return s}a.prototype.ObjectElement=L,a.prototype.RefElement=$,a.prototype.MemberElement=j,a.prototype.refract=refract,U.prototype.refract=refract,s.exports={Element:a,NullElement:u,StringElement:_,NumberElement:w,BooleanElement:x,ArrayElement:C,MemberElement:j,ObjectElement:L,LinkElement:B,RefElement:$,refract,ArraySlice:U,ObjectSlice:V,KeyValuePair:z}},86303(s,o,i){const a=i(10316);s.exports=class LinkElement extends a{constructor(s,o,i){super(s||[],o,i),this.element="link"}get relation(){return this.attributes.get("relation")}set relation(s){this.attributes.set("relation",s)}get href(){return this.attributes.get("href")}set href(s){this.attributes.set("href",s)}}},14540(s,o,i){const a=i(10316);s.exports=class RefElement extends a{constructor(s,o,i){super(s||[],o,i),this.element="ref",this.path||(this.path="element")}get path(){return this.attributes.get("path")}set path(s){this.attributes.set("path",s)}}},34035(s,o,i){const a=i(3110),u=i(86804);o.g$=a,o.KeyValuePair=i(55973),o.G6=u.ArraySlice,o.ot=u.ObjectSlice,o.Hg=u.Element,o.Om=u.StringElement,o.kT=u.NumberElement,o.bd=u.BooleanElement,o.Os=u.NullElement,o.wE=u.ArrayElement,o.Sh=u.ObjectElement,o.Pr=u.MemberElement,o.sI=u.RefElement,o.Ft=u.LinkElement,o.e=u.refract,i(85105),i(75147)},6233(s,o,i){const a=i(6048),u=i(10316),_=i(92340);class ArrayElement extends u{constructor(s,o,i){super(s||[],o,i),this.element="array"}primitive(){return"array"}get(s){return this.content[s]}getValue(s){const o=this.get(s);if(o)return o.toValue()}getIndex(s){return this.content[s]}set(s,o){return this.content[s]=this.refract(o),this}remove(s){const o=this.content.splice(s,1);return o.length?o[0]:null}map(s,o){return this.content.map(s,o)}flatMap(s,o){return this.map(s,o).reduce(((s,o)=>s.concat(o)),[])}compactMap(s,o){const i=[];return this.forEach((a=>{const u=s.bind(o)(a);u&&i.push(u)})),i}filter(s,o){return new _(this.content.filter(s,o))}reject(s,o){return this.filter(a(s),o)}reduce(s,o){let i,a;void 0!==o?(i=0,a=this.refract(o)):(i=1,a="object"===this.primitive()?this.first.value:this.first);for(let o=i;o{s.bind(o)(i,this.refract(a))}))}shift(){return this.content.shift()}unshift(s){this.content.unshift(this.refract(s))}push(s){return this.content.push(this.refract(s)),this}add(s){this.push(s)}findElements(s,o){const i=o||{},a=!!i.recursive,u=void 0===i.results?[]:i.results;return this.forEach(((o,i,_)=>{a&&void 0!==o.findElements&&o.findElements(s,{results:u,recursive:a}),s(o,i,_)&&u.push(o)})),u}find(s){return new _(this.findElements(s,{recursive:!0}))}findByElement(s){return this.find((o=>o.element===s))}findByClass(s){return this.find((o=>o.classes.includes(s)))}getById(s){return this.find((o=>o.id.toValue()===s)).first}includes(s){return this.content.some((o=>o.equals(s)))}contains(s){return this.includes(s)}empty(){return new this.constructor([])}"fantasy-land/empty"(){return this.empty()}concat(s){return new this.constructor(this.content.concat(s.content))}"fantasy-land/concat"(s){return this.concat(s)}"fantasy-land/map"(s){return new this.constructor(this.map(s))}"fantasy-land/chain"(s){return this.map((o=>s(o)),this).reduce(((s,o)=>s.concat(o)),this.empty())}"fantasy-land/filter"(s){return new this.constructor(this.content.filter(s))}"fantasy-land/reduce"(s,o){return this.content.reduce(s,o)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}get first(){return this.getIndex(0)}get second(){return this.getIndex(1)}get last(){return this.getIndex(this.length-1)}}ArrayElement.empty=function empty(){return new this},ArrayElement["fantasy-land/empty"]=ArrayElement.empty,"undefined"!=typeof Symbol&&(ArrayElement.prototype[Symbol.iterator]=function symbol(){return this.content[Symbol.iterator]()}),s.exports=ArrayElement},12242(s,o,i){const a=i(10316);s.exports=class BooleanElement extends a{constructor(s,o,i){super(s,o,i),this.element="boolean"}primitive(){return"boolean"}}},10316(s,o,i){const a=i(2404),u=i(55973),_=i(92340);class Element{constructor(s,o,i){o&&(this.meta=o),i&&(this.attributes=i),this.content=s}freeze(){Object.isFrozen(this)||(this._meta&&(this.meta.parent=this,this.meta.freeze()),this._attributes&&(this.attributes.parent=this,this.attributes.freeze()),this.children.forEach((s=>{s.parent=this,s.freeze()}),this),this.content&&Array.isArray(this.content)&&Object.freeze(this.content),Object.freeze(this))}primitive(){}clone(){const s=new this.constructor;return s.element=this.element,this.meta.length&&(s._meta=this.meta.clone()),this.attributes.length&&(s._attributes=this.attributes.clone()),this.content?this.content.clone?s.content=this.content.clone():Array.isArray(this.content)?s.content=this.content.map((s=>s.clone())):s.content=this.content:s.content=this.content,s}toValue(){return this.content instanceof Element?this.content.toValue():this.content instanceof u?{key:this.content.key.toValue(),value:this.content.value?this.content.value.toValue():void 0}:this.content&&this.content.map?this.content.map((s=>s.toValue()),this):this.content}toRef(s){if(""===this.id.toValue())throw Error("Cannot create reference to an element that does not contain an ID");const o=new this.RefElement(this.id.toValue());return s&&(o.path=s),o}findRecursive(...s){if(arguments.length>1&&!this.isFrozen)throw new Error("Cannot find recursive with multiple element names without first freezing the element. Call `element.freeze()`");const o=s.pop();let i=new _;const append=(s,o)=>(s.push(o),s),checkElement=(s,i)=>{i.element===o&&s.push(i);const a=i.findRecursive(o);return a&&a.reduce(append,s),i.content instanceof u&&(i.content.key&&checkElement(s,i.content.key),i.content.value&&checkElement(s,i.content.value)),s};return this.content&&(this.content.element&&checkElement(i,this.content),Array.isArray(this.content)&&this.content.reduce(checkElement,i)),s.isEmpty||(i=i.filter((o=>{let i=o.parents.map((s=>s.element));for(const o in s){const a=s[o],u=i.indexOf(a);if(-1===u)return!1;i=i.splice(0,u)}return!0}))),i}set(s){return this.content=s,this}equals(s){return a(this.toValue(),s)}getMetaProperty(s,o){if(!this.meta.hasKey(s)){if(this.isFrozen){const s=this.refract(o);return s.freeze(),s}this.meta.set(s,o)}return this.meta.get(s)}setMetaProperty(s,o){this.meta.set(s,o)}get element(){return this._storedElement||"element"}set element(s){this._storedElement=s}get content(){return this._content}set content(s){if(s instanceof Element)this._content=s;else if(s instanceof _)this.content=s.elements;else if("string"==typeof s||"number"==typeof s||"boolean"==typeof s||"null"===s||null==s)this._content=s;else if(s instanceof u)this._content=s;else if(Array.isArray(s))this._content=s.map(this.refract);else{if("object"!=typeof s)throw new Error("Cannot set content to given value");this._content=Object.keys(s).map((o=>new this.MemberElement(o,s[o])))}}get meta(){if(!this._meta){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._meta=new this.ObjectElement}return this._meta}set meta(s){s instanceof this.ObjectElement?this._meta=s:this.meta.set(s||{})}get attributes(){if(!this._attributes){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._attributes=new this.ObjectElement}return this._attributes}set attributes(s){s instanceof this.ObjectElement?this._attributes=s:this.attributes.set(s||{})}get id(){return this.getMetaProperty("id","")}set id(s){this.setMetaProperty("id",s)}get classes(){return this.getMetaProperty("classes",[])}set classes(s){this.setMetaProperty("classes",s)}get title(){return this.getMetaProperty("title","")}set title(s){this.setMetaProperty("title",s)}get description(){return this.getMetaProperty("description","")}set description(s){this.setMetaProperty("description",s)}get links(){return this.getMetaProperty("links",[])}set links(s){this.setMetaProperty("links",s)}get isFrozen(){return Object.isFrozen(this)}get parents(){let{parent:s}=this;const o=new _;for(;s;)o.push(s),s=s.parent;return o}get children(){if(Array.isArray(this.content))return new _(this.content);if(this.content instanceof u){const s=new _([this.content.key]);return this.content.value&&s.push(this.content.value),s}return this.content instanceof Element?new _([this.content]):new _}get recursiveChildren(){const s=new _;return this.children.forEach((o=>{s.push(o),o.recursiveChildren.forEach((o=>{s.push(o)}))})),s}}s.exports=Element},87726(s,o,i){const a=i(55973),u=i(10316);s.exports=class MemberElement extends u{constructor(s,o,i,u){super(new a,i,u),this.element="member",this.key=s,this.value=o}get key(){return this.content.key}set key(s){this.content.key=this.refract(s)}get value(){return this.content.value}set value(s){this.content.value=this.refract(s)}}},41067(s,o,i){const a=i(10316);s.exports=class NullElement extends a{constructor(s,o,i){super(s||null,o,i),this.element="null"}primitive(){return"null"}set(){return new Error("Cannot set the value of null")}}},40239(s,o,i){const a=i(10316);s.exports=class NumberElement extends a{constructor(s,o,i){super(s,o,i),this.element="number"}primitive(){return"number"}}},61045(s,o,i){const a=i(6048),u=i(23805),_=i(6233),w=i(87726),x=i(10866);s.exports=class ObjectElement extends _{constructor(s,o,i){super(s||[],o,i),this.element="object"}primitive(){return"object"}toValue(){return this.content.reduce(((s,o)=>(s[o.key.toValue()]=o.value?o.value.toValue():void 0,s)),{})}get(s){const o=this.getMember(s);if(o)return o.value}getMember(s){if(void 0!==s)return this.content.find((o=>o.key.toValue()===s))}remove(s){let o=null;return this.content=this.content.filter((i=>i.key.toValue()!==s||(o=i,!1))),o}getKey(s){const o=this.getMember(s);if(o)return o.key}set(s,o){if(u(s))return Object.keys(s).forEach((o=>{this.set(o,s[o])})),this;const i=s,a=this.getMember(i);return a?a.value=o:this.content.push(new w(i,o)),this}keys(){return this.content.map((s=>s.key.toValue()))}values(){return this.content.map((s=>s.value.toValue()))}hasKey(s){return this.content.some((o=>o.key.equals(s)))}items(){return this.content.map((s=>[s.key.toValue(),s.value.toValue()]))}map(s,o){return this.content.map((i=>s.bind(o)(i.value,i.key,i)))}compactMap(s,o){const i=[];return this.forEach(((a,u,_)=>{const w=s.bind(o)(a,u,_);w&&i.push(w)})),i}filter(s,o){return new x(this.content).filter(s,o)}reject(s,o){return this.filter(a(s),o)}forEach(s,o){return this.content.forEach((i=>s.bind(o)(i.value,i.key,i)))}}},71167(s,o,i){const a=i(10316);s.exports=class StringElement extends a{constructor(s,o,i){super(s,o,i),this.element="string"}primitive(){return"string"}get length(){return this.content.length}}},75147(s,o,i){const a=i(85105);s.exports=class JSON06Serialiser extends a{serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);let o;s._attributes&&s.attributes.get("variable")&&(o=s.attributes.get("variable"));const i={element:s.element};s._meta&&s._meta.length>0&&(i.meta=this.serialiseObject(s.meta));const a="enum"===s.element||-1!==s.attributes.keys().indexOf("enumerations");if(a){const o=this.enumSerialiseAttributes(s);o&&(i.attributes=o)}else if(s._attributes&&s._attributes.length>0){let{attributes:a}=s;a.get("metadata")&&(a=a.clone(),a.set("meta",a.get("metadata")),a.remove("metadata")),"member"===s.element&&o&&(a=a.clone(),a.remove("variable")),a.length>0&&(i.attributes=this.serialiseObject(a))}if(a)i.content=this.enumSerialiseContent(s,i);else if(this[`${s.element}SerialiseContent`])i.content=this[`${s.element}SerialiseContent`](s,i);else if(void 0!==s.content){let a;o&&s.content.key?(a=s.content.clone(),a.key.attributes.set("variable",o),a=this.serialiseContent(a)):a=this.serialiseContent(s.content),this.shouldSerialiseContent(s,a)&&(i.content=a)}else this.shouldSerialiseContent(s,s.content)&&s instanceof this.namespace.elements.Array&&(i.content=[]);return i}shouldSerialiseContent(s,o){return"parseResult"===s.element||"httpRequest"===s.element||"httpResponse"===s.element||"category"===s.element||"link"===s.element||void 0!==o&&(!Array.isArray(o)||0!==o.length)}refSerialiseContent(s,o){return delete o.attributes,{href:s.toValue(),path:s.path.toValue()}}sourceMapSerialiseContent(s){return s.toValue()}dataStructureSerialiseContent(s){return[this.serialiseContent(s.content)]}enumSerialiseAttributes(s){const o=s.attributes.clone(),i=o.remove("enumerations")||new this.namespace.elements.Array([]),a=o.get("default");let u=o.get("samples")||new this.namespace.elements.Array([]);if(a&&a.content&&(a.content.attributes&&a.content.attributes.remove("typeAttributes"),o.set("default",new this.namespace.elements.Array([a.content]))),u.forEach((s=>{s.content&&s.content.element&&s.content.attributes.remove("typeAttributes")})),s.content&&0!==i.length&&u.unshift(s.content),u=u.map((s=>s instanceof this.namespace.elements.Array?[s]:new this.namespace.elements.Array([s.content]))),u.length&&o.set("samples",u),o.length>0)return this.serialiseObject(o)}enumSerialiseContent(s){if(s._attributes){const o=s.attributes.get("enumerations");if(o&&o.length>0)return o.content.map((s=>{const o=s.clone();return o.attributes.remove("typeAttributes"),this.serialise(o)}))}if(s.content){const o=s.content.clone();return o.attributes.remove("typeAttributes"),[this.serialise(o)]}return[]}deserialise(s){if("string"==typeof s)return new this.namespace.elements.String(s);if("number"==typeof s)return new this.namespace.elements.Number(s);if("boolean"==typeof s)return new this.namespace.elements.Boolean(s);if(null===s)return new this.namespace.elements.Null;if(Array.isArray(s))return new this.namespace.elements.Array(s.map(this.deserialise,this));const o=this.namespace.getElementClass(s.element),i=new o;i.element!==s.element&&(i.element=s.element),s.meta&&this.deserialiseObject(s.meta,i.meta),s.attributes&&this.deserialiseObject(s.attributes,i.attributes);const a=this.deserialiseContent(s.content);if(void 0===a&&null!==i.content||(i.content=a),"enum"===i.element){i.content&&i.attributes.set("enumerations",i.content);let s=i.attributes.get("samples");if(i.attributes.remove("samples"),s){const a=s;s=new this.namespace.elements.Array,a.forEach((a=>{a.forEach((a=>{const u=new o(a);u.element=i.element,s.push(u)}))}));const u=s.shift();i.content=u?u.content:void 0,i.attributes.set("samples",s)}else i.content=void 0;let a=i.attributes.get("default");if(a&&a.length>0){a=a.get(0);const s=new o(a);s.element=i.element,i.attributes.set("default",s)}}else if("dataStructure"===i.element&&Array.isArray(i.content))[i.content]=i.content;else if("category"===i.element){const s=i.attributes.get("meta");s&&(i.attributes.set("metadata",s),i.attributes.remove("meta"))}else"member"===i.element&&i.key&&i.key._attributes&&i.key._attributes.getValue("variable")&&(i.attributes.set("variable",i.key.attributes.get("variable")),i.key.attributes.remove("variable"));return i}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const o={key:this.serialise(s.key)};return s.value&&(o.value=this.serialise(s.value)),o}return s&&s.map?s.map(this.serialise,this):s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const o=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(o.value=this.deserialise(s.value)),o}if(s.map)return s.map(this.deserialise,this)}return s}shouldRefract(s){return!!(s._attributes&&s.attributes.keys().length||s._meta&&s.meta.keys().length)||"enum"!==s.element&&(s.element!==s.primitive()||"member"===s.element)}convertKeyToRefract(s,o){return this.shouldRefract(o)?this.serialise(o):"enum"===o.element?this.serialiseEnum(o):"array"===o.element?o.map((o=>this.shouldRefract(o)||"default"===s?this.serialise(o):"array"===o.element||"object"===o.element||"enum"===o.element?o.children.map((s=>this.serialise(s))):o.toValue())):"object"===o.element?(o.content||[]).map(this.serialise,this):o.toValue()}serialiseEnum(s){return s.children.map((s=>this.serialise(s)))}serialiseObject(s){const o={};return s.forEach(((s,i)=>{if(s){const a=i.toValue();o[a]=this.convertKeyToRefract(a,s)}})),o}deserialiseObject(s,o){Object.keys(s).forEach((i=>{o.set(i,this.deserialise(s[i]))}))}}},85105(s){s.exports=class JSONSerialiser{constructor(s){this.namespace=s||new this.Namespace}serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);const o={element:s.element};s._meta&&s._meta.length>0&&(o.meta=this.serialiseObject(s.meta)),s._attributes&&s._attributes.length>0&&(o.attributes=this.serialiseObject(s.attributes));const i=this.serialiseContent(s.content);return void 0!==i&&(o.content=i),o}deserialise(s){if(!s.element)throw new Error("Given value is not an object containing an element name");const o=new(this.namespace.getElementClass(s.element));o.element!==s.element&&(o.element=s.element),s.meta&&this.deserialiseObject(s.meta,o.meta),s.attributes&&this.deserialiseObject(s.attributes,o.attributes);const i=this.deserialiseContent(s.content);return void 0===i&&null!==o.content||(o.content=i),o}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const o={key:this.serialise(s.key)};return s.value&&(o.value=this.serialise(s.value)),o}if(s&&s.map){if(0===s.length)return;return s.map(this.serialise,this)}return s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const o=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(o.value=this.deserialise(s.value)),o}if(s.map)return s.map(this.deserialise,this)}return s}serialiseObject(s){const o={};if(s.forEach(((s,i)=>{s&&(o[i.toValue()]=this.serialise(s))})),0!==Object.keys(o).length)return o}deserialiseObject(s,o){Object.keys(s).forEach((i=>{o.set(i,this.deserialise(s[i]))}))}}},76578(s){"use strict";s.exports=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]},65606(s){var o,i,a=s.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(s){if(o===setTimeout)return setTimeout(s,0);if((o===defaultSetTimout||!o)&&setTimeout)return o=setTimeout,setTimeout(s,0);try{return o(s,0)}catch(i){try{return o.call(null,s,0)}catch(i){return o.call(this,s,0)}}}!function(){try{o="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(s){o=defaultSetTimout}try{i="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(s){i=defaultClearTimeout}}();var u,_=[],w=!1,x=-1;function cleanUpNextTick(){w&&u&&(w=!1,u.length?_=u.concat(_):x=-1,_.length&&drainQueue())}function drainQueue(){if(!w){var s=runTimeout(cleanUpNextTick);w=!0;for(var o=_.length;o;){for(u=_,_=[];++x1)for(var i=1;i_)throw new RangeError("requested too many random bytes");var i=w.allocUnsafe(s);if(s>0)if(s>u)for(var C=0;C=0||(u[i]=s[i]);return u}(s,o);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);for(a=0;a<_.length;a++)i=_[a],o.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(s,i)&&(u[i]=s[i])}return u}function _defineProperties(s,o){for(var i=0;i=0||(u[i]=s[i]);return u}(s,o);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);for(a=0;a<_.length;a++)i=_[a],o.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(s,i)&&(u[i]=s[i])}return u}function ownKeys(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter((function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable}))),i.push.apply(i,a)}return i}function _objectSpread(s){for(var o=1;o=a?i.notify(s):o.length>u.length&&i.notify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:""})}))}))})),_defineProperty(_assertThisInitialized(i),"onKeyDown",(function(s){"Enter"===s.key&&i.forceNotify(s);var o=i.props.onKeyDown;o&&(s.persist(),o(s))})),_defineProperty(_assertThisInitialized(i),"onBlur",(function(s){i.forceNotify(s);var o=i.props.onBlur;o&&(s.persist(),o(s))})),_defineProperty(_assertThisInitialized(i),"createNotifier",(function(s){if(s<0)i.notify=function(){return null};else if(0===s)i.notify=i.doNotify;else{var o=(0,u.default)((function(s){i.isDebouncing=!1,i.doNotify(s)}),s);i.notify=function(s){i.isDebouncing=!0,o(s)},i.flush=function(){return o.flush()},i.cancel=function(){i.isDebouncing=!1,o.cancel()}}})),_defineProperty(_assertThisInitialized(i),"doNotify",(function(){i.props.onChange.apply(void 0,arguments)})),_defineProperty(_assertThisInitialized(i),"forceNotify",(function(s){var o=i.props.debounceTimeout;if(i.isDebouncing||!(o>0)){i.cancel&&i.cancel();var a=i.state.value,u=i.props.minLength;a.length>=u?i.doNotify(s):i.doNotify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:a})}))}})),i.isDebouncing=!1,i.state={value:void 0===s.value||null===s.value?"":s.value};var a=i.props.debounceTimeout;return i.createNotifier(a),i}return function _createClass(s,o,i){return o&&_defineProperties(s.prototype,o),i&&_defineProperties(s,i),Object.defineProperty(s,"prototype",{writable:!1}),s}(DebounceInput,[{key:"componentDidUpdate",value:function componentDidUpdate(s){if(!this.isDebouncing){var o=this.props,i=o.value,a=o.debounceTimeout,u=s.debounceTimeout,_=s.value,w=this.state.value;void 0!==i&&_!==i&&w!==i&&this.setState({value:i}),a!==u&&this.createNotifier(a)}}},{key:"componentWillUnmount",value:function componentWillUnmount(){this.flush&&this.flush()}},{key:"render",value:function render(){var s,o,i=this.props,u=i.element,w=(i.onChange,i.value,i.minLength,i.debounceTimeout,i.forceNotifyByEnter),x=i.forceNotifyOnBlur,C=i.onKeyDown,j=i.onBlur,L=i.inputRef,B=_objectWithoutProperties(i,_),$=this.state.value;s=w?{onKeyDown:this.onKeyDown}:C?{onKeyDown:C}:{},o=x?{onBlur:this.onBlur}:j?{onBlur:j}:{};var U=L?{ref:L}:{};return a.default.createElement(u,_objectSpread(_objectSpread(_objectSpread(_objectSpread({},B),{},{onChange:this.onChange,value:$},s),o),U))}}]),DebounceInput}(a.default.PureComponent);o.DebounceInput=w,_defineProperty(w,"defaultProps",{element:"input",type:"text",onKeyDown:void 0,onBlur:void 0,value:void 0,minLength:0,debounceTimeout:100,forceNotifyByEnter:!0,forceNotifyOnBlur:!0,inputRef:void 0})},24677(s,o,i){"use strict";var a=i(81214).DebounceInput;a.DebounceInput=a,s.exports=a},22551(s,o,i){"use strict";var a=i(96540),u=i(69982);function p(s){for(var o="https://reactjs.org/docs/error-decoder.html?invariant="+s,i=1;i
'); + } + value() { + return this.buffer; + } + span(s) { + this.buffer += ``; + } + } + class TokenTree { + constructor() { + ((this.rootNode = { children: [] }), (this.stack = [this.rootNode])); + } + get top() { + return this.stack[this.stack.length - 1]; + } + get root() { + return this.rootNode; + } + add(s) { + this.top.children.push(s); + } + openNode(s) { + const o = { kind: s, children: [] }; + (this.add(o), this.stack.push(o)); + } + closeNode() { + if (this.stack.length > 1) return this.stack.pop(); + } + closeAllNodes() { + for (; this.closeNode(); ); + } + toJSON() { + return JSON.stringify(this.rootNode, null, 4); + } + walk(s) { + return this.constructor._walk(s, this.rootNode); + } + static _walk(s, o) { + return ( + 'string' == typeof o + ? s.addText(o) + : o.children && + (s.openNode(o), o.children.forEach((o) => this._walk(s, o)), s.closeNode(o)), + s + ); + } + static _collapse(s) { + 'string' != typeof s && + s.children && + (s.children.every((s) => 'string' == typeof s) + ? (s.children = [s.children.join('')]) + : s.children.forEach((s) => { + TokenTree._collapse(s); + })); + } + } + class TokenTreeEmitter extends TokenTree { + constructor(s) { + (super(), (this.options = s)); + } + addKeyword(s, o) { + '' !== s && (this.openNode(o), this.addText(s), this.closeNode()); + } + addText(s) { + '' !== s && this.add(s); + } + addSublanguage(s, o) { + const i = s.root; + ((i.kind = o), (i.sublanguage = !0), this.add(i)); + } + toHTML() { + return new HTMLRenderer(this, this.options).value(); + } + finalize() { + return !0; + } + } + function source(s) { + return s ? ('string' == typeof s ? s : s.source) : null; + } + const a = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./; + const u = '[a-zA-Z]\\w*', + _ = '[a-zA-Z_]\\w*', + w = '\\b\\d+(\\.\\d+)?', + x = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)', + C = '\\b(0b[01]+)', + j = { begin: '\\\\[\\s\\S]', relevance: 0 }, + L = { className: 'string', begin: "'", end: "'", illegal: '\\n', contains: [j] }, + B = { className: 'string', begin: '"', end: '"', illegal: '\\n', contains: [j] }, + $ = { + begin: + /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ + }, + COMMENT = function (s, o, i = {}) { + const a = inherit({ className: 'comment', begin: s, end: o, contains: [] }, i); + return ( + a.contains.push($), + a.contains.push({ + className: 'doctag', + begin: '(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):', + relevance: 0 + }), + a + ); + }, + U = COMMENT('//', '$'), + V = COMMENT('/\\*', '\\*/'), + z = COMMENT('#', '$'), + Y = { className: 'number', begin: w, relevance: 0 }, + Z = { className: 'number', begin: x, relevance: 0 }, + ee = { className: 'number', begin: C, relevance: 0 }, + ie = { + className: 'number', + begin: + w + + '(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?', + relevance: 0 + }, + ae = { + begin: /(?=\/[^/\n]*\/)/, + contains: [ + { + className: 'regexp', + begin: /\//, + end: /\/[gimuy]*/, + illegal: /\n/, + contains: [j, { begin: /\[/, end: /\]/, relevance: 0, contains: [j] }] + } + ] + }, + ce = { className: 'title', begin: u, relevance: 0 }, + le = { className: 'title', begin: _, relevance: 0 }, + pe = { begin: '\\.\\s*' + _, relevance: 0 }; + var de = Object.freeze({ + __proto__: null, + MATCH_NOTHING_RE: /\b\B/, + IDENT_RE: u, + UNDERSCORE_IDENT_RE: _, + NUMBER_RE: w, + C_NUMBER_RE: x, + BINARY_NUMBER_RE: C, + RE_STARTERS_RE: + '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~', + SHEBANG: (s = {}) => { + const o = /^#![ ]*\//; + return ( + s.binary && + (s.begin = (function concat(...s) { + return s.map((s) => source(s)).join(''); + })(o, /.*\b/, s.binary, /\b.*/)), + inherit( + { + className: 'meta', + begin: o, + end: /$/, + relevance: 0, + 'on:begin': (s, o) => { + 0 !== s.index && o.ignoreMatch(); + } + }, + s + ) + ); + }, + BACKSLASH_ESCAPE: j, + APOS_STRING_MODE: L, + QUOTE_STRING_MODE: B, + PHRASAL_WORDS_MODE: $, + COMMENT, + C_LINE_COMMENT_MODE: U, + C_BLOCK_COMMENT_MODE: V, + HASH_COMMENT_MODE: z, + NUMBER_MODE: Y, + C_NUMBER_MODE: Z, + BINARY_NUMBER_MODE: ee, + CSS_NUMBER_MODE: ie, + REGEXP_MODE: ae, + TITLE_MODE: ce, + UNDERSCORE_TITLE_MODE: le, + METHOD_GUARD: pe, + END_SAME_AS_BEGIN: function (s) { + return Object.assign(s, { + 'on:begin': (s, o) => { + o.data._beginMatch = s[1]; + }, + 'on:end': (s, o) => { + o.data._beginMatch !== s[1] && o.ignoreMatch(); + } + }); + } + }); + function skipIfhasPrecedingDot(s, o) { + '.' === s.input[s.index - 1] && o.ignoreMatch(); + } + function beginKeywords(s, o) { + o && + s.beginKeywords && + ((s.begin = '\\b(' + s.beginKeywords.split(' ').join('|') + ')(?!\\.)(?=\\b|\\s)'), + (s.__beforeBegin = skipIfhasPrecedingDot), + (s.keywords = s.keywords || s.beginKeywords), + delete s.beginKeywords, + void 0 === s.relevance && (s.relevance = 0)); + } + function compileIllegal(s, o) { + Array.isArray(s.illegal) && + (s.illegal = (function either(...s) { + return '(' + s.map((s) => source(s)).join('|') + ')'; + })(...s.illegal)); + } + function compileMatch(s, o) { + if (s.match) { + if (s.begin || s.end) throw new Error('begin & end are not supported with match'); + ((s.begin = s.match), delete s.match); + } + } + function compileRelevance(s, o) { + void 0 === s.relevance && (s.relevance = 1); + } + const fe = [ + 'of', + 'and', + 'for', + 'in', + 'not', + 'or', + 'if', + 'then', + 'parent', + 'list', + 'value' + ]; + function compileKeywords(s, o, i = 'keyword') { + const a = {}; + return ( + 'string' == typeof s + ? compileList(i, s.split(' ')) + : Array.isArray(s) + ? compileList(i, s) + : Object.keys(s).forEach(function (i) { + Object.assign(a, compileKeywords(s[i], o, i)); + }), + a + ); + function compileList(s, i) { + (o && (i = i.map((s) => s.toLowerCase())), + i.forEach(function (o) { + const i = o.split('|'); + a[i[0]] = [s, scoreForKeyword(i[0], i[1])]; + })); + } + } + function scoreForKeyword(s, o) { + return o + ? Number(o) + : (function commonKeyword(s) { + return fe.includes(s.toLowerCase()); + })(s) + ? 0 + : 1; + } + function compileLanguage(s, { plugins: o }) { + function langRe(o, i) { + return new RegExp(source(o), 'm' + (s.case_insensitive ? 'i' : '') + (i ? 'g' : '')); + } + class MultiRegex { + constructor() { + ((this.matchIndexes = {}), + (this.regexes = []), + (this.matchAt = 1), + (this.position = 0)); + } + addRule(s, o) { + ((o.position = this.position++), + (this.matchIndexes[this.matchAt] = o), + this.regexes.push([o, s]), + (this.matchAt += + (function countMatchGroups(s) { + return new RegExp(s.toString() + '|').exec('').length - 1; + })(s) + 1)); + } + compile() { + 0 === this.regexes.length && (this.exec = () => null); + const s = this.regexes.map((s) => s[1]); + ((this.matcherRe = langRe( + (function join(s, o = '|') { + let i = 0; + return s + .map((s) => { + i += 1; + const o = i; + let u = source(s), + _ = ''; + for (; u.length > 0; ) { + const s = a.exec(u); + if (!s) { + _ += u; + break; + } + ((_ += u.substring(0, s.index)), + (u = u.substring(s.index + s[0].length)), + '\\' === s[0][0] && s[1] + ? (_ += '\\' + String(Number(s[1]) + o)) + : ((_ += s[0]), '(' === s[0] && i++)); + } + return _; + }) + .map((s) => `(${s})`) + .join(o); + })(s), + !0 + )), + (this.lastIndex = 0)); + } + exec(s) { + this.matcherRe.lastIndex = this.lastIndex; + const o = this.matcherRe.exec(s); + if (!o) return null; + const i = o.findIndex((s, o) => o > 0 && void 0 !== s), + a = this.matchIndexes[i]; + return (o.splice(0, i), Object.assign(o, a)); + } + } + class ResumableMultiRegex { + constructor() { + ((this.rules = []), + (this.multiRegexes = []), + (this.count = 0), + (this.lastIndex = 0), + (this.regexIndex = 0)); + } + getMatcher(s) { + if (this.multiRegexes[s]) return this.multiRegexes[s]; + const o = new MultiRegex(); + return ( + this.rules.slice(s).forEach(([s, i]) => o.addRule(s, i)), + o.compile(), + (this.multiRegexes[s] = o), + o + ); + } + resumingScanAtSamePosition() { + return 0 !== this.regexIndex; + } + considerAll() { + this.regexIndex = 0; + } + addRule(s, o) { + (this.rules.push([s, o]), 'begin' === o.type && this.count++); + } + exec(s) { + const o = this.getMatcher(this.regexIndex); + o.lastIndex = this.lastIndex; + let i = o.exec(s); + if (this.resumingScanAtSamePosition()) + if (i && i.index === this.lastIndex); + else { + const o = this.getMatcher(0); + ((o.lastIndex = this.lastIndex + 1), (i = o.exec(s))); + } + return ( + i && + ((this.regexIndex += i.position + 1), + this.regexIndex === this.count && this.considerAll()), + i + ); + } + } + if ( + (s.compilerExtensions || (s.compilerExtensions = []), + s.contains && s.contains.includes('self')) + ) + throw new Error( + 'ERR: contains `self` is not supported at the top-level of a language. See documentation.' + ); + return ( + (s.classNameAliases = inherit(s.classNameAliases || {})), + (function compileMode(o, i) { + const a = o; + if (o.isCompiled) return a; + ([compileMatch].forEach((s) => s(o, i)), + s.compilerExtensions.forEach((s) => s(o, i)), + (o.__beforeBegin = null), + [beginKeywords, compileIllegal, compileRelevance].forEach((s) => s(o, i)), + (o.isCompiled = !0)); + let u = null; + if ( + ('object' == typeof o.keywords && + ((u = o.keywords.$pattern), delete o.keywords.$pattern), + o.keywords && (o.keywords = compileKeywords(o.keywords, s.case_insensitive)), + o.lexemes && u) + ) + throw new Error( + 'ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ' + ); + return ( + (u = u || o.lexemes || /\w+/), + (a.keywordPatternRe = langRe(u, !0)), + i && + (o.begin || (o.begin = /\B|\b/), + (a.beginRe = langRe(o.begin)), + o.endSameAsBegin && (o.end = o.begin), + o.end || o.endsWithParent || (o.end = /\B|\b/), + o.end && (a.endRe = langRe(o.end)), + (a.terminatorEnd = source(o.end) || ''), + o.endsWithParent && + i.terminatorEnd && + (a.terminatorEnd += (o.end ? '|' : '') + i.terminatorEnd)), + o.illegal && (a.illegalRe = langRe(o.illegal)), + o.contains || (o.contains = []), + (o.contains = [].concat( + ...o.contains.map(function (s) { + return (function expandOrCloneMode(s) { + s.variants && + !s.cachedVariants && + (s.cachedVariants = s.variants.map(function (o) { + return inherit(s, { variants: null }, o); + })); + if (s.cachedVariants) return s.cachedVariants; + if (dependencyOnParent(s)) + return inherit(s, { starts: s.starts ? inherit(s.starts) : null }); + if (Object.isFrozen(s)) return inherit(s); + return s; + })('self' === s ? o : s); + }) + )), + o.contains.forEach(function (s) { + compileMode(s, a); + }), + o.starts && compileMode(o.starts, i), + (a.matcher = (function buildModeRegex(s) { + const o = new ResumableMultiRegex(); + return ( + s.contains.forEach((s) => o.addRule(s.begin, { rule: s, type: 'begin' })), + s.terminatorEnd && o.addRule(s.terminatorEnd, { type: 'end' }), + s.illegal && o.addRule(s.illegal, { type: 'illegal' }), + o + ); + })(a)), + a + ); + })(s) + ); + } + function dependencyOnParent(s) { + return !!s && (s.endsWithParent || dependencyOnParent(s.starts)); + } + function BuildVuePlugin(s) { + const o = { + props: ['language', 'code', 'autodetect'], + data: function () { + return { detectedLanguage: '', unknownLanguage: !1 }; + }, + computed: { + className() { + return this.unknownLanguage ? '' : 'hljs ' + this.detectedLanguage; + }, + highlighted() { + if (!this.autoDetect && !s.getLanguage(this.language)) + return ( + console.warn( + `The language "${this.language}" you specified could not be found.` + ), + (this.unknownLanguage = !0), + escapeHTML(this.code) + ); + let o = {}; + return ( + this.autoDetect + ? ((o = s.highlightAuto(this.code)), (this.detectedLanguage = o.language)) + : ((o = s.highlight(this.language, this.code, this.ignoreIllegals)), + (this.detectedLanguage = this.language)), + o.value + ); + }, + autoDetect() { + return ( + !this.language || + (function hasValueOrEmptyAttribute(s) { + return Boolean(s || '' === s); + })(this.autodetect) + ); + }, + ignoreIllegals: () => !0 + }, + render(s) { + return s('pre', {}, [ + s('code', { class: this.className, domProps: { innerHTML: this.highlighted } }) + ]); + } + }; + return { + Component: o, + VuePlugin: { + install(s) { + s.component('highlightjs', o); + } + } + }; + } + const ye = { + 'after:highlightElement': ({ el: s, result: o, text: i }) => { + const a = nodeStream(s); + if (!a.length) return; + const u = document.createElement('div'); + ((u.innerHTML = o.value), + (o.value = (function mergeStreams(s, o, i) { + let a = 0, + u = ''; + const _ = []; + function selectStream() { + return s.length && o.length + ? s[0].offset !== o[0].offset + ? s[0].offset < o[0].offset + ? s + : o + : 'start' === o[0].event + ? s + : o + : s.length + ? s + : o; + } + function open(s) { + function attributeString(s) { + return ' ' + s.nodeName + '="' + escapeHTML(s.value) + '"'; + } + u += '<' + tag(s) + [].map.call(s.attributes, attributeString).join('') + '>'; + } + function close(s) { + u += ''; + } + function render(s) { + ('start' === s.event ? open : close)(s.node); + } + for (; s.length || o.length; ) { + let o = selectStream(); + if ( + ((u += escapeHTML(i.substring(a, o[0].offset))), (a = o[0].offset), o === s) + ) { + _.reverse().forEach(close); + do { + (render(o.splice(0, 1)[0]), (o = selectStream())); + } while (o === s && o.length && o[0].offset === a); + _.reverse().forEach(open); + } else + ('start' === o[0].event ? _.push(o[0].node) : _.pop(), + render(o.splice(0, 1)[0])); + } + return u + escapeHTML(i.substr(a)); + })(a, nodeStream(u), i))); + } + }; + function tag(s) { + return s.nodeName.toLowerCase(); + } + function nodeStream(s) { + const o = []; + return ( + (function _nodeStream(s, i) { + for (let a = s.firstChild; a; a = a.nextSibling) + 3 === a.nodeType + ? (i += a.nodeValue.length) + : 1 === a.nodeType && + (o.push({ event: 'start', offset: i, node: a }), + (i = _nodeStream(a, i)), + tag(a).match(/br|hr|img|input/) || + o.push({ event: 'stop', offset: i, node: a })); + return i; + })(s, 0), + o + ); + } + const be = {}, + error = (s) => { + console.error(s); + }, + warn = (s, ...o) => { + console.log(`WARN: ${s}`, ...o); + }, + deprecated = (s, o) => { + be[`${s}/${o}`] || + (console.log(`Deprecated as of ${s}. ${o}`), (be[`${s}/${o}`] = !0)); + }, + Se = escapeHTML, + _e = inherit, + we = Symbol('nomatch'); + var xe = (function (s) { + const i = Object.create(null), + a = Object.create(null), + u = []; + let _ = !0; + const w = /(^(<[^>]+>|\t|)+|\n)/gm, + x = + "Could not find the language '{}', did you forget to load/include a language module?", + C = { disableAutodetect: !0, name: 'Plain text', contains: [] }; + let j = { + noHighlightRe: /^(no-?highlight)$/i, + languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i, + classPrefix: 'hljs-', + tabReplace: null, + useBR: !1, + languages: null, + __emitter: TokenTreeEmitter + }; + function shouldNotHighlight(s) { + return j.noHighlightRe.test(s); + } + function highlight(s, o, i, a) { + let u = '', + _ = ''; + 'object' == typeof o + ? ((u = s), (i = o.ignoreIllegals), (_ = o.language), (a = void 0)) + : (deprecated('10.7.0', 'highlight(lang, code, ...args) has been deprecated.'), + deprecated( + '10.7.0', + 'Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277' + ), + (_ = s), + (u = o)); + const w = { code: u, language: _ }; + fire('before:highlight', w); + const x = w.result ? w.result : _highlight(w.language, w.code, i, a); + return ((x.code = w.code), fire('after:highlight', x), x); + } + function _highlight(s, o, a, w) { + function keywordData(s, o) { + const i = L.case_insensitive ? o[0].toLowerCase() : o[0]; + return Object.prototype.hasOwnProperty.call(s.keywords, i) && s.keywords[i]; + } + function processBuffer() { + (null != U.subLanguage + ? (function processSubLanguage() { + if ('' === Y) return; + let s = null; + if ('string' == typeof U.subLanguage) { + if (!i[U.subLanguage]) return void z.addText(Y); + ((s = _highlight(U.subLanguage, Y, !0, V[U.subLanguage])), + (V[U.subLanguage] = s.top)); + } else s = highlightAuto(Y, U.subLanguage.length ? U.subLanguage : null); + (U.relevance > 0 && (Z += s.relevance), + z.addSublanguage(s.emitter, s.language)); + })() + : (function processKeywords() { + if (!U.keywords) return void z.addText(Y); + let s = 0; + U.keywordPatternRe.lastIndex = 0; + let o = U.keywordPatternRe.exec(Y), + i = ''; + for (; o; ) { + i += Y.substring(s, o.index); + const a = keywordData(U, o); + if (a) { + const [s, u] = a; + if ((z.addText(i), (i = ''), (Z += u), s.startsWith('_'))) i += o[0]; + else { + const i = L.classNameAliases[s] || s; + z.addKeyword(o[0], i); + } + } else i += o[0]; + ((s = U.keywordPatternRe.lastIndex), (o = U.keywordPatternRe.exec(Y))); + } + ((i += Y.substr(s)), z.addText(i)); + })(), + (Y = '')); + } + function startNewMode(s) { + return ( + s.className && z.openNode(L.classNameAliases[s.className] || s.className), + (U = Object.create(s, { parent: { value: U } })), + U + ); + } + function endOfMode(s, o, i) { + let a = (function startsWith(s, o) { + const i = s && s.exec(o); + return i && 0 === i.index; + })(s.endRe, i); + if (a) { + if (s['on:end']) { + const i = new Response(s); + (s['on:end'](o, i), i.isMatchIgnored && (a = !1)); + } + if (a) { + for (; s.endsParent && s.parent; ) s = s.parent; + return s; + } + } + if (s.endsWithParent) return endOfMode(s.parent, o, i); + } + function doIgnore(s) { + return 0 === U.matcher.regexIndex ? ((Y += s[0]), 1) : ((ae = !0), 0); + } + function doBeginMatch(s) { + const o = s[0], + i = s.rule, + a = new Response(i), + u = [i.__beforeBegin, i['on:begin']]; + for (const i of u) if (i && (i(s, a), a.isMatchIgnored)) return doIgnore(o); + return ( + i && + i.endSameAsBegin && + (i.endRe = (function escape(s) { + return new RegExp(s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'm'); + })(o)), + i.skip + ? (Y += o) + : (i.excludeBegin && (Y += o), + processBuffer(), + i.returnBegin || i.excludeBegin || (Y = o)), + startNewMode(i), + i.returnBegin ? 0 : o.length + ); + } + function doEndMatch(s) { + const i = s[0], + a = o.substr(s.index), + u = endOfMode(U, s, a); + if (!u) return we; + const _ = U; + _.skip + ? (Y += i) + : (_.returnEnd || _.excludeEnd || (Y += i), + processBuffer(), + _.excludeEnd && (Y = i)); + do { + (U.className && z.closeNode(), + U.skip || U.subLanguage || (Z += U.relevance), + (U = U.parent)); + } while (U !== u.parent); + return ( + u.starts && + (u.endSameAsBegin && (u.starts.endRe = u.endRe), startNewMode(u.starts)), + _.returnEnd ? 0 : i.length + ); + } + let C = {}; + function processLexeme(i, u) { + const w = u && u[0]; + if (((Y += i), null == w)) return (processBuffer(), 0); + if ('begin' === C.type && 'end' === u.type && C.index === u.index && '' === w) { + if (((Y += o.slice(u.index, u.index + 1)), !_)) { + const o = new Error('0 width match regex'); + throw ((o.languageName = s), (o.badRule = C.rule), o); + } + return 1; + } + if (((C = u), 'begin' === u.type)) return doBeginMatch(u); + if ('illegal' === u.type && !a) { + const s = new Error( + 'Illegal lexeme "' + w + '" for mode "' + (U.className || '') + '"' + ); + throw ((s.mode = U), s); + } + if ('end' === u.type) { + const s = doEndMatch(u); + if (s !== we) return s; + } + if ('illegal' === u.type && '' === w) return 1; + if (ie > 1e5 && ie > 3 * u.index) { + throw new Error('potential infinite loop, way more iterations than matches'); + } + return ((Y += w), w.length); + } + const L = getLanguage(s); + if (!L) throw (error(x.replace('{}', s)), new Error('Unknown language: "' + s + '"')); + const B = compileLanguage(L, { plugins: u }); + let $ = '', + U = w || B; + const V = {}, + z = new j.__emitter(j); + !(function processContinuations() { + const s = []; + for (let o = U; o !== L; o = o.parent) o.className && s.unshift(o.className); + s.forEach((s) => z.openNode(s)); + })(); + let Y = '', + Z = 0, + ee = 0, + ie = 0, + ae = !1; + try { + for (U.matcher.considerAll(); ; ) { + (ie++, ae ? (ae = !1) : U.matcher.considerAll(), (U.matcher.lastIndex = ee)); + const s = U.matcher.exec(o); + if (!s) break; + const i = processLexeme(o.substring(ee, s.index), s); + ee = s.index + i; + } + return ( + processLexeme(o.substr(ee)), + z.closeAllNodes(), + z.finalize(), + ($ = z.toHTML()), + { + relevance: Math.floor(Z), + value: $, + language: s, + illegal: !1, + emitter: z, + top: U + } + ); + } catch (i) { + if (i.message && i.message.includes('Illegal')) + return { + illegal: !0, + illegalBy: { + msg: i.message, + context: o.slice(ee - 100, ee + 100), + mode: i.mode + }, + sofar: $, + relevance: 0, + value: Se(o), + emitter: z + }; + if (_) + return { + illegal: !1, + relevance: 0, + value: Se(o), + emitter: z, + language: s, + top: U, + errorRaised: i + }; + throw i; + } + } + function highlightAuto(s, o) { + o = o || j.languages || Object.keys(i); + const a = (function justTextHighlightResult(s) { + const o = { + relevance: 0, + emitter: new j.__emitter(j), + value: Se(s), + illegal: !1, + top: C + }; + return (o.emitter.addText(s), o); + })(s), + u = o + .filter(getLanguage) + .filter(autoDetection) + .map((o) => _highlight(o, s, !1)); + u.unshift(a); + const _ = u.sort((s, o) => { + if (s.relevance !== o.relevance) return o.relevance - s.relevance; + if (s.language && o.language) { + if (getLanguage(s.language).supersetOf === o.language) return 1; + if (getLanguage(o.language).supersetOf === s.language) return -1; + } + return 0; + }), + [w, x] = _, + L = w; + return ((L.second_best = x), L); + } + const L = { + 'before:highlightElement': ({ el: s }) => { + j.useBR && + (s.innerHTML = s.innerHTML.replace(/\n/g, '').replace(//g, '\n')); + }, + 'after:highlightElement': ({ result: s }) => { + j.useBR && (s.value = s.value.replace(/\n/g, '
')); + } + }, + B = /^(<[^>]+>|\t)+/gm, + $ = { + 'after:highlightElement': ({ result: s }) => { + j.tabReplace && + (s.value = s.value.replace(B, (s) => s.replace(/\t/g, j.tabReplace))); + } + }; + function highlightElement(s) { + let o = null; + const i = (function blockLanguage(s) { + let o = s.className + ' '; + o += s.parentNode ? s.parentNode.className : ''; + const i = j.languageDetectRe.exec(o); + if (i) { + const o = getLanguage(i[1]); + return ( + o || + (warn(x.replace('{}', i[1])), + warn('Falling back to no-highlight mode for this block.', s)), + o ? i[1] : 'no-highlight' + ); + } + return o.split(/\s+/).find((s) => shouldNotHighlight(s) || getLanguage(s)); + })(s); + if (shouldNotHighlight(i)) return; + (fire('before:highlightElement', { el: s, language: i }), (o = s)); + const u = o.textContent, + _ = i ? highlight(u, { language: i, ignoreIllegals: !0 }) : highlightAuto(u); + (fire('after:highlightElement', { el: s, result: _, text: u }), + (s.innerHTML = _.value), + (function updateClassName(s, o, i) { + const u = o ? a[o] : i; + (s.classList.add('hljs'), u && s.classList.add(u)); + })(s, i, _.language), + (s.result = { language: _.language, re: _.relevance, relavance: _.relevance }), + _.second_best && + (s.second_best = { + language: _.second_best.language, + re: _.second_best.relevance, + relavance: _.second_best.relevance + })); + } + const initHighlighting = () => { + if (initHighlighting.called) return; + ((initHighlighting.called = !0), + deprecated( + '10.6.0', + 'initHighlighting() is deprecated. Use highlightAll() instead.' + )); + document.querySelectorAll('pre code').forEach(highlightElement); + }; + let U = !1; + function highlightAll() { + if ('loading' === document.readyState) return void (U = !0); + document.querySelectorAll('pre code').forEach(highlightElement); + } + function getLanguage(s) { + return ((s = (s || '').toLowerCase()), i[s] || i[a[s]]); + } + function registerAliases(s, { languageName: o }) { + ('string' == typeof s && (s = [s]), + s.forEach((s) => { + a[s.toLowerCase()] = o; + })); + } + function autoDetection(s) { + const o = getLanguage(s); + return o && !o.disableAutodetect; + } + function fire(s, o) { + const i = s; + u.forEach(function (s) { + s[i] && s[i](o); + }); + } + ('undefined' != typeof window && + window.addEventListener && + window.addEventListener( + 'DOMContentLoaded', + function boot() { + U && highlightAll(); + }, + !1 + ), + Object.assign(s, { + highlight, + highlightAuto, + highlightAll, + fixMarkup: function deprecateFixMarkup(s) { + return ( + deprecated('10.2.0', 'fixMarkup will be removed entirely in v11.0'), + deprecated( + '10.2.0', + 'Please see https://github.com/highlightjs/highlight.js/issues/2534' + ), + (function fixMarkup(s) { + return j.tabReplace || j.useBR + ? s.replace(w, (s) => + '\n' === s + ? j.useBR + ? '
' + : s + : j.tabReplace + ? s.replace(/\t/g, j.tabReplace) + : s + ) + : s; + })(s) + ); + }, + highlightElement, + highlightBlock: function deprecateHighlightBlock(s) { + return ( + deprecated('10.7.0', 'highlightBlock will be removed entirely in v12.0'), + deprecated('10.7.0', 'Please use highlightElement now.'), + highlightElement(s) + ); + }, + configure: function configure(s) { + (s.useBR && + (deprecated('10.3.0', "'useBR' will be removed entirely in v11.0"), + deprecated( + '10.3.0', + 'Please see https://github.com/highlightjs/highlight.js/issues/2559' + )), + (j = _e(j, s))); + }, + initHighlighting, + initHighlightingOnLoad: function initHighlightingOnLoad() { + (deprecated( + '10.6.0', + 'initHighlightingOnLoad() is deprecated. Use highlightAll() instead.' + ), + (U = !0)); + }, + registerLanguage: function registerLanguage(o, a) { + let u = null; + try { + u = a(s); + } catch (s) { + if ( + (error( + "Language definition for '{}' could not be registered.".replace('{}', o) + ), + !_) + ) + throw s; + (error(s), (u = C)); + } + (u.name || (u.name = o), + (i[o] = u), + (u.rawDefinition = a.bind(null, s)), + u.aliases && registerAliases(u.aliases, { languageName: o })); + }, + unregisterLanguage: function unregisterLanguage(s) { + delete i[s]; + for (const o of Object.keys(a)) a[o] === s && delete a[o]; + }, + listLanguages: function listLanguages() { + return Object.keys(i); + }, + getLanguage, + registerAliases, + requireLanguage: function requireLanguage(s) { + (deprecated('10.4.0', 'requireLanguage will be removed entirely in v11.'), + deprecated( + '10.4.0', + 'Please see https://github.com/highlightjs/highlight.js/pull/2844' + )); + const o = getLanguage(s); + if (o) return o; + throw new Error( + "The '{}' language is required, but not loaded.".replace('{}', s) + ); + }, + autoDetection, + inherit: _e, + addPlugin: function addPlugin(s) { + (!(function upgradePluginAPI(s) { + (s['before:highlightBlock'] && + !s['before:highlightElement'] && + (s['before:highlightElement'] = (o) => { + s['before:highlightBlock'](Object.assign({ block: o.el }, o)); + }), + s['after:highlightBlock'] && + !s['after:highlightElement'] && + (s['after:highlightElement'] = (o) => { + s['after:highlightBlock'](Object.assign({ block: o.el }, o)); + })); + })(s), + u.push(s)); + }, + vuePlugin: BuildVuePlugin(s).VuePlugin + }), + (s.debugMode = function () { + _ = !1; + }), + (s.safeMode = function () { + _ = !0; + }), + (s.versionString = '10.7.3')); + for (const s in de) 'object' == typeof de[s] && o(de[s]); + return (Object.assign(s, de), s.addPlugin(L), s.addPlugin(ye), s.addPlugin($), s); + })({}); + s.exports = xe; + }, + 35344(s) { + function concat(...s) { + return s + .map((s) => + (function source(s) { + return s ? ('string' == typeof s ? s : s.source) : null; + })(s) + ) + .join(''); + } + s.exports = function bash(s) { + const o = {}, + i = { begin: /\$\{/, end: /\}/, contains: ['self', { begin: /:-/, contains: [o] }] }; + Object.assign(o, { + className: 'variable', + variants: [{ begin: concat(/\$[\w\d#@][\w\d_]*/, '(?![\\w\\d])(?![$])') }, i] + }); + const a = { + className: 'subst', + begin: /\$\(/, + end: /\)/, + contains: [s.BACKSLASH_ESCAPE] + }, + u = { + begin: /<<-?\s*(?=\w+)/, + starts: { + contains: [ + s.END_SAME_AS_BEGIN({ begin: /(\w+)/, end: /(\w+)/, className: 'string' }) + ] + } + }, + _ = { + className: 'string', + begin: /"/, + end: /"/, + contains: [s.BACKSLASH_ESCAPE, o, a] + }; + a.contains.push(_); + const w = { + begin: /\$\(\(/, + end: /\)\)/, + contains: [{ begin: /\d+#[0-9a-f]+/, className: 'number' }, s.NUMBER_MODE, o] + }, + x = s.SHEBANG({ + binary: `(${['fish', 'bash', 'zsh', 'sh', 'csh', 'ksh', 'tcsh', 'dash', 'scsh'].join('|')})`, + relevance: 10 + }), + C = { + className: 'function', + begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/, + returnBegin: !0, + contains: [s.inherit(s.TITLE_MODE, { begin: /\w[\w\d_]*/ })], + relevance: 0 + }; + return { + name: 'Bash', + aliases: ['sh', 'zsh'], + keywords: { + $pattern: /\b[a-z._-]+\b/, + keyword: 'if then else elif fi for while in do done case esac function', + literal: 'true false', + built_in: + 'break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp' + }, + contains: [ + x, + s.SHEBANG(), + C, + w, + s.HASH_COMMENT_MODE, + u, + _, + { className: '', begin: /\\"/ }, + { className: 'string', begin: /'/, end: /'/ }, + o + ] + }; + }; + }, + 73402(s) { + function concat(...s) { + return s + .map((s) => + (function source(s) { + return s ? ('string' == typeof s ? s : s.source) : null; + })(s) + ) + .join(''); + } + s.exports = function http(s) { + const o = 'HTTP/(2|1\\.[01])', + i = { + className: 'attribute', + begin: concat('^', /[A-Za-z][A-Za-z0-9-]*/, '(?=\\:\\s)'), + starts: { + contains: [ + { + className: 'punctuation', + begin: /: /, + relevance: 0, + starts: { end: '$', relevance: 0 } + } + ] + } + }, + a = [i, { begin: '\\n\\n', starts: { subLanguage: [], endsWithParent: !0 } }]; + return { + name: 'HTTP', + aliases: ['https'], + illegal: /\S/, + contains: [ + { + begin: '^(?=' + o + ' \\d{3})', + end: /$/, + contains: [ + { className: 'meta', begin: o }, + { className: 'number', begin: '\\b\\d{3}\\b' } + ], + starts: { end: /\b\B/, illegal: /\S/, contains: a } + }, + { + begin: '(?=^[A-Z]+ (.*?) ' + o + '$)', + end: /$/, + contains: [ + { className: 'string', begin: ' ', end: ' ', excludeBegin: !0, excludeEnd: !0 }, + { className: 'meta', begin: o }, + { className: 'keyword', begin: '[A-Z]+' } + ], + starts: { end: /\b\B/, illegal: /\S/, contains: a } + }, + s.inherit(i, { relevance: 0 }) + ] + }; + }; + }, + 95089(s) { + const o = '[A-Za-z$_][0-9A-Za-z$_]*', + i = [ + 'as', + 'in', + 'of', + 'if', + 'for', + 'while', + 'finally', + 'var', + 'new', + 'function', + 'do', + 'return', + 'void', + 'else', + 'break', + 'catch', + 'instanceof', + 'with', + 'throw', + 'case', + 'default', + 'try', + 'switch', + 'continue', + 'typeof', + 'delete', + 'let', + 'yield', + 'const', + 'class', + 'debugger', + 'async', + 'await', + 'static', + 'import', + 'from', + 'export', + 'extends' + ], + a = ['true', 'false', 'null', 'undefined', 'NaN', 'Infinity'], + u = [].concat( + [ + 'setInterval', + 'setTimeout', + 'clearInterval', + 'clearTimeout', + 'require', + 'exports', + 'eval', + 'isFinite', + 'isNaN', + 'parseFloat', + 'parseInt', + 'decodeURI', + 'decodeURIComponent', + 'encodeURI', + 'encodeURIComponent', + 'escape', + 'unescape' + ], + [ + 'arguments', + 'this', + 'super', + 'console', + 'window', + 'document', + 'localStorage', + 'module', + 'global' + ], + [ + 'Intl', + 'DataView', + 'Number', + 'Math', + 'Date', + 'String', + 'RegExp', + 'Object', + 'Function', + 'Boolean', + 'Error', + 'Symbol', + 'Set', + 'Map', + 'WeakSet', + 'WeakMap', + 'Proxy', + 'Reflect', + 'JSON', + 'Promise', + 'Float64Array', + 'Int16Array', + 'Int32Array', + 'Int8Array', + 'Uint16Array', + 'Uint32Array', + 'Float32Array', + 'Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'ArrayBuffer', + 'BigInt64Array', + 'BigUint64Array', + 'BigInt' + ], + [ + 'EvalError', + 'InternalError', + 'RangeError', + 'ReferenceError', + 'SyntaxError', + 'TypeError', + 'URIError' + ] + ); + function lookahead(s) { + return concat('(?=', s, ')'); + } + function concat(...s) { + return s + .map((s) => + (function source(s) { + return s ? ('string' == typeof s ? s : s.source) : null; + })(s) + ) + .join(''); + } + s.exports = function javascript(s) { + const _ = o, + w = '<>', + x = '', + C = { + begin: /<[A-Za-z0-9\\._:-]+/, + end: /\/[A-Za-z0-9\\._:-]+>|\/>/, + isTrulyOpeningTag: (s, o) => { + const i = s[0].length + s.index, + a = s.input[i]; + '<' !== a + ? '>' === a && + (((s, { after: o }) => { + const i = '', + returnBegin: !0, + end: '\\s*=>', + contains: [ + { + className: 'params', + variants: [ + { begin: s.UNDERSCORE_IDENT_RE, relevance: 0 }, + { className: null, begin: /\(\s*\)/, skip: !0 }, + { + begin: /\(/, + end: /\)/, + excludeBegin: !0, + excludeEnd: !0, + keywords: j, + contains: ce + } + ] + } + ] + }, + { begin: /,/, relevance: 0 }, + { className: '', begin: /\s/, end: /\s*/, skip: !0 }, + { + variants: [ + { begin: w, end: x }, + { begin: C.begin, 'on:begin': C.isTrulyOpeningTag, end: C.end } + ], + subLanguage: 'xml', + contains: [{ begin: C.begin, end: C.end, skip: !0, contains: ['self'] }] + } + ], + relevance: 0 + }, + { + className: 'function', + beginKeywords: 'function', + end: /[{;]/, + excludeEnd: !0, + keywords: j, + contains: ['self', s.inherit(s.TITLE_MODE, { begin: _ }), le], + illegal: /%/ + }, + { beginKeywords: 'while if switch catch for' }, + { + className: 'function', + begin: + s.UNDERSCORE_IDENT_RE + + '\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{', + returnBegin: !0, + contains: [le, s.inherit(s.TITLE_MODE, { begin: _ })] + }, + { variants: [{ begin: '\\.' + _ }, { begin: '\\$' + _ }], relevance: 0 }, + { + className: 'class', + beginKeywords: 'class', + end: /[{;=]/, + excludeEnd: !0, + illegal: /[:"[\]]/, + contains: [{ beginKeywords: 'extends' }, s.UNDERSCORE_TITLE_MODE] + }, + { + begin: /\b(?=constructor)/, + end: /[{;]/, + excludeEnd: !0, + contains: [s.inherit(s.TITLE_MODE, { begin: _ }), 'self', le] + }, + { + begin: '(get|set)\\s+(?=' + _ + '\\()', + end: /\{/, + keywords: 'get set', + contains: [s.inherit(s.TITLE_MODE, { begin: _ }), { begin: /\(\)/ }, le] + }, + { begin: /\$[(.]/ } + ] + }; + }; + }, + 65772(s) { + s.exports = function json(s) { + const o = { literal: 'true false null' }, + i = [s.C_LINE_COMMENT_MODE, s.C_BLOCK_COMMENT_MODE], + a = [s.QUOTE_STRING_MODE, s.C_NUMBER_MODE], + u = { end: ',', endsWithParent: !0, excludeEnd: !0, contains: a, keywords: o }, + _ = { + begin: /\{/, + end: /\}/, + contains: [ + { + className: 'attr', + begin: /"/, + end: /"/, + contains: [s.BACKSLASH_ESCAPE], + illegal: '\\n' + }, + s.inherit(u, { begin: /:/ }) + ].concat(i), + illegal: '\\S' + }, + w = { begin: '\\[', end: '\\]', contains: [s.inherit(u)], illegal: '\\S' }; + return ( + a.push(_, w), + i.forEach(function (s) { + a.push(s); + }), + { name: 'JSON', contains: a, keywords: o, illegal: '\\S' } + ); + }; + }, + 26571(s) { + s.exports = function powershell(s) { + const o = { + $pattern: /-?[A-z\.\-]+\b/, + keyword: + 'if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter', + built_in: + 'ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write' + }, + i = { begin: '`[\\s\\S]', relevance: 0 }, + a = { + className: 'variable', + variants: [ + { begin: /\$\B/ }, + { className: 'keyword', begin: /\$this/ }, + { begin: /\$[\w\d][\w\d_:]*/ } + ] + }, + u = { + className: 'string', + variants: [ + { begin: /"/, end: /"/ }, + { begin: /@"/, end: /^"@/ } + ], + contains: [i, a, { className: 'variable', begin: /\$[A-z]/, end: /[^A-z]/ }] + }, + _ = { + className: 'string', + variants: [ + { begin: /'/, end: /'/ }, + { begin: /@'/, end: /^'@/ } + ] + }, + w = s.inherit(s.COMMENT(null, null), { + variants: [ + { begin: /#/, end: /$/ }, + { begin: /<#/, end: /#>/ } + ], + contains: [ + { + className: 'doctag', + variants: [ + { + begin: + /\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/ + }, + { + begin: + /\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/ + } + ] + } + ] + }), + x = { + className: 'built_in', + variants: [ + { + begin: '('.concat( + 'Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where', + ')+(-)[\\w\\d]+' + ) + } + ] + }, + C = { + className: 'class', + beginKeywords: 'class enum', + end: /\s*[{]/, + excludeEnd: !0, + relevance: 0, + contains: [s.TITLE_MODE] + }, + j = { + className: 'function', + begin: /function\s+/, + end: /\s*\{|$/, + excludeEnd: !0, + returnBegin: !0, + relevance: 0, + contains: [ + { begin: 'function', relevance: 0, className: 'keyword' }, + { className: 'title', begin: /\w[\w\d]*((-)[\w\d]+)*/, relevance: 0 }, + { begin: /\(/, end: /\)/, className: 'params', relevance: 0, contains: [a] } + ] + }, + L = { + begin: /using\s/, + end: /$/, + returnBegin: !0, + contains: [ + u, + _, + { className: 'keyword', begin: /(using|assembly|command|module|namespace|type)/ } + ] + }, + B = { + variants: [ + { + className: 'operator', + begin: '('.concat( + '-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor', + ')\\b' + ) + }, + { className: 'literal', begin: /(-)[\w\d]+/, relevance: 0 } + ] + }, + $ = { + className: 'function', + begin: /\[.*\]\s*[\w]+[ ]??\(/, + end: /$/, + returnBegin: !0, + relevance: 0, + contains: [ + { + className: 'keyword', + begin: '('.concat(o.keyword.toString().replace(/\s/g, '|'), ')\\b'), + endsParent: !0, + relevance: 0 + }, + s.inherit(s.TITLE_MODE, { endsParent: !0 }) + ] + }, + U = [ + $, + w, + i, + s.NUMBER_MODE, + u, + _, + x, + a, + { className: 'literal', begin: /\$(null|true|false)\b/ }, + { className: 'selector-tag', begin: /@\B/, relevance: 0 } + ], + V = { + begin: /\[/, + end: /\]/, + excludeBegin: !0, + excludeEnd: !0, + relevance: 0, + contains: [].concat( + 'self', + U, + { + begin: + '(' + + [ + 'string', + 'char', + 'byte', + 'int', + 'long', + 'bool', + 'decimal', + 'single', + 'double', + 'DateTime', + 'xml', + 'array', + 'hashtable', + 'void' + ].join('|') + + ')', + className: 'built_in', + relevance: 0 + }, + { className: 'type', begin: /[\.\w\d]+/, relevance: 0 } + ) + }; + return ( + $.contains.unshift(V), + { + name: 'PowerShell', + aliases: ['ps', 'ps1'], + case_insensitive: !0, + keywords: o, + contains: U.concat(C, j, L, B, V) + } + ); + }; + }, + 17285(s) { + function source(s) { + return s ? ('string' == typeof s ? s : s.source) : null; + } + function lookahead(s) { + return concat('(?=', s, ')'); + } + function concat(...s) { + return s.map((s) => source(s)).join(''); + } + function either(...s) { + return '(' + s.map((s) => source(s)).join('|') + ')'; + } + s.exports = function xml(s) { + const o = concat( + /[A-Z_]/, + (function optional(s) { + return concat('(', s, ')?'); + })(/[A-Z0-9_.-]*:/), + /[A-Z0-9_.-]*/ + ), + i = { className: 'symbol', begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/ }, + a = { + begin: /\s/, + contains: [ + { className: 'meta-keyword', begin: /#?[a-z_][a-z1-9_-]+/, illegal: /\n/ } + ] + }, + u = s.inherit(a, { begin: /\(/, end: /\)/ }), + _ = s.inherit(s.APOS_STRING_MODE, { className: 'meta-string' }), + w = s.inherit(s.QUOTE_STRING_MODE, { className: 'meta-string' }), + x = { + endsWithParent: !0, + illegal: /`]+/ } + ] + } + ] + } + ] + }; + return { + name: 'HTML, XML', + aliases: ['html', 'xhtml', 'rss', 'atom', 'xjb', 'xsd', 'xsl', 'plist', 'wsf', 'svg'], + case_insensitive: !0, + contains: [ + { + className: 'meta', + begin: //, + relevance: 10, + contains: [ + a, + w, + _, + u, + { + begin: /\[/, + end: /\]/, + contains: [ + { className: 'meta', begin: //, contains: [a, u, w, _] } + ] + } + ] + }, + s.COMMENT(//, { relevance: 10 }), + { begin: //, relevance: 10 }, + i, + { className: 'meta', begin: /<\?xml/, end: /\?>/, relevance: 10 }, + { + className: 'tag', + begin: /)/, + end: />/, + keywords: { name: 'style' }, + contains: [x], + starts: { end: /<\/style>/, returnEnd: !0, subLanguage: ['css', 'xml'] } + }, + { + className: 'tag', + begin: /)/, + end: />/, + keywords: { name: 'script' }, + contains: [x], + starts: { + end: /<\/script>/, + returnEnd: !0, + subLanguage: ['javascript', 'handlebars', 'xml'] + } + }, + { className: 'tag', begin: /<>|<\/>/ }, + { + className: 'tag', + begin: concat(//, />/, /\s/)))), + end: /\/?>/, + contains: [{ className: 'name', begin: o, relevance: 0, starts: x }] + }, + { + className: 'tag', + begin: concat(/<\//, lookahead(concat(o, />/))), + contains: [ + { className: 'name', begin: o, relevance: 0 }, + { begin: />/, relevance: 0, endsParent: !0 } + ] + } + ] + }; + }; + }, + 17533(s) { + s.exports = function yaml(s) { + var o = 'true false yes no null', + i = "[\\w#;/?:@&=+$,.~*'()[\\]]+", + a = { + className: 'string', + relevance: 0, + variants: [{ begin: /'/, end: /'/ }, { begin: /"/, end: /"/ }, { begin: /\S+/ }], + contains: [ + s.BACKSLASH_ESCAPE, + { + className: 'template-variable', + variants: [ + { begin: /\{\{/, end: /\}\}/ }, + { begin: /%\{/, end: /\}/ } + ] + } + ] + }, + u = s.inherit(a, { + variants: [ + { begin: /'/, end: /'/ }, + { begin: /"/, end: /"/ }, + { begin: /[^\s,{}[\]]+/ } + ] + }), + _ = { + className: 'number', + begin: + '\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b' + }, + w = { end: ',', endsWithParent: !0, excludeEnd: !0, keywords: o, relevance: 0 }, + x = { begin: /\{/, end: /\}/, contains: [w], illegal: '\\n', relevance: 0 }, + C = { begin: '\\[', end: '\\]', contains: [w], illegal: '\\n', relevance: 0 }, + j = [ + { + className: 'attr', + variants: [ + { begin: '\\w[\\w :\\/.-]*:(?=[ \t]|$)' }, + { begin: '"\\w[\\w :\\/.-]*":(?=[ \t]|$)' }, + { begin: "'\\w[\\w :\\/.-]*':(?=[ \t]|$)" } + ] + }, + { className: 'meta', begin: '^---\\s*$', relevance: 10 }, + { + className: 'string', + begin: '[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*' + }, + { + begin: '<%[%=-]?', + end: '[%-]?%>', + subLanguage: 'ruby', + excludeBegin: !0, + excludeEnd: !0, + relevance: 0 + }, + { className: 'type', begin: '!\\w+!' + i }, + { className: 'type', begin: '!<' + i + '>' }, + { className: 'type', begin: '!' + i }, + { className: 'type', begin: '!!' + i }, + { className: 'meta', begin: '&' + s.UNDERSCORE_IDENT_RE + '$' }, + { className: 'meta', begin: '\\*' + s.UNDERSCORE_IDENT_RE + '$' }, + { className: 'bullet', begin: '-(?=[ ]|$)', relevance: 0 }, + s.HASH_COMMENT_MODE, + { beginKeywords: o, keywords: { literal: o } }, + _, + { className: 'number', begin: s.C_NUMBER_RE + '\\b', relevance: 0 }, + x, + C, + a + ], + L = [...j]; + return ( + L.pop(), + L.push(u), + (w.contains = L), + { name: 'YAML', case_insensitive: !0, aliases: ['yml'], contains: j } + ); + }; + }, + 251(s, o) { + ((o.read = function (s, o, i, a, u) { + var _, + w, + x = 8 * u - a - 1, + C = (1 << x) - 1, + j = C >> 1, + L = -7, + B = i ? u - 1 : 0, + $ = i ? -1 : 1, + U = s[o + B]; + for ( + B += $, _ = U & ((1 << -L) - 1), U >>= -L, L += x; + L > 0; + _ = 256 * _ + s[o + B], B += $, L -= 8 + ); + for ( + w = _ & ((1 << -L) - 1), _ >>= -L, L += a; + L > 0; + w = 256 * w + s[o + B], B += $, L -= 8 + ); + if (0 === _) _ = 1 - j; + else { + if (_ === C) return w ? NaN : (1 / 0) * (U ? -1 : 1); + ((w += Math.pow(2, a)), (_ -= j)); + } + return (U ? -1 : 1) * w * Math.pow(2, _ - a); + }), + (o.write = function (s, o, i, a, u, _) { + var w, + x, + C, + j = 8 * _ - u - 1, + L = (1 << j) - 1, + B = L >> 1, + $ = 23 === u ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + U = a ? 0 : _ - 1, + V = a ? 1 : -1, + z = o < 0 || (0 === o && 1 / o < 0) ? 1 : 0; + for ( + o = Math.abs(o), + isNaN(o) || o === 1 / 0 + ? ((x = isNaN(o) ? 1 : 0), (w = L)) + : ((w = Math.floor(Math.log(o) / Math.LN2)), + o * (C = Math.pow(2, -w)) < 1 && (w--, (C *= 2)), + (o += w + B >= 1 ? $ / C : $ * Math.pow(2, 1 - B)) * C >= 2 && + (w++, (C /= 2)), + w + B >= L + ? ((x = 0), (w = L)) + : w + B >= 1 + ? ((x = (o * C - 1) * Math.pow(2, u)), (w += B)) + : ((x = o * Math.pow(2, B - 1) * Math.pow(2, u)), (w = 0))); + u >= 8; + s[i + U] = 255 & x, U += V, x /= 256, u -= 8 + ); + for (w = (w << u) | x, j += u; j > 0; s[i + U] = 255 & w, U += V, w /= 256, j -= 8); + s[i + U - V] |= 128 * z; + })); + }, + 9404(s) { + s.exports = (function () { + 'use strict'; + var s = Array.prototype.slice; + function createClass(s, o) { + (o && (s.prototype = Object.create(o.prototype)), (s.prototype.constructor = s)); + } + function Iterable(s) { + return isIterable(s) ? s : Seq(s); + } + function KeyedIterable(s) { + return isKeyed(s) ? s : KeyedSeq(s); + } + function IndexedIterable(s) { + return isIndexed(s) ? s : IndexedSeq(s); + } + function SetIterable(s) { + return isIterable(s) && !isAssociative(s) ? s : SetSeq(s); + } + function isIterable(s) { + return !(!s || !s[o]); + } + function isKeyed(s) { + return !(!s || !s[i]); + } + function isIndexed(s) { + return !(!s || !s[a]); + } + function isAssociative(s) { + return isKeyed(s) || isIndexed(s); + } + function isOrdered(s) { + return !(!s || !s[u]); + } + (createClass(KeyedIterable, Iterable), + createClass(IndexedIterable, Iterable), + createClass(SetIterable, Iterable), + (Iterable.isIterable = isIterable), + (Iterable.isKeyed = isKeyed), + (Iterable.isIndexed = isIndexed), + (Iterable.isAssociative = isAssociative), + (Iterable.isOrdered = isOrdered), + (Iterable.Keyed = KeyedIterable), + (Iterable.Indexed = IndexedIterable), + (Iterable.Set = SetIterable)); + var o = '@@__IMMUTABLE_ITERABLE__@@', + i = '@@__IMMUTABLE_KEYED__@@', + a = '@@__IMMUTABLE_INDEXED__@@', + u = '@@__IMMUTABLE_ORDERED__@@', + _ = 'delete', + w = 5, + x = 1 << w, + C = x - 1, + j = {}, + L = { value: !1 }, + B = { value: !1 }; + function MakeRef(s) { + return ((s.value = !1), s); + } + function SetRef(s) { + s && (s.value = !0); + } + function OwnerID() {} + function arrCopy(s, o) { + o = o || 0; + for (var i = Math.max(0, s.length - o), a = new Array(i), u = 0; u < i; u++) + a[u] = s[u + o]; + return a; + } + function ensureSize(s) { + return (void 0 === s.size && (s.size = s.__iterate(returnTrue)), s.size); + } + function wrapIndex(s, o) { + if ('number' != typeof o) { + var i = o >>> 0; + if ('' + i !== o || 4294967295 === i) return NaN; + o = i; + } + return o < 0 ? ensureSize(s) + o : o; + } + function returnTrue() { + return !0; + } + function wholeSlice(s, o, i) { + return ( + (0 === s || (void 0 !== i && s <= -i)) && (void 0 === o || (void 0 !== i && o >= i)) + ); + } + function resolveBegin(s, o) { + return resolveIndex(s, o, 0); + } + function resolveEnd(s, o) { + return resolveIndex(s, o, o); + } + function resolveIndex(s, o, i) { + return void 0 === s + ? i + : s < 0 + ? Math.max(0, o + s) + : void 0 === o + ? s + : Math.min(o, s); + } + var $ = 0, + U = 1, + V = 2, + z = 'function' == typeof Symbol && Symbol.iterator, + Y = '@@iterator', + Z = z || Y; + function Iterator(s) { + this.next = s; + } + function iteratorValue(s, o, i, a) { + var u = 0 === s ? o : 1 === s ? i : [o, i]; + return (a ? (a.value = u) : (a = { value: u, done: !1 }), a); + } + function iteratorDone() { + return { value: void 0, done: !0 }; + } + function hasIterator(s) { + return !!getIteratorFn(s); + } + function isIterator(s) { + return s && 'function' == typeof s.next; + } + function getIterator(s) { + var o = getIteratorFn(s); + return o && o.call(s); + } + function getIteratorFn(s) { + var o = s && ((z && s[z]) || s[Y]); + if ('function' == typeof o) return o; + } + function isArrayLike(s) { + return s && 'number' == typeof s.length; + } + function Seq(s) { + return null == s ? emptySequence() : isIterable(s) ? s.toSeq() : seqFromValue(s); + } + function KeyedSeq(s) { + return null == s + ? emptySequence().toKeyedSeq() + : isIterable(s) + ? isKeyed(s) + ? s.toSeq() + : s.fromEntrySeq() + : keyedSeqFromValue(s); + } + function IndexedSeq(s) { + return null == s + ? emptySequence() + : isIterable(s) + ? isKeyed(s) + ? s.entrySeq() + : s.toIndexedSeq() + : indexedSeqFromValue(s); + } + function SetSeq(s) { + return ( + null == s + ? emptySequence() + : isIterable(s) + ? isKeyed(s) + ? s.entrySeq() + : s + : indexedSeqFromValue(s) + ).toSetSeq(); + } + ((Iterator.prototype.toString = function () { + return '[Iterator]'; + }), + (Iterator.KEYS = $), + (Iterator.VALUES = U), + (Iterator.ENTRIES = V), + (Iterator.prototype.inspect = Iterator.prototype.toSource = + function () { + return this.toString(); + }), + (Iterator.prototype[Z] = function () { + return this; + }), + createClass(Seq, Iterable), + (Seq.of = function () { + return Seq(arguments); + }), + (Seq.prototype.toSeq = function () { + return this; + }), + (Seq.prototype.toString = function () { + return this.__toString('Seq {', '}'); + }), + (Seq.prototype.cacheResult = function () { + return ( + !this._cache && + this.__iterateUncached && + ((this._cache = this.entrySeq().toArray()), (this.size = this._cache.length)), + this + ); + }), + (Seq.prototype.__iterate = function (s, o) { + return seqIterate(this, s, o, !0); + }), + (Seq.prototype.__iterator = function (s, o) { + return seqIterator(this, s, o, !0); + }), + createClass(KeyedSeq, Seq), + (KeyedSeq.prototype.toKeyedSeq = function () { + return this; + }), + createClass(IndexedSeq, Seq), + (IndexedSeq.of = function () { + return IndexedSeq(arguments); + }), + (IndexedSeq.prototype.toIndexedSeq = function () { + return this; + }), + (IndexedSeq.prototype.toString = function () { + return this.__toString('Seq [', ']'); + }), + (IndexedSeq.prototype.__iterate = function (s, o) { + return seqIterate(this, s, o, !1); + }), + (IndexedSeq.prototype.__iterator = function (s, o) { + return seqIterator(this, s, o, !1); + }), + createClass(SetSeq, Seq), + (SetSeq.of = function () { + return SetSeq(arguments); + }), + (SetSeq.prototype.toSetSeq = function () { + return this; + }), + (Seq.isSeq = isSeq), + (Seq.Keyed = KeyedSeq), + (Seq.Set = SetSeq), + (Seq.Indexed = IndexedSeq)); + var ee, + ie, + ae, + ce = '@@__IMMUTABLE_SEQ__@@'; + function ArraySeq(s) { + ((this._array = s), (this.size = s.length)); + } + function ObjectSeq(s) { + var o = Object.keys(s); + ((this._object = s), (this._keys = o), (this.size = o.length)); + } + function IterableSeq(s) { + ((this._iterable = s), (this.size = s.length || s.size)); + } + function IteratorSeq(s) { + ((this._iterator = s), (this._iteratorCache = [])); + } + function isSeq(s) { + return !(!s || !s[ce]); + } + function emptySequence() { + return ee || (ee = new ArraySeq([])); + } + function keyedSeqFromValue(s) { + var o = Array.isArray(s) + ? new ArraySeq(s).fromEntrySeq() + : isIterator(s) + ? new IteratorSeq(s).fromEntrySeq() + : hasIterator(s) + ? new IterableSeq(s).fromEntrySeq() + : 'object' == typeof s + ? new ObjectSeq(s) + : void 0; + if (!o) + throw new TypeError( + 'Expected Array or iterable object of [k, v] entries, or keyed object: ' + s + ); + return o; + } + function indexedSeqFromValue(s) { + var o = maybeIndexedSeqFromValue(s); + if (!o) throw new TypeError('Expected Array or iterable object of values: ' + s); + return o; + } + function seqFromValue(s) { + var o = maybeIndexedSeqFromValue(s) || ('object' == typeof s && new ObjectSeq(s)); + if (!o) + throw new TypeError( + 'Expected Array or iterable object of values, or keyed object: ' + s + ); + return o; + } + function maybeIndexedSeqFromValue(s) { + return isArrayLike(s) + ? new ArraySeq(s) + : isIterator(s) + ? new IteratorSeq(s) + : hasIterator(s) + ? new IterableSeq(s) + : void 0; + } + function seqIterate(s, o, i, a) { + var u = s._cache; + if (u) { + for (var _ = u.length - 1, w = 0; w <= _; w++) { + var x = u[i ? _ - w : w]; + if (!1 === o(x[1], a ? x[0] : w, s)) return w + 1; + } + return w; + } + return s.__iterateUncached(o, i); + } + function seqIterator(s, o, i, a) { + var u = s._cache; + if (u) { + var _ = u.length - 1, + w = 0; + return new Iterator(function () { + var s = u[i ? _ - w : w]; + return w++ > _ ? iteratorDone() : iteratorValue(o, a ? s[0] : w - 1, s[1]); + }); + } + return s.__iteratorUncached(o, i); + } + function fromJS(s, o) { + return o ? fromJSWith(o, s, '', { '': s }) : fromJSDefault(s); + } + function fromJSWith(s, o, i, a) { + return Array.isArray(o) + ? s.call( + a, + i, + IndexedSeq(o).map(function (i, a) { + return fromJSWith(s, i, a, o); + }) + ) + : isPlainObj(o) + ? s.call( + a, + i, + KeyedSeq(o).map(function (i, a) { + return fromJSWith(s, i, a, o); + }) + ) + : o; + } + function fromJSDefault(s) { + return Array.isArray(s) + ? IndexedSeq(s).map(fromJSDefault).toList() + : isPlainObj(s) + ? KeyedSeq(s).map(fromJSDefault).toMap() + : s; + } + function isPlainObj(s) { + return s && (s.constructor === Object || void 0 === s.constructor); + } + function is(s, o) { + if (s === o || (s != s && o != o)) return !0; + if (!s || !o) return !1; + if ('function' == typeof s.valueOf && 'function' == typeof o.valueOf) { + if ((s = s.valueOf()) === (o = o.valueOf()) || (s != s && o != o)) return !0; + if (!s || !o) return !1; + } + return !( + 'function' != typeof s.equals || + 'function' != typeof o.equals || + !s.equals(o) + ); + } + function deepEqual(s, o) { + if (s === o) return !0; + if ( + !isIterable(o) || + (void 0 !== s.size && void 0 !== o.size && s.size !== o.size) || + (void 0 !== s.__hash && void 0 !== o.__hash && s.__hash !== o.__hash) || + isKeyed(s) !== isKeyed(o) || + isIndexed(s) !== isIndexed(o) || + isOrdered(s) !== isOrdered(o) + ) + return !1; + if (0 === s.size && 0 === o.size) return !0; + var i = !isAssociative(s); + if (isOrdered(s)) { + var a = s.entries(); + return ( + o.every(function (s, o) { + var u = a.next().value; + return u && is(u[1], s) && (i || is(u[0], o)); + }) && a.next().done + ); + } + var u = !1; + if (void 0 === s.size) + if (void 0 === o.size) 'function' == typeof s.cacheResult && s.cacheResult(); + else { + u = !0; + var _ = s; + ((s = o), (o = _)); + } + var w = !0, + x = o.__iterate(function (o, a) { + if (i ? !s.has(o) : u ? !is(o, s.get(a, j)) : !is(s.get(a, j), o)) + return ((w = !1), !1); + }); + return w && s.size === x; + } + function Repeat(s, o) { + if (!(this instanceof Repeat)) return new Repeat(s, o); + if ( + ((this._value = s), + (this.size = void 0 === o ? 1 / 0 : Math.max(0, o)), + 0 === this.size) + ) { + if (ie) return ie; + ie = this; + } + } + function invariant(s, o) { + if (!s) throw new Error(o); + } + function Range(s, o, i) { + if (!(this instanceof Range)) return new Range(s, o, i); + if ( + (invariant(0 !== i, 'Cannot step a Range by 0'), + (s = s || 0), + void 0 === o && (o = 1 / 0), + (i = void 0 === i ? 1 : Math.abs(i)), + o < s && (i = -i), + (this._start = s), + (this._end = o), + (this._step = i), + (this.size = Math.max(0, Math.ceil((o - s) / i - 1) + 1)), + 0 === this.size) + ) { + if (ae) return ae; + ae = this; + } + } + function Collection() { + throw TypeError('Abstract'); + } + function KeyedCollection() {} + function IndexedCollection() {} + function SetCollection() {} + ((Seq.prototype[ce] = !0), + createClass(ArraySeq, IndexedSeq), + (ArraySeq.prototype.get = function (s, o) { + return this.has(s) ? this._array[wrapIndex(this, s)] : o; + }), + (ArraySeq.prototype.__iterate = function (s, o) { + for (var i = this._array, a = i.length - 1, u = 0; u <= a; u++) + if (!1 === s(i[o ? a - u : u], u, this)) return u + 1; + return u; + }), + (ArraySeq.prototype.__iterator = function (s, o) { + var i = this._array, + a = i.length - 1, + u = 0; + return new Iterator(function () { + return u > a ? iteratorDone() : iteratorValue(s, u, i[o ? a - u++ : u++]); + }); + }), + createClass(ObjectSeq, KeyedSeq), + (ObjectSeq.prototype.get = function (s, o) { + return void 0 === o || this.has(s) ? this._object[s] : o; + }), + (ObjectSeq.prototype.has = function (s) { + return this._object.hasOwnProperty(s); + }), + (ObjectSeq.prototype.__iterate = function (s, o) { + for (var i = this._object, a = this._keys, u = a.length - 1, _ = 0; _ <= u; _++) { + var w = a[o ? u - _ : _]; + if (!1 === s(i[w], w, this)) return _ + 1; + } + return _; + }), + (ObjectSeq.prototype.__iterator = function (s, o) { + var i = this._object, + a = this._keys, + u = a.length - 1, + _ = 0; + return new Iterator(function () { + var w = a[o ? u - _ : _]; + return _++ > u ? iteratorDone() : iteratorValue(s, w, i[w]); + }); + }), + (ObjectSeq.prototype[u] = !0), + createClass(IterableSeq, IndexedSeq), + (IterableSeq.prototype.__iterateUncached = function (s, o) { + if (o) return this.cacheResult().__iterate(s, o); + var i = getIterator(this._iterable), + a = 0; + if (isIterator(i)) + for (var u; !(u = i.next()).done && !1 !== s(u.value, a++, this); ); + return a; + }), + (IterableSeq.prototype.__iteratorUncached = function (s, o) { + if (o) return this.cacheResult().__iterator(s, o); + var i = getIterator(this._iterable); + if (!isIterator(i)) return new Iterator(iteratorDone); + var a = 0; + return new Iterator(function () { + var o = i.next(); + return o.done ? o : iteratorValue(s, a++, o.value); + }); + }), + createClass(IteratorSeq, IndexedSeq), + (IteratorSeq.prototype.__iterateUncached = function (s, o) { + if (o) return this.cacheResult().__iterate(s, o); + for (var i, a = this._iterator, u = this._iteratorCache, _ = 0; _ < u.length; ) + if (!1 === s(u[_], _++, this)) return _; + for (; !(i = a.next()).done; ) { + var w = i.value; + if (((u[_] = w), !1 === s(w, _++, this))) break; + } + return _; + }), + (IteratorSeq.prototype.__iteratorUncached = function (s, o) { + if (o) return this.cacheResult().__iterator(s, o); + var i = this._iterator, + a = this._iteratorCache, + u = 0; + return new Iterator(function () { + if (u >= a.length) { + var o = i.next(); + if (o.done) return o; + a[u] = o.value; + } + return iteratorValue(s, u, a[u++]); + }); + }), + createClass(Repeat, IndexedSeq), + (Repeat.prototype.toString = function () { + return 0 === this.size + ? 'Repeat []' + : 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; + }), + (Repeat.prototype.get = function (s, o) { + return this.has(s) ? this._value : o; + }), + (Repeat.prototype.includes = function (s) { + return is(this._value, s); + }), + (Repeat.prototype.slice = function (s, o) { + var i = this.size; + return wholeSlice(s, o, i) + ? this + : new Repeat(this._value, resolveEnd(o, i) - resolveBegin(s, i)); + }), + (Repeat.prototype.reverse = function () { + return this; + }), + (Repeat.prototype.indexOf = function (s) { + return is(this._value, s) ? 0 : -1; + }), + (Repeat.prototype.lastIndexOf = function (s) { + return is(this._value, s) ? this.size : -1; + }), + (Repeat.prototype.__iterate = function (s, o) { + for (var i = 0; i < this.size; i++) + if (!1 === s(this._value, i, this)) return i + 1; + return i; + }), + (Repeat.prototype.__iterator = function (s, o) { + var i = this, + a = 0; + return new Iterator(function () { + return a < i.size ? iteratorValue(s, a++, i._value) : iteratorDone(); + }); + }), + (Repeat.prototype.equals = function (s) { + return s instanceof Repeat ? is(this._value, s._value) : deepEqual(s); + }), + createClass(Range, IndexedSeq), + (Range.prototype.toString = function () { + return 0 === this.size + ? 'Range []' + : 'Range [ ' + + this._start + + '...' + + this._end + + (1 !== this._step ? ' by ' + this._step : '') + + ' ]'; + }), + (Range.prototype.get = function (s, o) { + return this.has(s) ? this._start + wrapIndex(this, s) * this._step : o; + }), + (Range.prototype.includes = function (s) { + var o = (s - this._start) / this._step; + return o >= 0 && o < this.size && o === Math.floor(o); + }), + (Range.prototype.slice = function (s, o) { + return wholeSlice(s, o, this.size) + ? this + : ((s = resolveBegin(s, this.size)), + (o = resolveEnd(o, this.size)) <= s + ? new Range(0, 0) + : new Range(this.get(s, this._end), this.get(o, this._end), this._step)); + }), + (Range.prototype.indexOf = function (s) { + var o = s - this._start; + if (o % this._step == 0) { + var i = o / this._step; + if (i >= 0 && i < this.size) return i; + } + return -1; + }), + (Range.prototype.lastIndexOf = function (s) { + return this.indexOf(s); + }), + (Range.prototype.__iterate = function (s, o) { + for ( + var i = this.size - 1, + a = this._step, + u = o ? this._start + i * a : this._start, + _ = 0; + _ <= i; + _++ + ) { + if (!1 === s(u, _, this)) return _ + 1; + u += o ? -a : a; + } + return _; + }), + (Range.prototype.__iterator = function (s, o) { + var i = this.size - 1, + a = this._step, + u = o ? this._start + i * a : this._start, + _ = 0; + return new Iterator(function () { + var w = u; + return ((u += o ? -a : a), _ > i ? iteratorDone() : iteratorValue(s, _++, w)); + }); + }), + (Range.prototype.equals = function (s) { + return s instanceof Range + ? this._start === s._start && this._end === s._end && this._step === s._step + : deepEqual(this, s); + }), + createClass(Collection, Iterable), + createClass(KeyedCollection, Collection), + createClass(IndexedCollection, Collection), + createClass(SetCollection, Collection), + (Collection.Keyed = KeyedCollection), + (Collection.Indexed = IndexedCollection), + (Collection.Set = SetCollection)); + var le = + 'function' == typeof Math.imul && -2 === Math.imul(4294967295, 2) + ? Math.imul + : function imul(s, o) { + var i = 65535 & (s |= 0), + a = 65535 & (o |= 0); + return (i * a + ((((s >>> 16) * a + i * (o >>> 16)) << 16) >>> 0)) | 0; + }; + function smi(s) { + return ((s >>> 1) & 1073741824) | (3221225471 & s); + } + function hash(s) { + if (!1 === s || null == s) return 0; + if ('function' == typeof s.valueOf && (!1 === (s = s.valueOf()) || null == s)) + return 0; + if (!0 === s) return 1; + var o = typeof s; + if ('number' === o) { + if (s != s || s === 1 / 0) return 0; + var i = 0 | s; + for (i !== s && (i ^= 4294967295 * s); s > 4294967295; ) i ^= s /= 4294967295; + return smi(i); + } + if ('string' === o) return s.length > _e ? cachedHashString(s) : hashString(s); + if ('function' == typeof s.hashCode) return s.hashCode(); + if ('object' === o) return hashJSObj(s); + if ('function' == typeof s.toString) return hashString(s.toString()); + throw new Error('Value type ' + o + ' cannot be hashed.'); + } + function cachedHashString(s) { + var o = Pe[s]; + return ( + void 0 === o && + ((o = hashString(s)), xe === we && ((xe = 0), (Pe = {})), xe++, (Pe[s] = o)), + o + ); + } + function hashString(s) { + for (var o = 0, i = 0; i < s.length; i++) o = (31 * o + s.charCodeAt(i)) | 0; + return smi(o); + } + function hashJSObj(s) { + var o; + if (ye && void 0 !== (o = fe.get(s))) return o; + if (void 0 !== (o = s[Se])) return o; + if (!de) { + if (void 0 !== (o = s.propertyIsEnumerable && s.propertyIsEnumerable[Se])) return o; + if (void 0 !== (o = getIENodeHash(s))) return o; + } + if (((o = ++be), 1073741824 & be && (be = 0), ye)) fe.set(s, o); + else { + if (void 0 !== pe && !1 === pe(s)) + throw new Error('Non-extensible objects are not allowed as keys.'); + if (de) + Object.defineProperty(s, Se, { + enumerable: !1, + configurable: !1, + writable: !1, + value: o + }); + else if ( + void 0 !== s.propertyIsEnumerable && + s.propertyIsEnumerable === s.constructor.prototype.propertyIsEnumerable + ) + ((s.propertyIsEnumerable = function () { + return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); + }), + (s.propertyIsEnumerable[Se] = o)); + else { + if (void 0 === s.nodeType) + throw new Error('Unable to set a non-enumerable property on object.'); + s[Se] = o; + } + } + return o; + } + var pe = Object.isExtensible, + de = (function () { + try { + return (Object.defineProperty({}, '@', {}), !0); + } catch (s) { + return !1; + } + })(); + function getIENodeHash(s) { + if (s && s.nodeType > 0) + switch (s.nodeType) { + case 1: + return s.uniqueID; + case 9: + return s.documentElement && s.documentElement.uniqueID; + } + } + var fe, + ye = 'function' == typeof WeakMap; + ye && (fe = new WeakMap()); + var be = 0, + Se = '__immutablehash__'; + 'function' == typeof Symbol && (Se = Symbol(Se)); + var _e = 16, + we = 255, + xe = 0, + Pe = {}; + function assertNotInfinite(s) { + invariant(s !== 1 / 0, 'Cannot perform this action with an infinite size.'); + } + function Map(s) { + return null == s + ? emptyMap() + : isMap(s) && !isOrdered(s) + ? s + : emptyMap().withMutations(function (o) { + var i = KeyedIterable(s); + (assertNotInfinite(i.size), + i.forEach(function (s, i) { + return o.set(i, s); + })); + }); + } + function isMap(s) { + return !(!s || !s[Re]); + } + (createClass(Map, KeyedCollection), + (Map.of = function () { + var o = s.call(arguments, 0); + return emptyMap().withMutations(function (s) { + for (var i = 0; i < o.length; i += 2) { + if (i + 1 >= o.length) throw new Error('Missing value for key: ' + o[i]); + s.set(o[i], o[i + 1]); + } + }); + }), + (Map.prototype.toString = function () { + return this.__toString('Map {', '}'); + }), + (Map.prototype.get = function (s, o) { + return this._root ? this._root.get(0, void 0, s, o) : o; + }), + (Map.prototype.set = function (s, o) { + return updateMap(this, s, o); + }), + (Map.prototype.setIn = function (s, o) { + return this.updateIn(s, j, function () { + return o; + }); + }), + (Map.prototype.remove = function (s) { + return updateMap(this, s, j); + }), + (Map.prototype.deleteIn = function (s) { + return this.updateIn(s, function () { + return j; + }); + }), + (Map.prototype.update = function (s, o, i) { + return 1 === arguments.length ? s(this) : this.updateIn([s], o, i); + }), + (Map.prototype.updateIn = function (s, o, i) { + i || ((i = o), (o = void 0)); + var a = updateInDeepMap(this, forceIterator(s), o, i); + return a === j ? void 0 : a; + }), + (Map.prototype.clear = function () { + return 0 === this.size + ? this + : this.__ownerID + ? ((this.size = 0), + (this._root = null), + (this.__hash = void 0), + (this.__altered = !0), + this) + : emptyMap(); + }), + (Map.prototype.merge = function () { + return mergeIntoMapWith(this, void 0, arguments); + }), + (Map.prototype.mergeWith = function (o) { + return mergeIntoMapWith(this, o, s.call(arguments, 1)); + }), + (Map.prototype.mergeIn = function (o) { + var i = s.call(arguments, 1); + return this.updateIn(o, emptyMap(), function (s) { + return 'function' == typeof s.merge ? s.merge.apply(s, i) : i[i.length - 1]; + }); + }), + (Map.prototype.mergeDeep = function () { + return mergeIntoMapWith(this, deepMerger, arguments); + }), + (Map.prototype.mergeDeepWith = function (o) { + var i = s.call(arguments, 1); + return mergeIntoMapWith(this, deepMergerWith(o), i); + }), + (Map.prototype.mergeDeepIn = function (o) { + var i = s.call(arguments, 1); + return this.updateIn(o, emptyMap(), function (s) { + return 'function' == typeof s.mergeDeep + ? s.mergeDeep.apply(s, i) + : i[i.length - 1]; + }); + }), + (Map.prototype.sort = function (s) { + return OrderedMap(sortFactory(this, s)); + }), + (Map.prototype.sortBy = function (s, o) { + return OrderedMap(sortFactory(this, o, s)); + }), + (Map.prototype.withMutations = function (s) { + var o = this.asMutable(); + return (s(o), o.wasAltered() ? o.__ensureOwner(this.__ownerID) : this); + }), + (Map.prototype.asMutable = function () { + return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); + }), + (Map.prototype.asImmutable = function () { + return this.__ensureOwner(); + }), + (Map.prototype.wasAltered = function () { + return this.__altered; + }), + (Map.prototype.__iterator = function (s, o) { + return new MapIterator(this, s, o); + }), + (Map.prototype.__iterate = function (s, o) { + var i = this, + a = 0; + return ( + this._root && + this._root.iterate(function (o) { + return (a++, s(o[1], o[0], i)); + }, o), + a + ); + }), + (Map.prototype.__ensureOwner = function (s) { + return s === this.__ownerID + ? this + : s + ? makeMap(this.size, this._root, s, this.__hash) + : ((this.__ownerID = s), (this.__altered = !1), this); + }), + (Map.isMap = isMap)); + var Te, + Re = '@@__IMMUTABLE_MAP__@@', + $e = Map.prototype; + function ArrayMapNode(s, o) { + ((this.ownerID = s), (this.entries = o)); + } + function BitmapIndexedNode(s, o, i) { + ((this.ownerID = s), (this.bitmap = o), (this.nodes = i)); + } + function HashArrayMapNode(s, o, i) { + ((this.ownerID = s), (this.count = o), (this.nodes = i)); + } + function HashCollisionNode(s, o, i) { + ((this.ownerID = s), (this.keyHash = o), (this.entries = i)); + } + function ValueNode(s, o, i) { + ((this.ownerID = s), (this.keyHash = o), (this.entry = i)); + } + function MapIterator(s, o, i) { + ((this._type = o), + (this._reverse = i), + (this._stack = s._root && mapIteratorFrame(s._root))); + } + function mapIteratorValue(s, o) { + return iteratorValue(s, o[0], o[1]); + } + function mapIteratorFrame(s, o) { + return { node: s, index: 0, __prev: o }; + } + function makeMap(s, o, i, a) { + var u = Object.create($e); + return ( + (u.size = s), + (u._root = o), + (u.__ownerID = i), + (u.__hash = a), + (u.__altered = !1), + u + ); + } + function emptyMap() { + return Te || (Te = makeMap(0)); + } + function updateMap(s, o, i) { + var a, u; + if (s._root) { + var _ = MakeRef(L), + w = MakeRef(B); + if (((a = updateNode(s._root, s.__ownerID, 0, void 0, o, i, _, w)), !w.value)) + return s; + u = s.size + (_.value ? (i === j ? -1 : 1) : 0); + } else { + if (i === j) return s; + ((u = 1), (a = new ArrayMapNode(s.__ownerID, [[o, i]]))); + } + return s.__ownerID + ? ((s.size = u), (s._root = a), (s.__hash = void 0), (s.__altered = !0), s) + : a + ? makeMap(u, a) + : emptyMap(); + } + function updateNode(s, o, i, a, u, _, w, x) { + return s + ? s.update(o, i, a, u, _, w, x) + : _ === j + ? s + : (SetRef(x), SetRef(w), new ValueNode(o, a, [u, _])); + } + function isLeafNode(s) { + return s.constructor === ValueNode || s.constructor === HashCollisionNode; + } + function mergeIntoNode(s, o, i, a, u) { + if (s.keyHash === a) return new HashCollisionNode(o, a, [s.entry, u]); + var _, + x = (0 === i ? s.keyHash : s.keyHash >>> i) & C, + j = (0 === i ? a : a >>> i) & C; + return new BitmapIndexedNode( + o, + (1 << x) | (1 << j), + x === j + ? [mergeIntoNode(s, o, i + w, a, u)] + : ((_ = new ValueNode(o, a, u)), x < j ? [s, _] : [_, s]) + ); + } + function createNodes(s, o, i, a) { + s || (s = new OwnerID()); + for (var u = new ValueNode(s, hash(i), [i, a]), _ = 0; _ < o.length; _++) { + var w = o[_]; + u = u.update(s, 0, void 0, w[0], w[1]); + } + return u; + } + function packNodes(s, o, i, a) { + for ( + var u = 0, _ = 0, w = new Array(i), x = 0, C = 1, j = o.length; + x < j; + x++, C <<= 1 + ) { + var L = o[x]; + void 0 !== L && x !== a && ((u |= C), (w[_++] = L)); + } + return new BitmapIndexedNode(s, u, w); + } + function expandNodes(s, o, i, a, u) { + for (var _ = 0, w = new Array(x), C = 0; 0 !== i; C++, i >>>= 1) + w[C] = 1 & i ? o[_++] : void 0; + return ((w[a] = u), new HashArrayMapNode(s, _ + 1, w)); + } + function mergeIntoMapWith(s, o, i) { + for (var a = [], u = 0; u < i.length; u++) { + var _ = i[u], + w = KeyedIterable(_); + (isIterable(_) || + (w = w.map(function (s) { + return fromJS(s); + })), + a.push(w)); + } + return mergeIntoCollectionWith(s, o, a); + } + function deepMerger(s, o, i) { + return s && s.mergeDeep && isIterable(o) ? s.mergeDeep(o) : is(s, o) ? s : o; + } + function deepMergerWith(s) { + return function (o, i, a) { + if (o && o.mergeDeepWith && isIterable(i)) return o.mergeDeepWith(s, i); + var u = s(o, i, a); + return is(o, u) ? o : u; + }; + } + function mergeIntoCollectionWith(s, o, i) { + return 0 === + (i = i.filter(function (s) { + return 0 !== s.size; + })).length + ? s + : 0 !== s.size || s.__ownerID || 1 !== i.length + ? s.withMutations(function (s) { + for ( + var a = o + ? function (i, a) { + s.update(a, j, function (s) { + return s === j ? i : o(s, i, a); + }); + } + : function (o, i) { + s.set(i, o); + }, + u = 0; + u < i.length; + u++ + ) + i[u].forEach(a); + }) + : s.constructor(i[0]); + } + function updateInDeepMap(s, o, i, a) { + var u = s === j, + _ = o.next(); + if (_.done) { + var w = u ? i : s, + x = a(w); + return x === w ? s : x; + } + invariant(u || (s && s.set), 'invalid keyPath'); + var C = _.value, + L = u ? j : s.get(C, j), + B = updateInDeepMap(L, o, i, a); + return B === L ? s : B === j ? s.remove(C) : (u ? emptyMap() : s).set(C, B); + } + function popCount(s) { + return ( + (s = + ((s = (858993459 & (s -= (s >> 1) & 1431655765)) + ((s >> 2) & 858993459)) + + (s >> 4)) & + 252645135), + (s += s >> 8), + 127 & (s += s >> 16) + ); + } + function setIn(s, o, i, a) { + var u = a ? s : arrCopy(s); + return ((u[o] = i), u); + } + function spliceIn(s, o, i, a) { + var u = s.length + 1; + if (a && o + 1 === u) return ((s[o] = i), s); + for (var _ = new Array(u), w = 0, x = 0; x < u; x++) + x === o ? ((_[x] = i), (w = -1)) : (_[x] = s[x + w]); + return _; + } + function spliceOut(s, o, i) { + var a = s.length - 1; + if (i && o === a) return (s.pop(), s); + for (var u = new Array(a), _ = 0, w = 0; w < a; w++) + (w === o && (_ = 1), (u[w] = s[w + _])); + return u; + } + (($e[Re] = !0), + ($e[_] = $e.remove), + ($e.removeIn = $e.deleteIn), + (ArrayMapNode.prototype.get = function (s, o, i, a) { + for (var u = this.entries, _ = 0, w = u.length; _ < w; _++) + if (is(i, u[_][0])) return u[_][1]; + return a; + }), + (ArrayMapNode.prototype.update = function (s, o, i, a, u, _, w) { + for ( + var x = u === j, C = this.entries, L = 0, B = C.length; + L < B && !is(a, C[L][0]); + L++ + ); + var $ = L < B; + if ($ ? C[L][1] === u : x) return this; + if ((SetRef(w), (x || !$) && SetRef(_), !x || 1 !== C.length)) { + if (!$ && !x && C.length >= qe) return createNodes(s, C, a, u); + var U = s && s === this.ownerID, + V = U ? C : arrCopy(C); + return ( + $ + ? x + ? L === B - 1 + ? V.pop() + : (V[L] = V.pop()) + : (V[L] = [a, u]) + : V.push([a, u]), + U ? ((this.entries = V), this) : new ArrayMapNode(s, V) + ); + } + }), + (BitmapIndexedNode.prototype.get = function (s, o, i, a) { + void 0 === o && (o = hash(i)); + var u = 1 << ((0 === s ? o : o >>> s) & C), + _ = this.bitmap; + return _ & u ? this.nodes[popCount(_ & (u - 1))].get(s + w, o, i, a) : a; + }), + (BitmapIndexedNode.prototype.update = function (s, o, i, a, u, _, x) { + void 0 === i && (i = hash(a)); + var L = (0 === o ? i : i >>> o) & C, + B = 1 << L, + $ = this.bitmap, + U = !!($ & B); + if (!U && u === j) return this; + var V = popCount($ & (B - 1)), + z = this.nodes, + Y = U ? z[V] : void 0, + Z = updateNode(Y, s, o + w, i, a, u, _, x); + if (Z === Y) return this; + if (!U && Z && z.length >= ze) return expandNodes(s, z, $, L, Z); + if (U && !Z && 2 === z.length && isLeafNode(z[1 ^ V])) return z[1 ^ V]; + if (U && Z && 1 === z.length && isLeafNode(Z)) return Z; + var ee = s && s === this.ownerID, + ie = U ? (Z ? $ : $ ^ B) : $ | B, + ae = U ? (Z ? setIn(z, V, Z, ee) : spliceOut(z, V, ee)) : spliceIn(z, V, Z, ee); + return ee + ? ((this.bitmap = ie), (this.nodes = ae), this) + : new BitmapIndexedNode(s, ie, ae); + }), + (HashArrayMapNode.prototype.get = function (s, o, i, a) { + void 0 === o && (o = hash(i)); + var u = (0 === s ? o : o >>> s) & C, + _ = this.nodes[u]; + return _ ? _.get(s + w, o, i, a) : a; + }), + (HashArrayMapNode.prototype.update = function (s, o, i, a, u, _, x) { + void 0 === i && (i = hash(a)); + var L = (0 === o ? i : i >>> o) & C, + B = u === j, + $ = this.nodes, + U = $[L]; + if (B && !U) return this; + var V = updateNode(U, s, o + w, i, a, u, _, x); + if (V === U) return this; + var z = this.count; + if (U) { + if (!V && --z < We) return packNodes(s, $, z, L); + } else z++; + var Y = s && s === this.ownerID, + Z = setIn($, L, V, Y); + return Y + ? ((this.count = z), (this.nodes = Z), this) + : new HashArrayMapNode(s, z, Z); + }), + (HashCollisionNode.prototype.get = function (s, o, i, a) { + for (var u = this.entries, _ = 0, w = u.length; _ < w; _++) + if (is(i, u[_][0])) return u[_][1]; + return a; + }), + (HashCollisionNode.prototype.update = function (s, o, i, a, u, _, w) { + void 0 === i && (i = hash(a)); + var x = u === j; + if (i !== this.keyHash) + return x ? this : (SetRef(w), SetRef(_), mergeIntoNode(this, s, o, i, [a, u])); + for (var C = this.entries, L = 0, B = C.length; L < B && !is(a, C[L][0]); L++); + var $ = L < B; + if ($ ? C[L][1] === u : x) return this; + if ((SetRef(w), (x || !$) && SetRef(_), x && 2 === B)) + return new ValueNode(s, this.keyHash, C[1 ^ L]); + var U = s && s === this.ownerID, + V = U ? C : arrCopy(C); + return ( + $ + ? x + ? L === B - 1 + ? V.pop() + : (V[L] = V.pop()) + : (V[L] = [a, u]) + : V.push([a, u]), + U ? ((this.entries = V), this) : new HashCollisionNode(s, this.keyHash, V) + ); + }), + (ValueNode.prototype.get = function (s, o, i, a) { + return is(i, this.entry[0]) ? this.entry[1] : a; + }), + (ValueNode.prototype.update = function (s, o, i, a, u, _, w) { + var x = u === j, + C = is(a, this.entry[0]); + return (C ? u === this.entry[1] : x) + ? this + : (SetRef(w), + x + ? void SetRef(_) + : C + ? s && s === this.ownerID + ? ((this.entry[1] = u), this) + : new ValueNode(s, this.keyHash, [a, u]) + : (SetRef(_), mergeIntoNode(this, s, o, hash(a), [a, u]))); + }), + (ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = + function (s, o) { + for (var i = this.entries, a = 0, u = i.length - 1; a <= u; a++) + if (!1 === s(i[o ? u - a : a])) return !1; + }), + (BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = + function (s, o) { + for (var i = this.nodes, a = 0, u = i.length - 1; a <= u; a++) { + var _ = i[o ? u - a : a]; + if (_ && !1 === _.iterate(s, o)) return !1; + } + }), + (ValueNode.prototype.iterate = function (s, o) { + return s(this.entry); + }), + createClass(MapIterator, Iterator), + (MapIterator.prototype.next = function () { + for (var s = this._type, o = this._stack; o; ) { + var i, + a = o.node, + u = o.index++; + if (a.entry) { + if (0 === u) return mapIteratorValue(s, a.entry); + } else if (a.entries) { + if (u <= (i = a.entries.length - 1)) + return mapIteratorValue(s, a.entries[this._reverse ? i - u : u]); + } else if (u <= (i = a.nodes.length - 1)) { + var _ = a.nodes[this._reverse ? i - u : u]; + if (_) { + if (_.entry) return mapIteratorValue(s, _.entry); + o = this._stack = mapIteratorFrame(_, o); + } + continue; + } + o = this._stack = this._stack.__prev; + } + return iteratorDone(); + })); + var qe = x / 4, + ze = x / 2, + We = x / 4; + function List(s) { + var o = emptyList(); + if (null == s) return o; + if (isList(s)) return s; + var i = IndexedIterable(s), + a = i.size; + return 0 === a + ? o + : (assertNotInfinite(a), + a > 0 && a < x + ? makeList(0, a, w, null, new VNode(i.toArray())) + : o.withMutations(function (s) { + (s.setSize(a), + i.forEach(function (o, i) { + return s.set(i, o); + })); + })); + } + function isList(s) { + return !(!s || !s[He]); + } + (createClass(List, IndexedCollection), + (List.of = function () { + return this(arguments); + }), + (List.prototype.toString = function () { + return this.__toString('List [', ']'); + }), + (List.prototype.get = function (s, o) { + if ((s = wrapIndex(this, s)) >= 0 && s < this.size) { + var i = listNodeFor(this, (s += this._origin)); + return i && i.array[s & C]; + } + return o; + }), + (List.prototype.set = function (s, o) { + return updateList(this, s, o); + }), + (List.prototype.remove = function (s) { + return this.has(s) + ? 0 === s + ? this.shift() + : s === this.size - 1 + ? this.pop() + : this.splice(s, 1) + : this; + }), + (List.prototype.insert = function (s, o) { + return this.splice(s, 0, o); + }), + (List.prototype.clear = function () { + return 0 === this.size + ? this + : this.__ownerID + ? ((this.size = this._origin = this._capacity = 0), + (this._level = w), + (this._root = this._tail = null), + (this.__hash = void 0), + (this.__altered = !0), + this) + : emptyList(); + }), + (List.prototype.push = function () { + var s = arguments, + o = this.size; + return this.withMutations(function (i) { + setListBounds(i, 0, o + s.length); + for (var a = 0; a < s.length; a++) i.set(o + a, s[a]); + }); + }), + (List.prototype.pop = function () { + return setListBounds(this, 0, -1); + }), + (List.prototype.unshift = function () { + var s = arguments; + return this.withMutations(function (o) { + setListBounds(o, -s.length); + for (var i = 0; i < s.length; i++) o.set(i, s[i]); + }); + }), + (List.prototype.shift = function () { + return setListBounds(this, 1); + }), + (List.prototype.merge = function () { + return mergeIntoListWith(this, void 0, arguments); + }), + (List.prototype.mergeWith = function (o) { + return mergeIntoListWith(this, o, s.call(arguments, 1)); + }), + (List.prototype.mergeDeep = function () { + return mergeIntoListWith(this, deepMerger, arguments); + }), + (List.prototype.mergeDeepWith = function (o) { + var i = s.call(arguments, 1); + return mergeIntoListWith(this, deepMergerWith(o), i); + }), + (List.prototype.setSize = function (s) { + return setListBounds(this, 0, s); + }), + (List.prototype.slice = function (s, o) { + var i = this.size; + return wholeSlice(s, o, i) + ? this + : setListBounds(this, resolveBegin(s, i), resolveEnd(o, i)); + }), + (List.prototype.__iterator = function (s, o) { + var i = 0, + a = iterateList(this, o); + return new Iterator(function () { + var o = a(); + return o === et ? iteratorDone() : iteratorValue(s, i++, o); + }); + }), + (List.prototype.__iterate = function (s, o) { + for ( + var i, a = 0, u = iterateList(this, o); + (i = u()) !== et && !1 !== s(i, a++, this); + ); + return a; + }), + (List.prototype.__ensureOwner = function (s) { + return s === this.__ownerID + ? this + : s + ? makeList( + this._origin, + this._capacity, + this._level, + this._root, + this._tail, + s, + this.__hash + ) + : ((this.__ownerID = s), this); + }), + (List.isList = isList)); + var He = '@@__IMMUTABLE_LIST__@@', + Ye = List.prototype; + function VNode(s, o) { + ((this.array = s), (this.ownerID = o)); + } + ((Ye[He] = !0), + (Ye[_] = Ye.remove), + (Ye.setIn = $e.setIn), + (Ye.deleteIn = Ye.removeIn = $e.removeIn), + (Ye.update = $e.update), + (Ye.updateIn = $e.updateIn), + (Ye.mergeIn = $e.mergeIn), + (Ye.mergeDeepIn = $e.mergeDeepIn), + (Ye.withMutations = $e.withMutations), + (Ye.asMutable = $e.asMutable), + (Ye.asImmutable = $e.asImmutable), + (Ye.wasAltered = $e.wasAltered), + (VNode.prototype.removeBefore = function (s, o, i) { + if (i === o ? 1 << o : 0 === this.array.length) return this; + var a = (i >>> o) & C; + if (a >= this.array.length) return new VNode([], s); + var u, + _ = 0 === a; + if (o > 0) { + var x = this.array[a]; + if ((u = x && x.removeBefore(s, o - w, i)) === x && _) return this; + } + if (_ && !u) return this; + var j = editableVNode(this, s); + if (!_) for (var L = 0; L < a; L++) j.array[L] = void 0; + return (u && (j.array[a] = u), j); + }), + (VNode.prototype.removeAfter = function (s, o, i) { + if (i === (o ? 1 << o : 0) || 0 === this.array.length) return this; + var a, + u = ((i - 1) >>> o) & C; + if (u >= this.array.length) return this; + if (o > 0) { + var _ = this.array[u]; + if ((a = _ && _.removeAfter(s, o - w, i)) === _ && u === this.array.length - 1) + return this; + } + var x = editableVNode(this, s); + return (x.array.splice(u + 1), a && (x.array[u] = a), x); + })); + var Xe, + Qe, + et = {}; + function iterateList(s, o) { + var i = s._origin, + a = s._capacity, + u = getTailOffset(a), + _ = s._tail; + return iterateNodeOrLeaf(s._root, s._level, 0); + function iterateNodeOrLeaf(s, o, i) { + return 0 === o ? iterateLeaf(s, i) : iterateNode(s, o, i); + } + function iterateLeaf(s, w) { + var C = w === u ? _ && _.array : s && s.array, + j = w > i ? 0 : i - w, + L = a - w; + return ( + L > x && (L = x), + function () { + if (j === L) return et; + var s = o ? --L : j++; + return C && C[s]; + } + ); + } + function iterateNode(s, u, _) { + var C, + j = s && s.array, + L = _ > i ? 0 : (i - _) >> u, + B = 1 + ((a - _) >> u); + return ( + B > x && (B = x), + function () { + for (;;) { + if (C) { + var s = C(); + if (s !== et) return s; + C = null; + } + if (L === B) return et; + var i = o ? --B : L++; + C = iterateNodeOrLeaf(j && j[i], u - w, _ + (i << u)); + } + } + ); + } + } + function makeList(s, o, i, a, u, _, w) { + var x = Object.create(Ye); + return ( + (x.size = o - s), + (x._origin = s), + (x._capacity = o), + (x._level = i), + (x._root = a), + (x._tail = u), + (x.__ownerID = _), + (x.__hash = w), + (x.__altered = !1), + x + ); + } + function emptyList() { + return Xe || (Xe = makeList(0, 0, w)); + } + function updateList(s, o, i) { + if ((o = wrapIndex(s, o)) != o) return s; + if (o >= s.size || o < 0) + return s.withMutations(function (s) { + o < 0 ? setListBounds(s, o).set(0, i) : setListBounds(s, 0, o + 1).set(o, i); + }); + o += s._origin; + var a = s._tail, + u = s._root, + _ = MakeRef(B); + return ( + o >= getTailOffset(s._capacity) + ? (a = updateVNode(a, s.__ownerID, 0, o, i, _)) + : (u = updateVNode(u, s.__ownerID, s._level, o, i, _)), + _.value + ? s.__ownerID + ? ((s._root = u), (s._tail = a), (s.__hash = void 0), (s.__altered = !0), s) + : makeList(s._origin, s._capacity, s._level, u, a) + : s + ); + } + function updateVNode(s, o, i, a, u, _) { + var x, + j = (a >>> i) & C, + L = s && j < s.array.length; + if (!L && void 0 === u) return s; + if (i > 0) { + var B = s && s.array[j], + $ = updateVNode(B, o, i - w, a, u, _); + return $ === B ? s : (((x = editableVNode(s, o)).array[j] = $), x); + } + return L && s.array[j] === u + ? s + : (SetRef(_), + (x = editableVNode(s, o)), + void 0 === u && j === x.array.length - 1 ? x.array.pop() : (x.array[j] = u), + x); + } + function editableVNode(s, o) { + return o && s && o === s.ownerID ? s : new VNode(s ? s.array.slice() : [], o); + } + function listNodeFor(s, o) { + if (o >= getTailOffset(s._capacity)) return s._tail; + if (o < 1 << (s._level + w)) { + for (var i = s._root, a = s._level; i && a > 0; ) + ((i = i.array[(o >>> a) & C]), (a -= w)); + return i; + } + } + function setListBounds(s, o, i) { + (void 0 !== o && (o |= 0), void 0 !== i && (i |= 0)); + var a = s.__ownerID || new OwnerID(), + u = s._origin, + _ = s._capacity, + x = u + o, + j = void 0 === i ? _ : i < 0 ? _ + i : u + i; + if (x === u && j === _) return s; + if (x >= j) return s.clear(); + for (var L = s._level, B = s._root, $ = 0; x + $ < 0; ) + ((B = new VNode(B && B.array.length ? [void 0, B] : [], a)), ($ += 1 << (L += w))); + $ && ((x += $), (u += $), (j += $), (_ += $)); + for (var U = getTailOffset(_), V = getTailOffset(j); V >= 1 << (L + w); ) + ((B = new VNode(B && B.array.length ? [B] : [], a)), (L += w)); + var z = s._tail, + Y = V < U ? listNodeFor(s, j - 1) : V > U ? new VNode([], a) : z; + if (z && V > U && x < _ && z.array.length) { + for (var Z = (B = editableVNode(B, a)), ee = L; ee > w; ee -= w) { + var ie = (U >>> ee) & C; + Z = Z.array[ie] = editableVNode(Z.array[ie], a); + } + Z.array[(U >>> w) & C] = z; + } + if ((j < _ && (Y = Y && Y.removeAfter(a, 0, j)), x >= V)) + ((x -= V), (j -= V), (L = w), (B = null), (Y = Y && Y.removeBefore(a, 0, x))); + else if (x > u || V < U) { + for ($ = 0; B; ) { + var ae = (x >>> L) & C; + if ((ae !== V >>> L) & C) break; + (ae && ($ += (1 << L) * ae), (L -= w), (B = B.array[ae])); + } + (B && x > u && (B = B.removeBefore(a, L, x - $)), + B && V < U && (B = B.removeAfter(a, L, V - $)), + $ && ((x -= $), (j -= $))); + } + return s.__ownerID + ? ((s.size = j - x), + (s._origin = x), + (s._capacity = j), + (s._level = L), + (s._root = B), + (s._tail = Y), + (s.__hash = void 0), + (s.__altered = !0), + s) + : makeList(x, j, L, B, Y); + } + function mergeIntoListWith(s, o, i) { + for (var a = [], u = 0, _ = 0; _ < i.length; _++) { + var w = i[_], + x = IndexedIterable(w); + (x.size > u && (u = x.size), + isIterable(w) || + (x = x.map(function (s) { + return fromJS(s); + })), + a.push(x)); + } + return (u > s.size && (s = s.setSize(u)), mergeIntoCollectionWith(s, o, a)); + } + function getTailOffset(s) { + return s < x ? 0 : ((s - 1) >>> w) << w; + } + function OrderedMap(s) { + return null == s + ? emptyOrderedMap() + : isOrderedMap(s) + ? s + : emptyOrderedMap().withMutations(function (o) { + var i = KeyedIterable(s); + (assertNotInfinite(i.size), + i.forEach(function (s, i) { + return o.set(i, s); + })); + }); + } + function isOrderedMap(s) { + return isMap(s) && isOrdered(s); + } + function makeOrderedMap(s, o, i, a) { + var u = Object.create(OrderedMap.prototype); + return ( + (u.size = s ? s.size : 0), + (u._map = s), + (u._list = o), + (u.__ownerID = i), + (u.__hash = a), + u + ); + } + function emptyOrderedMap() { + return Qe || (Qe = makeOrderedMap(emptyMap(), emptyList())); + } + function updateOrderedMap(s, o, i) { + var a, + u, + _ = s._map, + w = s._list, + C = _.get(o), + L = void 0 !== C; + if (i === j) { + if (!L) return s; + w.size >= x && w.size >= 2 * _.size + ? ((a = (u = w.filter(function (s, o) { + return void 0 !== s && C !== o; + })) + .toKeyedSeq() + .map(function (s) { + return s[0]; + }) + .flip() + .toMap()), + s.__ownerID && (a.__ownerID = u.__ownerID = s.__ownerID)) + : ((a = _.remove(o)), (u = C === w.size - 1 ? w.pop() : w.set(C, void 0))); + } else if (L) { + if (i === w.get(C)[1]) return s; + ((a = _), (u = w.set(C, [o, i]))); + } else ((a = _.set(o, w.size)), (u = w.set(w.size, [o, i]))); + return s.__ownerID + ? ((s.size = a.size), (s._map = a), (s._list = u), (s.__hash = void 0), s) + : makeOrderedMap(a, u); + } + function ToKeyedSequence(s, o) { + ((this._iter = s), (this._useKeys = o), (this.size = s.size)); + } + function ToIndexedSequence(s) { + ((this._iter = s), (this.size = s.size)); + } + function ToSetSequence(s) { + ((this._iter = s), (this.size = s.size)); + } + function FromEntriesSequence(s) { + ((this._iter = s), (this.size = s.size)); + } + function flipFactory(s) { + var o = makeSequence(s); + return ( + (o._iter = s), + (o.size = s.size), + (o.flip = function () { + return s; + }), + (o.reverse = function () { + var o = s.reverse.apply(this); + return ( + (o.flip = function () { + return s.reverse(); + }), + o + ); + }), + (o.has = function (o) { + return s.includes(o); + }), + (o.includes = function (o) { + return s.has(o); + }), + (o.cacheResult = cacheResultThrough), + (o.__iterateUncached = function (o, i) { + var a = this; + return s.__iterate(function (s, i) { + return !1 !== o(i, s, a); + }, i); + }), + (o.__iteratorUncached = function (o, i) { + if (o === V) { + var a = s.__iterator(o, i); + return new Iterator(function () { + var s = a.next(); + if (!s.done) { + var o = s.value[0]; + ((s.value[0] = s.value[1]), (s.value[1] = o)); + } + return s; + }); + } + return s.__iterator(o === U ? $ : U, i); + }), + o + ); + } + function mapFactory(s, o, i) { + var a = makeSequence(s); + return ( + (a.size = s.size), + (a.has = function (o) { + return s.has(o); + }), + (a.get = function (a, u) { + var _ = s.get(a, j); + return _ === j ? u : o.call(i, _, a, s); + }), + (a.__iterateUncached = function (a, u) { + var _ = this; + return s.__iterate(function (s, u, w) { + return !1 !== a(o.call(i, s, u, w), u, _); + }, u); + }), + (a.__iteratorUncached = function (a, u) { + var _ = s.__iterator(V, u); + return new Iterator(function () { + var u = _.next(); + if (u.done) return u; + var w = u.value, + x = w[0]; + return iteratorValue(a, x, o.call(i, w[1], x, s), u); + }); + }), + a + ); + } + function reverseFactory(s, o) { + var i = makeSequence(s); + return ( + (i._iter = s), + (i.size = s.size), + (i.reverse = function () { + return s; + }), + s.flip && + (i.flip = function () { + var o = flipFactory(s); + return ( + (o.reverse = function () { + return s.flip(); + }), + o + ); + }), + (i.get = function (i, a) { + return s.get(o ? i : -1 - i, a); + }), + (i.has = function (i) { + return s.has(o ? i : -1 - i); + }), + (i.includes = function (o) { + return s.includes(o); + }), + (i.cacheResult = cacheResultThrough), + (i.__iterate = function (o, i) { + var a = this; + return s.__iterate(function (s, i) { + return o(s, i, a); + }, !i); + }), + (i.__iterator = function (o, i) { + return s.__iterator(o, !i); + }), + i + ); + } + function filterFactory(s, o, i, a) { + var u = makeSequence(s); + return ( + a && + ((u.has = function (a) { + var u = s.get(a, j); + return u !== j && !!o.call(i, u, a, s); + }), + (u.get = function (a, u) { + var _ = s.get(a, j); + return _ !== j && o.call(i, _, a, s) ? _ : u; + })), + (u.__iterateUncached = function (u, _) { + var w = this, + x = 0; + return ( + s.__iterate(function (s, _, C) { + if (o.call(i, s, _, C)) return (x++, u(s, a ? _ : x - 1, w)); + }, _), + x + ); + }), + (u.__iteratorUncached = function (u, _) { + var w = s.__iterator(V, _), + x = 0; + return new Iterator(function () { + for (;;) { + var _ = w.next(); + if (_.done) return _; + var C = _.value, + j = C[0], + L = C[1]; + if (o.call(i, L, j, s)) return iteratorValue(u, a ? j : x++, L, _); + } + }); + }), + u + ); + } + function countByFactory(s, o, i) { + var a = Map().asMutable(); + return ( + s.__iterate(function (u, _) { + a.update(o.call(i, u, _, s), 0, function (s) { + return s + 1; + }); + }), + a.asImmutable() + ); + } + function groupByFactory(s, o, i) { + var a = isKeyed(s), + u = (isOrdered(s) ? OrderedMap() : Map()).asMutable(); + s.__iterate(function (_, w) { + u.update(o.call(i, _, w, s), function (s) { + return ((s = s || []).push(a ? [w, _] : _), s); + }); + }); + var _ = iterableClass(s); + return u.map(function (o) { + return reify(s, _(o)); + }); + } + function sliceFactory(s, o, i, a) { + var u = s.size; + if ( + (void 0 !== o && (o |= 0), + void 0 !== i && (i === 1 / 0 ? (i = u) : (i |= 0)), + wholeSlice(o, i, u)) + ) + return s; + var _ = resolveBegin(o, u), + w = resolveEnd(i, u); + if (_ != _ || w != w) return sliceFactory(s.toSeq().cacheResult(), o, i, a); + var x, + C = w - _; + C == C && (x = C < 0 ? 0 : C); + var j = makeSequence(s); + return ( + (j.size = 0 === x ? x : (s.size && x) || void 0), + !a && + isSeq(s) && + x >= 0 && + (j.get = function (o, i) { + return (o = wrapIndex(this, o)) >= 0 && o < x ? s.get(o + _, i) : i; + }), + (j.__iterateUncached = function (o, i) { + var u = this; + if (0 === x) return 0; + if (i) return this.cacheResult().__iterate(o, i); + var w = 0, + C = !0, + j = 0; + return ( + s.__iterate(function (s, i) { + if (!C || !(C = w++ < _)) + return (j++, !1 !== o(s, a ? i : j - 1, u) && j !== x); + }), + j + ); + }), + (j.__iteratorUncached = function (o, i) { + if (0 !== x && i) return this.cacheResult().__iterator(o, i); + var u = 0 !== x && s.__iterator(o, i), + w = 0, + C = 0; + return new Iterator(function () { + for (; w++ < _; ) u.next(); + if (++C > x) return iteratorDone(); + var s = u.next(); + return a || o === U + ? s + : iteratorValue(o, C - 1, o === $ ? void 0 : s.value[1], s); + }); + }), + j + ); + } + function takeWhileFactory(s, o, i) { + var a = makeSequence(s); + return ( + (a.__iterateUncached = function (a, u) { + var _ = this; + if (u) return this.cacheResult().__iterate(a, u); + var w = 0; + return ( + s.__iterate(function (s, u, x) { + return o.call(i, s, u, x) && ++w && a(s, u, _); + }), + w + ); + }), + (a.__iteratorUncached = function (a, u) { + var _ = this; + if (u) return this.cacheResult().__iterator(a, u); + var w = s.__iterator(V, u), + x = !0; + return new Iterator(function () { + if (!x) return iteratorDone(); + var s = w.next(); + if (s.done) return s; + var u = s.value, + C = u[0], + j = u[1]; + return o.call(i, j, C, _) + ? a === V + ? s + : iteratorValue(a, C, j, s) + : ((x = !1), iteratorDone()); + }); + }), + a + ); + } + function skipWhileFactory(s, o, i, a) { + var u = makeSequence(s); + return ( + (u.__iterateUncached = function (u, _) { + var w = this; + if (_) return this.cacheResult().__iterate(u, _); + var x = !0, + C = 0; + return ( + s.__iterate(function (s, _, j) { + if (!x || !(x = o.call(i, s, _, j))) return (C++, u(s, a ? _ : C - 1, w)); + }), + C + ); + }), + (u.__iteratorUncached = function (u, _) { + var w = this; + if (_) return this.cacheResult().__iterator(u, _); + var x = s.__iterator(V, _), + C = !0, + j = 0; + return new Iterator(function () { + var s, _, L; + do { + if ((s = x.next()).done) + return a || u === U + ? s + : iteratorValue(u, j++, u === $ ? void 0 : s.value[1], s); + var B = s.value; + ((_ = B[0]), (L = B[1]), C && (C = o.call(i, L, _, w))); + } while (C); + return u === V ? s : iteratorValue(u, _, L, s); + }); + }), + u + ); + } + function concatFactory(s, o) { + var i = isKeyed(s), + a = [s] + .concat(o) + .map(function (s) { + return ( + isIterable(s) + ? i && (s = KeyedIterable(s)) + : (s = i + ? keyedSeqFromValue(s) + : indexedSeqFromValue(Array.isArray(s) ? s : [s])), + s + ); + }) + .filter(function (s) { + return 0 !== s.size; + }); + if (0 === a.length) return s; + if (1 === a.length) { + var u = a[0]; + if (u === s || (i && isKeyed(u)) || (isIndexed(s) && isIndexed(u))) return u; + } + var _ = new ArraySeq(a); + return ( + i ? (_ = _.toKeyedSeq()) : isIndexed(s) || (_ = _.toSetSeq()), + ((_ = _.flatten(!0)).size = a.reduce(function (s, o) { + if (void 0 !== s) { + var i = o.size; + if (void 0 !== i) return s + i; + } + }, 0)), + _ + ); + } + function flattenFactory(s, o, i) { + var a = makeSequence(s); + return ( + (a.__iterateUncached = function (a, u) { + var _ = 0, + w = !1; + function flatDeep(s, x) { + var C = this; + s.__iterate(function (s, u) { + return ( + (!o || x < o) && isIterable(s) + ? flatDeep(s, x + 1) + : !1 === a(s, i ? u : _++, C) && (w = !0), + !w + ); + }, u); + } + return (flatDeep(s, 0), _); + }), + (a.__iteratorUncached = function (a, u) { + var _ = s.__iterator(a, u), + w = [], + x = 0; + return new Iterator(function () { + for (; _; ) { + var s = _.next(); + if (!1 === s.done) { + var C = s.value; + if ((a === V && (C = C[1]), (o && !(w.length < o)) || !isIterable(C))) + return i ? s : iteratorValue(a, x++, C, s); + (w.push(_), (_ = C.__iterator(a, u))); + } else _ = w.pop(); + } + return iteratorDone(); + }); + }), + a + ); + } + function flatMapFactory(s, o, i) { + var a = iterableClass(s); + return s + .toSeq() + .map(function (u, _) { + return a(o.call(i, u, _, s)); + }) + .flatten(!0); + } + function interposeFactory(s, o) { + var i = makeSequence(s); + return ( + (i.size = s.size && 2 * s.size - 1), + (i.__iterateUncached = function (i, a) { + var u = this, + _ = 0; + return ( + s.__iterate(function (s, a) { + return (!_ || !1 !== i(o, _++, u)) && !1 !== i(s, _++, u); + }, a), + _ + ); + }), + (i.__iteratorUncached = function (i, a) { + var u, + _ = s.__iterator(U, a), + w = 0; + return new Iterator(function () { + return (!u || w % 2) && (u = _.next()).done + ? u + : w % 2 + ? iteratorValue(i, w++, o) + : iteratorValue(i, w++, u.value, u); + }); + }), + i + ); + } + function sortFactory(s, o, i) { + o || (o = defaultComparator); + var a = isKeyed(s), + u = 0, + _ = s + .toSeq() + .map(function (o, a) { + return [a, o, u++, i ? i(o, a, s) : o]; + }) + .toArray(); + return ( + _.sort(function (s, i) { + return o(s[3], i[3]) || s[2] - i[2]; + }).forEach( + a + ? function (s, o) { + _[o].length = 2; + } + : function (s, o) { + _[o] = s[1]; + } + ), + a ? KeyedSeq(_) : isIndexed(s) ? IndexedSeq(_) : SetSeq(_) + ); + } + function maxFactory(s, o, i) { + if ((o || (o = defaultComparator), i)) { + var a = s + .toSeq() + .map(function (o, a) { + return [o, i(o, a, s)]; + }) + .reduce(function (s, i) { + return maxCompare(o, s[1], i[1]) ? i : s; + }); + return a && a[0]; + } + return s.reduce(function (s, i) { + return maxCompare(o, s, i) ? i : s; + }); + } + function maxCompare(s, o, i) { + var a = s(i, o); + return (0 === a && i !== o && (null == i || i != i)) || a > 0; + } + function zipWithFactory(s, o, i) { + var a = makeSequence(s); + return ( + (a.size = new ArraySeq(i) + .map(function (s) { + return s.size; + }) + .min()), + (a.__iterate = function (s, o) { + for ( + var i, a = this.__iterator(U, o), u = 0; + !(i = a.next()).done && !1 !== s(i.value, u++, this); + ); + return u; + }), + (a.__iteratorUncached = function (s, a) { + var u = i.map(function (s) { + return ((s = Iterable(s)), getIterator(a ? s.reverse() : s)); + }), + _ = 0, + w = !1; + return new Iterator(function () { + var i; + return ( + w || + ((i = u.map(function (s) { + return s.next(); + })), + (w = i.some(function (s) { + return s.done; + }))), + w + ? iteratorDone() + : iteratorValue( + s, + _++, + o.apply( + null, + i.map(function (s) { + return s.value; + }) + ) + ) + ); + }); + }), + a + ); + } + function reify(s, o) { + return isSeq(s) ? o : s.constructor(o); + } + function validateEntry(s) { + if (s !== Object(s)) throw new TypeError('Expected [K, V] tuple: ' + s); + } + function resolveSize(s) { + return (assertNotInfinite(s.size), ensureSize(s)); + } + function iterableClass(s) { + return isKeyed(s) ? KeyedIterable : isIndexed(s) ? IndexedIterable : SetIterable; + } + function makeSequence(s) { + return Object.create( + (isKeyed(s) ? KeyedSeq : isIndexed(s) ? IndexedSeq : SetSeq).prototype + ); + } + function cacheResultThrough() { + return this._iter.cacheResult + ? (this._iter.cacheResult(), (this.size = this._iter.size), this) + : Seq.prototype.cacheResult.call(this); + } + function defaultComparator(s, o) { + return s > o ? 1 : s < o ? -1 : 0; + } + function forceIterator(s) { + var o = getIterator(s); + if (!o) { + if (!isArrayLike(s)) throw new TypeError('Expected iterable or array-like: ' + s); + o = getIterator(Iterable(s)); + } + return o; + } + function Record(s, o) { + var i, + a = function Record(_) { + if (_ instanceof a) return _; + if (!(this instanceof a)) return new a(_); + if (!i) { + i = !0; + var w = Object.keys(s); + (setProps(u, w), + (u.size = w.length), + (u._name = o), + (u._keys = w), + (u._defaultValues = s)); + } + this._map = Map(_); + }, + u = (a.prototype = Object.create(tt)); + return ((u.constructor = a), a); + } + (createClass(OrderedMap, Map), + (OrderedMap.of = function () { + return this(arguments); + }), + (OrderedMap.prototype.toString = function () { + return this.__toString('OrderedMap {', '}'); + }), + (OrderedMap.prototype.get = function (s, o) { + var i = this._map.get(s); + return void 0 !== i ? this._list.get(i)[1] : o; + }), + (OrderedMap.prototype.clear = function () { + return 0 === this.size + ? this + : this.__ownerID + ? ((this.size = 0), this._map.clear(), this._list.clear(), this) + : emptyOrderedMap(); + }), + (OrderedMap.prototype.set = function (s, o) { + return updateOrderedMap(this, s, o); + }), + (OrderedMap.prototype.remove = function (s) { + return updateOrderedMap(this, s, j); + }), + (OrderedMap.prototype.wasAltered = function () { + return this._map.wasAltered() || this._list.wasAltered(); + }), + (OrderedMap.prototype.__iterate = function (s, o) { + var i = this; + return this._list.__iterate(function (o) { + return o && s(o[1], o[0], i); + }, o); + }), + (OrderedMap.prototype.__iterator = function (s, o) { + return this._list.fromEntrySeq().__iterator(s, o); + }), + (OrderedMap.prototype.__ensureOwner = function (s) { + if (s === this.__ownerID) return this; + var o = this._map.__ensureOwner(s), + i = this._list.__ensureOwner(s); + return s + ? makeOrderedMap(o, i, s, this.__hash) + : ((this.__ownerID = s), (this._map = o), (this._list = i), this); + }), + (OrderedMap.isOrderedMap = isOrderedMap), + (OrderedMap.prototype[u] = !0), + (OrderedMap.prototype[_] = OrderedMap.prototype.remove), + createClass(ToKeyedSequence, KeyedSeq), + (ToKeyedSequence.prototype.get = function (s, o) { + return this._iter.get(s, o); + }), + (ToKeyedSequence.prototype.has = function (s) { + return this._iter.has(s); + }), + (ToKeyedSequence.prototype.valueSeq = function () { + return this._iter.valueSeq(); + }), + (ToKeyedSequence.prototype.reverse = function () { + var s = this, + o = reverseFactory(this, !0); + return ( + this._useKeys || + (o.valueSeq = function () { + return s._iter.toSeq().reverse(); + }), + o + ); + }), + (ToKeyedSequence.prototype.map = function (s, o) { + var i = this, + a = mapFactory(this, s, o); + return ( + this._useKeys || + (a.valueSeq = function () { + return i._iter.toSeq().map(s, o); + }), + a + ); + }), + (ToKeyedSequence.prototype.__iterate = function (s, o) { + var i, + a = this; + return this._iter.__iterate( + this._useKeys + ? function (o, i) { + return s(o, i, a); + } + : ((i = o ? resolveSize(this) : 0), + function (u) { + return s(u, o ? --i : i++, a); + }), + o + ); + }), + (ToKeyedSequence.prototype.__iterator = function (s, o) { + if (this._useKeys) return this._iter.__iterator(s, o); + var i = this._iter.__iterator(U, o), + a = o ? resolveSize(this) : 0; + return new Iterator(function () { + var u = i.next(); + return u.done ? u : iteratorValue(s, o ? --a : a++, u.value, u); + }); + }), + (ToKeyedSequence.prototype[u] = !0), + createClass(ToIndexedSequence, IndexedSeq), + (ToIndexedSequence.prototype.includes = function (s) { + return this._iter.includes(s); + }), + (ToIndexedSequence.prototype.__iterate = function (s, o) { + var i = this, + a = 0; + return this._iter.__iterate(function (o) { + return s(o, a++, i); + }, o); + }), + (ToIndexedSequence.prototype.__iterator = function (s, o) { + var i = this._iter.__iterator(U, o), + a = 0; + return new Iterator(function () { + var o = i.next(); + return o.done ? o : iteratorValue(s, a++, o.value, o); + }); + }), + createClass(ToSetSequence, SetSeq), + (ToSetSequence.prototype.has = function (s) { + return this._iter.includes(s); + }), + (ToSetSequence.prototype.__iterate = function (s, o) { + var i = this; + return this._iter.__iterate(function (o) { + return s(o, o, i); + }, o); + }), + (ToSetSequence.prototype.__iterator = function (s, o) { + var i = this._iter.__iterator(U, o); + return new Iterator(function () { + var o = i.next(); + return o.done ? o : iteratorValue(s, o.value, o.value, o); + }); + }), + createClass(FromEntriesSequence, KeyedSeq), + (FromEntriesSequence.prototype.entrySeq = function () { + return this._iter.toSeq(); + }), + (FromEntriesSequence.prototype.__iterate = function (s, o) { + var i = this; + return this._iter.__iterate(function (o) { + if (o) { + validateEntry(o); + var a = isIterable(o); + return s(a ? o.get(1) : o[1], a ? o.get(0) : o[0], i); + } + }, o); + }), + (FromEntriesSequence.prototype.__iterator = function (s, o) { + var i = this._iter.__iterator(U, o); + return new Iterator(function () { + for (;;) { + var o = i.next(); + if (o.done) return o; + var a = o.value; + if (a) { + validateEntry(a); + var u = isIterable(a); + return iteratorValue(s, u ? a.get(0) : a[0], u ? a.get(1) : a[1], o); + } + } + }); + }), + (ToIndexedSequence.prototype.cacheResult = + ToKeyedSequence.prototype.cacheResult = + ToSetSequence.prototype.cacheResult = + FromEntriesSequence.prototype.cacheResult = + cacheResultThrough), + createClass(Record, KeyedCollection), + (Record.prototype.toString = function () { + return this.__toString(recordName(this) + ' {', '}'); + }), + (Record.prototype.has = function (s) { + return this._defaultValues.hasOwnProperty(s); + }), + (Record.prototype.get = function (s, o) { + if (!this.has(s)) return o; + var i = this._defaultValues[s]; + return this._map ? this._map.get(s, i) : i; + }), + (Record.prototype.clear = function () { + if (this.__ownerID) return (this._map && this._map.clear(), this); + var s = this.constructor; + return s._empty || (s._empty = makeRecord(this, emptyMap())); + }), + (Record.prototype.set = function (s, o) { + if (!this.has(s)) + throw new Error('Cannot set unknown key "' + s + '" on ' + recordName(this)); + if (this._map && !this._map.has(s) && o === this._defaultValues[s]) return this; + var i = this._map && this._map.set(s, o); + return this.__ownerID || i === this._map ? this : makeRecord(this, i); + }), + (Record.prototype.remove = function (s) { + if (!this.has(s)) return this; + var o = this._map && this._map.remove(s); + return this.__ownerID || o === this._map ? this : makeRecord(this, o); + }), + (Record.prototype.wasAltered = function () { + return this._map.wasAltered(); + }), + (Record.prototype.__iterator = function (s, o) { + var i = this; + return KeyedIterable(this._defaultValues) + .map(function (s, o) { + return i.get(o); + }) + .__iterator(s, o); + }), + (Record.prototype.__iterate = function (s, o) { + var i = this; + return KeyedIterable(this._defaultValues) + .map(function (s, o) { + return i.get(o); + }) + .__iterate(s, o); + }), + (Record.prototype.__ensureOwner = function (s) { + if (s === this.__ownerID) return this; + var o = this._map && this._map.__ensureOwner(s); + return s ? makeRecord(this, o, s) : ((this.__ownerID = s), (this._map = o), this); + })); + var tt = Record.prototype; + function makeRecord(s, o, i) { + var a = Object.create(Object.getPrototypeOf(s)); + return ((a._map = o), (a.__ownerID = i), a); + } + function recordName(s) { + return s._name || s.constructor.name || 'Record'; + } + function setProps(s, o) { + try { + o.forEach(setProp.bind(void 0, s)); + } catch (s) {} + } + function setProp(s, o) { + Object.defineProperty(s, o, { + get: function () { + return this.get(o); + }, + set: function (s) { + (invariant(this.__ownerID, 'Cannot set on an immutable record.'), this.set(o, s)); + } + }); + } + function Set(s) { + return null == s + ? emptySet() + : isSet(s) && !isOrdered(s) + ? s + : emptySet().withMutations(function (o) { + var i = SetIterable(s); + (assertNotInfinite(i.size), + i.forEach(function (s) { + return o.add(s); + })); + }); + } + function isSet(s) { + return !(!s || !s[nt]); + } + ((tt[_] = tt.remove), + (tt.deleteIn = tt.removeIn = $e.removeIn), + (tt.merge = $e.merge), + (tt.mergeWith = $e.mergeWith), + (tt.mergeIn = $e.mergeIn), + (tt.mergeDeep = $e.mergeDeep), + (tt.mergeDeepWith = $e.mergeDeepWith), + (tt.mergeDeepIn = $e.mergeDeepIn), + (tt.setIn = $e.setIn), + (tt.update = $e.update), + (tt.updateIn = $e.updateIn), + (tt.withMutations = $e.withMutations), + (tt.asMutable = $e.asMutable), + (tt.asImmutable = $e.asImmutable), + createClass(Set, SetCollection), + (Set.of = function () { + return this(arguments); + }), + (Set.fromKeys = function (s) { + return this(KeyedIterable(s).keySeq()); + }), + (Set.prototype.toString = function () { + return this.__toString('Set {', '}'); + }), + (Set.prototype.has = function (s) { + return this._map.has(s); + }), + (Set.prototype.add = function (s) { + return updateSet(this, this._map.set(s, !0)); + }), + (Set.prototype.remove = function (s) { + return updateSet(this, this._map.remove(s)); + }), + (Set.prototype.clear = function () { + return updateSet(this, this._map.clear()); + }), + (Set.prototype.union = function () { + var o = s.call(arguments, 0); + return 0 === + (o = o.filter(function (s) { + return 0 !== s.size; + })).length + ? this + : 0 !== this.size || this.__ownerID || 1 !== o.length + ? this.withMutations(function (s) { + for (var i = 0; i < o.length; i++) + SetIterable(o[i]).forEach(function (o) { + return s.add(o); + }); + }) + : this.constructor(o[0]); + }), + (Set.prototype.intersect = function () { + var o = s.call(arguments, 0); + if (0 === o.length) return this; + o = o.map(function (s) { + return SetIterable(s); + }); + var i = this; + return this.withMutations(function (s) { + i.forEach(function (i) { + o.every(function (s) { + return s.includes(i); + }) || s.remove(i); + }); + }); + }), + (Set.prototype.subtract = function () { + var o = s.call(arguments, 0); + if (0 === o.length) return this; + o = o.map(function (s) { + return SetIterable(s); + }); + var i = this; + return this.withMutations(function (s) { + i.forEach(function (i) { + o.some(function (s) { + return s.includes(i); + }) && s.remove(i); + }); + }); + }), + (Set.prototype.merge = function () { + return this.union.apply(this, arguments); + }), + (Set.prototype.mergeWith = function (o) { + var i = s.call(arguments, 1); + return this.union.apply(this, i); + }), + (Set.prototype.sort = function (s) { + return OrderedSet(sortFactory(this, s)); + }), + (Set.prototype.sortBy = function (s, o) { + return OrderedSet(sortFactory(this, o, s)); + }), + (Set.prototype.wasAltered = function () { + return this._map.wasAltered(); + }), + (Set.prototype.__iterate = function (s, o) { + var i = this; + return this._map.__iterate(function (o, a) { + return s(a, a, i); + }, o); + }), + (Set.prototype.__iterator = function (s, o) { + return this._map + .map(function (s, o) { + return o; + }) + .__iterator(s, o); + }), + (Set.prototype.__ensureOwner = function (s) { + if (s === this.__ownerID) return this; + var o = this._map.__ensureOwner(s); + return s ? this.__make(o, s) : ((this.__ownerID = s), (this._map = o), this); + }), + (Set.isSet = isSet)); + var rt, + nt = '@@__IMMUTABLE_SET__@@', + st = Set.prototype; + function updateSet(s, o) { + return s.__ownerID + ? ((s.size = o.size), (s._map = o), s) + : o === s._map + ? s + : 0 === o.size + ? s.__empty() + : s.__make(o); + } + function makeSet(s, o) { + var i = Object.create(st); + return ((i.size = s ? s.size : 0), (i._map = s), (i.__ownerID = o), i); + } + function emptySet() { + return rt || (rt = makeSet(emptyMap())); + } + function OrderedSet(s) { + return null == s + ? emptyOrderedSet() + : isOrderedSet(s) + ? s + : emptyOrderedSet().withMutations(function (o) { + var i = SetIterable(s); + (assertNotInfinite(i.size), + i.forEach(function (s) { + return o.add(s); + })); + }); + } + function isOrderedSet(s) { + return isSet(s) && isOrdered(s); + } + ((st[nt] = !0), + (st[_] = st.remove), + (st.mergeDeep = st.merge), + (st.mergeDeepWith = st.mergeWith), + (st.withMutations = $e.withMutations), + (st.asMutable = $e.asMutable), + (st.asImmutable = $e.asImmutable), + (st.__empty = emptySet), + (st.__make = makeSet), + createClass(OrderedSet, Set), + (OrderedSet.of = function () { + return this(arguments); + }), + (OrderedSet.fromKeys = function (s) { + return this(KeyedIterable(s).keySeq()); + }), + (OrderedSet.prototype.toString = function () { + return this.__toString('OrderedSet {', '}'); + }), + (OrderedSet.isOrderedSet = isOrderedSet)); + var ot, + it = OrderedSet.prototype; + function makeOrderedSet(s, o) { + var i = Object.create(it); + return ((i.size = s ? s.size : 0), (i._map = s), (i.__ownerID = o), i); + } + function emptyOrderedSet() { + return ot || (ot = makeOrderedSet(emptyOrderedMap())); + } + function Stack(s) { + return null == s ? emptyStack() : isStack(s) ? s : emptyStack().unshiftAll(s); + } + function isStack(s) { + return !(!s || !s[ct]); + } + ((it[u] = !0), + (it.__empty = emptyOrderedSet), + (it.__make = makeOrderedSet), + createClass(Stack, IndexedCollection), + (Stack.of = function () { + return this(arguments); + }), + (Stack.prototype.toString = function () { + return this.__toString('Stack [', ']'); + }), + (Stack.prototype.get = function (s, o) { + var i = this._head; + for (s = wrapIndex(this, s); i && s--; ) i = i.next; + return i ? i.value : o; + }), + (Stack.prototype.peek = function () { + return this._head && this._head.value; + }), + (Stack.prototype.push = function () { + if (0 === arguments.length) return this; + for ( + var s = this.size + arguments.length, o = this._head, i = arguments.length - 1; + i >= 0; + i-- + ) + o = { value: arguments[i], next: o }; + return this.__ownerID + ? ((this.size = s), + (this._head = o), + (this.__hash = void 0), + (this.__altered = !0), + this) + : makeStack(s, o); + }), + (Stack.prototype.pushAll = function (s) { + if (0 === (s = IndexedIterable(s)).size) return this; + assertNotInfinite(s.size); + var o = this.size, + i = this._head; + return ( + s.reverse().forEach(function (s) { + (o++, (i = { value: s, next: i })); + }), + this.__ownerID + ? ((this.size = o), + (this._head = i), + (this.__hash = void 0), + (this.__altered = !0), + this) + : makeStack(o, i) + ); + }), + (Stack.prototype.pop = function () { + return this.slice(1); + }), + (Stack.prototype.unshift = function () { + return this.push.apply(this, arguments); + }), + (Stack.prototype.unshiftAll = function (s) { + return this.pushAll(s); + }), + (Stack.prototype.shift = function () { + return this.pop.apply(this, arguments); + }), + (Stack.prototype.clear = function () { + return 0 === this.size + ? this + : this.__ownerID + ? ((this.size = 0), + (this._head = void 0), + (this.__hash = void 0), + (this.__altered = !0), + this) + : emptyStack(); + }), + (Stack.prototype.slice = function (s, o) { + if (wholeSlice(s, o, this.size)) return this; + var i = resolveBegin(s, this.size); + if (resolveEnd(o, this.size) !== this.size) + return IndexedCollection.prototype.slice.call(this, s, o); + for (var a = this.size - i, u = this._head; i--; ) u = u.next; + return this.__ownerID + ? ((this.size = a), + (this._head = u), + (this.__hash = void 0), + (this.__altered = !0), + this) + : makeStack(a, u); + }), + (Stack.prototype.__ensureOwner = function (s) { + return s === this.__ownerID + ? this + : s + ? makeStack(this.size, this._head, s, this.__hash) + : ((this.__ownerID = s), (this.__altered = !1), this); + }), + (Stack.prototype.__iterate = function (s, o) { + if (o) return this.reverse().__iterate(s); + for (var i = 0, a = this._head; a && !1 !== s(a.value, i++, this); ) a = a.next; + return i; + }), + (Stack.prototype.__iterator = function (s, o) { + if (o) return this.reverse().__iterator(s); + var i = 0, + a = this._head; + return new Iterator(function () { + if (a) { + var o = a.value; + return ((a = a.next), iteratorValue(s, i++, o)); + } + return iteratorDone(); + }); + }), + (Stack.isStack = isStack)); + var at, + ct = '@@__IMMUTABLE_STACK__@@', + lt = Stack.prototype; + function makeStack(s, o, i, a) { + var u = Object.create(lt); + return ( + (u.size = s), + (u._head = o), + (u.__ownerID = i), + (u.__hash = a), + (u.__altered = !1), + u + ); + } + function emptyStack() { + return at || (at = makeStack(0)); + } + function mixin(s, o) { + var keyCopier = function (i) { + s.prototype[i] = o[i]; + }; + return ( + Object.keys(o).forEach(keyCopier), + Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(o).forEach(keyCopier), + s + ); + } + function isProtoKey(s) { + return 'string' == typeof s && ('__proto__' === s || 'constructor' === s); + } + ((lt[ct] = !0), + (lt.withMutations = $e.withMutations), + (lt.asMutable = $e.asMutable), + (lt.asImmutable = $e.asImmutable), + (lt.wasAltered = $e.wasAltered), + (Iterable.Iterator = Iterator), + mixin(Iterable, { + toArray: function () { + assertNotInfinite(this.size); + var s = new Array(this.size || 0); + return ( + this.valueSeq().__iterate(function (o, i) { + s[i] = o; + }), + s + ); + }, + toIndexedSeq: function () { + return new ToIndexedSequence(this); + }, + toJS: function () { + return this.toSeq() + .map(function (s) { + return s && 'function' == typeof s.toJS ? s.toJS() : s; + }) + .__toJS(); + }, + toJSON: function () { + return this.toSeq() + .map(function (s) { + return s && 'function' == typeof s.toJSON ? s.toJSON() : s; + }) + .__toJS(); + }, + toKeyedSeq: function () { + return new ToKeyedSequence(this, !0); + }, + toMap: function () { + return Map(this.toKeyedSeq()); + }, + toObject: function () { + assertNotInfinite(this.size); + var s = {}; + return ( + this.__iterate(function (o, i) { + isProtoKey(i) || (s[i] = o); + }), + s + ); + }, + toOrderedMap: function () { + return OrderedMap(this.toKeyedSeq()); + }, + toOrderedSet: function () { + return OrderedSet(isKeyed(this) ? this.valueSeq() : this); + }, + toSet: function () { + return Set(isKeyed(this) ? this.valueSeq() : this); + }, + toSetSeq: function () { + return new ToSetSequence(this); + }, + toSeq: function () { + return isIndexed(this) + ? this.toIndexedSeq() + : isKeyed(this) + ? this.toKeyedSeq() + : this.toSetSeq(); + }, + toStack: function () { + return Stack(isKeyed(this) ? this.valueSeq() : this); + }, + toList: function () { + return List(isKeyed(this) ? this.valueSeq() : this); + }, + toString: function () { + return '[Iterable]'; + }, + __toString: function (s, o) { + return 0 === this.size + ? s + o + : s + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + o; + }, + concat: function () { + return reify(this, concatFactory(this, s.call(arguments, 0))); + }, + includes: function (s) { + return this.some(function (o) { + return is(o, s); + }); + }, + entries: function () { + return this.__iterator(V); + }, + every: function (s, o) { + assertNotInfinite(this.size); + var i = !0; + return ( + this.__iterate(function (a, u, _) { + if (!s.call(o, a, u, _)) return ((i = !1), !1); + }), + i + ); + }, + filter: function (s, o) { + return reify(this, filterFactory(this, s, o, !0)); + }, + find: function (s, o, i) { + var a = this.findEntry(s, o); + return a ? a[1] : i; + }, + forEach: function (s, o) { + return (assertNotInfinite(this.size), this.__iterate(o ? s.bind(o) : s)); + }, + join: function (s) { + (assertNotInfinite(this.size), (s = void 0 !== s ? '' + s : ',')); + var o = '', + i = !0; + return ( + this.__iterate(function (a) { + (i ? (i = !1) : (o += s), (o += null != a ? a.toString() : '')); + }), + o + ); + }, + keys: function () { + return this.__iterator($); + }, + map: function (s, o) { + return reify(this, mapFactory(this, s, o)); + }, + reduce: function (s, o, i) { + var a, u; + return ( + assertNotInfinite(this.size), + arguments.length < 2 ? (u = !0) : (a = o), + this.__iterate(function (o, _, w) { + u ? ((u = !1), (a = o)) : (a = s.call(i, a, o, _, w)); + }), + a + ); + }, + reduceRight: function (s, o, i) { + var a = this.toKeyedSeq().reverse(); + return a.reduce.apply(a, arguments); + }, + reverse: function () { + return reify(this, reverseFactory(this, !0)); + }, + slice: function (s, o) { + return reify(this, sliceFactory(this, s, o, !0)); + }, + some: function (s, o) { + return !this.every(not(s), o); + }, + sort: function (s) { + return reify(this, sortFactory(this, s)); + }, + values: function () { + return this.__iterator(U); + }, + butLast: function () { + return this.slice(0, -1); + }, + isEmpty: function () { + return void 0 !== this.size + ? 0 === this.size + : !this.some(function () { + return !0; + }); + }, + count: function (s, o) { + return ensureSize(s ? this.toSeq().filter(s, o) : this); + }, + countBy: function (s, o) { + return countByFactory(this, s, o); + }, + equals: function (s) { + return deepEqual(this, s); + }, + entrySeq: function () { + var s = this; + if (s._cache) return new ArraySeq(s._cache); + var o = s.toSeq().map(entryMapper).toIndexedSeq(); + return ( + (o.fromEntrySeq = function () { + return s.toSeq(); + }), + o + ); + }, + filterNot: function (s, o) { + return this.filter(not(s), o); + }, + findEntry: function (s, o, i) { + var a = i; + return ( + this.__iterate(function (i, u, _) { + if (s.call(o, i, u, _)) return ((a = [u, i]), !1); + }), + a + ); + }, + findKey: function (s, o) { + var i = this.findEntry(s, o); + return i && i[0]; + }, + findLast: function (s, o, i) { + return this.toKeyedSeq().reverse().find(s, o, i); + }, + findLastEntry: function (s, o, i) { + return this.toKeyedSeq().reverse().findEntry(s, o, i); + }, + findLastKey: function (s, o) { + return this.toKeyedSeq().reverse().findKey(s, o); + }, + first: function () { + return this.find(returnTrue); + }, + flatMap: function (s, o) { + return reify(this, flatMapFactory(this, s, o)); + }, + flatten: function (s) { + return reify(this, flattenFactory(this, s, !0)); + }, + fromEntrySeq: function () { + return new FromEntriesSequence(this); + }, + get: function (s, o) { + return this.find( + function (o, i) { + return is(i, s); + }, + void 0, + o + ); + }, + getIn: function (s, o) { + for (var i, a = this, u = forceIterator(s); !(i = u.next()).done; ) { + var _ = i.value; + if ((a = a && a.get ? a.get(_, j) : j) === j) return o; + } + return a; + }, + groupBy: function (s, o) { + return groupByFactory(this, s, o); + }, + has: function (s) { + return this.get(s, j) !== j; + }, + hasIn: function (s) { + return this.getIn(s, j) !== j; + }, + isSubset: function (s) { + return ( + (s = 'function' == typeof s.includes ? s : Iterable(s)), + this.every(function (o) { + return s.includes(o); + }) + ); + }, + isSuperset: function (s) { + return (s = 'function' == typeof s.isSubset ? s : Iterable(s)).isSubset(this); + }, + keyOf: function (s) { + return this.findKey(function (o) { + return is(o, s); + }); + }, + keySeq: function () { + return this.toSeq().map(keyMapper).toIndexedSeq(); + }, + last: function () { + return this.toSeq().reverse().first(); + }, + lastKeyOf: function (s) { + return this.toKeyedSeq().reverse().keyOf(s); + }, + max: function (s) { + return maxFactory(this, s); + }, + maxBy: function (s, o) { + return maxFactory(this, o, s); + }, + min: function (s) { + return maxFactory(this, s ? neg(s) : defaultNegComparator); + }, + minBy: function (s, o) { + return maxFactory(this, o ? neg(o) : defaultNegComparator, s); + }, + rest: function () { + return this.slice(1); + }, + skip: function (s) { + return this.slice(Math.max(0, s)); + }, + skipLast: function (s) { + return reify(this, this.toSeq().reverse().skip(s).reverse()); + }, + skipWhile: function (s, o) { + return reify(this, skipWhileFactory(this, s, o, !0)); + }, + skipUntil: function (s, o) { + return this.skipWhile(not(s), o); + }, + sortBy: function (s, o) { + return reify(this, sortFactory(this, o, s)); + }, + take: function (s) { + return this.slice(0, Math.max(0, s)); + }, + takeLast: function (s) { + return reify(this, this.toSeq().reverse().take(s).reverse()); + }, + takeWhile: function (s, o) { + return reify(this, takeWhileFactory(this, s, o)); + }, + takeUntil: function (s, o) { + return this.takeWhile(not(s), o); + }, + valueSeq: function () { + return this.toIndexedSeq(); + }, + hashCode: function () { + return this.__hash || (this.__hash = hashIterable(this)); + } + })); + var ut = Iterable.prototype; + ((ut[o] = !0), + (ut[Z] = ut.values), + (ut.__toJS = ut.toArray), + (ut.__toStringMapper = quoteString), + (ut.inspect = ut.toSource = + function () { + return this.toString(); + }), + (ut.chain = ut.flatMap), + (ut.contains = ut.includes), + mixin(KeyedIterable, { + flip: function () { + return reify(this, flipFactory(this)); + }, + mapEntries: function (s, o) { + var i = this, + a = 0; + return reify( + this, + this.toSeq() + .map(function (u, _) { + return s.call(o, [_, u], a++, i); + }) + .fromEntrySeq() + ); + }, + mapKeys: function (s, o) { + var i = this; + return reify( + this, + this.toSeq() + .flip() + .map(function (a, u) { + return s.call(o, a, u, i); + }) + .flip() + ); + } + })); + var pt = KeyedIterable.prototype; + function keyMapper(s, o) { + return o; + } + function entryMapper(s, o) { + return [o, s]; + } + function not(s) { + return function () { + return !s.apply(this, arguments); + }; + } + function neg(s) { + return function () { + return -s.apply(this, arguments); + }; + } + function quoteString(s) { + return 'string' == typeof s ? JSON.stringify(s) : String(s); + } + function defaultZipper() { + return arrCopy(arguments); + } + function defaultNegComparator(s, o) { + return s < o ? 1 : s > o ? -1 : 0; + } + function hashIterable(s) { + if (s.size === 1 / 0) return 0; + var o = isOrdered(s), + i = isKeyed(s), + a = o ? 1 : 0; + return murmurHashOfSize( + s.__iterate( + i + ? o + ? function (s, o) { + a = (31 * a + hashMerge(hash(s), hash(o))) | 0; + } + : function (s, o) { + a = (a + hashMerge(hash(s), hash(o))) | 0; + } + : o + ? function (s) { + a = (31 * a + hash(s)) | 0; + } + : function (s) { + a = (a + hash(s)) | 0; + } + ), + a + ); + } + function murmurHashOfSize(s, o) { + return ( + (o = le(o, 3432918353)), + (o = le((o << 15) | (o >>> -15), 461845907)), + (o = le((o << 13) | (o >>> -13), 5)), + (o = le((o = (o + 3864292196) ^ s) ^ (o >>> 16), 2246822507)), + (o = smi((o = le(o ^ (o >>> 13), 3266489909)) ^ (o >>> 16))) + ); + } + function hashMerge(s, o) { + return s ^ (o + 2654435769 + (s << 6) + (s >> 2)); + } + return ( + (pt[i] = !0), + (pt[Z] = ut.entries), + (pt.__toJS = ut.toObject), + (pt.__toStringMapper = function (s, o) { + return JSON.stringify(o) + ': ' + quoteString(s); + }), + mixin(IndexedIterable, { + toKeyedSeq: function () { + return new ToKeyedSequence(this, !1); + }, + filter: function (s, o) { + return reify(this, filterFactory(this, s, o, !1)); + }, + findIndex: function (s, o) { + var i = this.findEntry(s, o); + return i ? i[0] : -1; + }, + indexOf: function (s) { + var o = this.keyOf(s); + return void 0 === o ? -1 : o; + }, + lastIndexOf: function (s) { + var o = this.lastKeyOf(s); + return void 0 === o ? -1 : o; + }, + reverse: function () { + return reify(this, reverseFactory(this, !1)); + }, + slice: function (s, o) { + return reify(this, sliceFactory(this, s, o, !1)); + }, + splice: function (s, o) { + var i = arguments.length; + if (((o = Math.max(0 | o, 0)), 0 === i || (2 === i && !o))) return this; + s = resolveBegin(s, s < 0 ? this.count() : this.size); + var a = this.slice(0, s); + return reify( + this, + 1 === i ? a : a.concat(arrCopy(arguments, 2), this.slice(s + o)) + ); + }, + findLastIndex: function (s, o) { + var i = this.findLastEntry(s, o); + return i ? i[0] : -1; + }, + first: function () { + return this.get(0); + }, + flatten: function (s) { + return reify(this, flattenFactory(this, s, !1)); + }, + get: function (s, o) { + return (s = wrapIndex(this, s)) < 0 || + this.size === 1 / 0 || + (void 0 !== this.size && s > this.size) + ? o + : this.find( + function (o, i) { + return i === s; + }, + void 0, + o + ); + }, + has: function (s) { + return ( + (s = wrapIndex(this, s)) >= 0 && + (void 0 !== this.size + ? this.size === 1 / 0 || s < this.size + : -1 !== this.indexOf(s)) + ); + }, + interpose: function (s) { + return reify(this, interposeFactory(this, s)); + }, + interleave: function () { + var s = [this].concat(arrCopy(arguments)), + o = zipWithFactory(this.toSeq(), IndexedSeq.of, s), + i = o.flatten(!0); + return (o.size && (i.size = o.size * s.length), reify(this, i)); + }, + keySeq: function () { + return Range(0, this.size); + }, + last: function () { + return this.get(-1); + }, + skipWhile: function (s, o) { + return reify(this, skipWhileFactory(this, s, o, !1)); + }, + zip: function () { + return reify( + this, + zipWithFactory(this, defaultZipper, [this].concat(arrCopy(arguments))) + ); + }, + zipWith: function (s) { + var o = arrCopy(arguments); + return ((o[0] = this), reify(this, zipWithFactory(this, s, o))); + } + }), + (IndexedIterable.prototype[a] = !0), + (IndexedIterable.prototype[u] = !0), + mixin(SetIterable, { + get: function (s, o) { + return this.has(s) ? s : o; + }, + includes: function (s) { + return this.has(s); + }, + keySeq: function () { + return this.valueSeq(); + } + }), + (SetIterable.prototype.has = ut.includes), + (SetIterable.prototype.contains = SetIterable.prototype.includes), + mixin(KeyedSeq, KeyedIterable.prototype), + mixin(IndexedSeq, IndexedIterable.prototype), + mixin(SetSeq, SetIterable.prototype), + mixin(KeyedCollection, KeyedIterable.prototype), + mixin(IndexedCollection, IndexedIterable.prototype), + mixin(SetCollection, SetIterable.prototype), + { + Iterable, + Seq, + Collection, + Map, + OrderedMap, + List, + Stack, + Set, + OrderedSet, + Record, + Range, + Repeat, + is, + fromJS + } + ); + })(); + }, + 56698(s) { + 'function' == typeof Object.create + ? (s.exports = function inherits(s, o) { + o && + ((s.super_ = o), + (s.prototype = Object.create(o.prototype, { + constructor: { value: s, enumerable: !1, writable: !0, configurable: !0 } + }))); + }) + : (s.exports = function inherits(s, o) { + if (o) { + s.super_ = o; + var TempCtor = function () {}; + ((TempCtor.prototype = o.prototype), + (s.prototype = new TempCtor()), + (s.prototype.constructor = s)); + } + }); + }, + 69600(s) { + 'use strict'; + var o, + i, + a = Function.prototype.toString, + u = 'object' == typeof Reflect && null !== Reflect && Reflect.apply; + if ('function' == typeof u && 'function' == typeof Object.defineProperty) + try { + ((o = Object.defineProperty({}, 'length', { + get: function () { + throw i; + } + })), + (i = {}), + u( + function () { + throw 42; + }, + null, + o + )); + } catch (s) { + s !== i && (u = null); + } + else u = null; + var _ = /^\s*class\b/, + w = function isES6ClassFunction(s) { + try { + var o = a.call(s); + return _.test(o); + } catch (s) { + return !1; + } + }, + x = function tryFunctionToStr(s) { + try { + return !w(s) && (a.call(s), !0); + } catch (s) { + return !1; + } + }, + C = Object.prototype.toString, + j = 'function' == typeof Symbol && !!Symbol.toStringTag, + L = !(0 in [,]), + B = function isDocumentDotAll() { + return !1; + }; + if ('object' == typeof document) { + var $ = document.all; + C.call($) === C.call(document.all) && + (B = function isDocumentDotAll(s) { + if ((L || !s) && (void 0 === s || 'object' == typeof s)) + try { + var o = C.call(s); + return ( + ('[object HTMLAllCollection]' === o || + '[object HTML document.all class]' === o || + '[object HTMLCollection]' === o || + '[object Object]' === o) && + null == s('') + ); + } catch (s) {} + return !1; + }); + } + s.exports = u + ? function isCallable(s) { + if (B(s)) return !0; + if (!s) return !1; + if ('function' != typeof s && 'object' != typeof s) return !1; + try { + u(s, null, o); + } catch (s) { + if (s !== i) return !1; + } + return !w(s) && x(s); + } + : function isCallable(s) { + if (B(s)) return !0; + if (!s) return !1; + if ('function' != typeof s && 'object' != typeof s) return !1; + if (j) return x(s); + if (w(s)) return !1; + var o = C.call(s); + return ( + !( + '[object Function]' !== o && + '[object GeneratorFunction]' !== o && + !/^\[object HTML/.test(o) + ) && x(s) + ); + }; + }, + 35680(s, o, i) { + 'use strict'; + var a = i(25767); + s.exports = function isTypedArray(s) { + return !!a(s); + }; + }, + 64634(s) { + var o = {}.toString; + s.exports = + Array.isArray || + function (s) { + return '[object Array]' == o.call(s); + }; + }, + 5419(s) { + s.exports = function (s, o, i, a) { + var u = new Blob(void 0 !== a ? [a, s] : [s], { + type: i || 'application/octet-stream' + }); + if (void 0 !== window.navigator.msSaveBlob) window.navigator.msSaveBlob(u, o); + else { + var _ = + window.URL && window.URL.createObjectURL + ? window.URL.createObjectURL(u) + : window.webkitURL.createObjectURL(u), + w = document.createElement('a'); + ((w.style.display = 'none'), + (w.href = _), + w.setAttribute('download', o), + void 0 === w.download && w.setAttribute('target', '_blank'), + document.body.appendChild(w), + w.click(), + setTimeout(function () { + (document.body.removeChild(w), window.URL.revokeObjectURL(_)); + }, 200)); + } + }; + }, + 20181(s, o, i) { + var a = /^\s+|\s+$/g, + u = /^[-+]0x[0-9a-f]+$/i, + _ = /^0b[01]+$/i, + w = /^0o[0-7]+$/i, + x = parseInt, + C = 'object' == typeof i.g && i.g && i.g.Object === Object && i.g, + j = 'object' == typeof self && self && self.Object === Object && self, + L = C || j || Function('return this')(), + B = Object.prototype.toString, + $ = Math.max, + U = Math.min, + now = function () { + return L.Date.now(); + }; + function isObject(s) { + var o = typeof s; + return !!s && ('object' == o || 'function' == o); + } + function toNumber(s) { + if ('number' == typeof s) return s; + if ( + (function isSymbol(s) { + return ( + 'symbol' == typeof s || + ((function isObjectLike(s) { + return !!s && 'object' == typeof s; + })(s) && + '[object Symbol]' == B.call(s)) + ); + })(s) + ) + return NaN; + if (isObject(s)) { + var o = 'function' == typeof s.valueOf ? s.valueOf() : s; + s = isObject(o) ? o + '' : o; + } + if ('string' != typeof s) return 0 === s ? s : +s; + s = s.replace(a, ''); + var i = _.test(s); + return i || w.test(s) ? x(s.slice(2), i ? 2 : 8) : u.test(s) ? NaN : +s; + } + s.exports = function debounce(s, o, i) { + var a, + u, + _, + w, + x, + C, + j = 0, + L = !1, + B = !1, + V = !0; + if ('function' != typeof s) throw new TypeError('Expected a function'); + function invokeFunc(o) { + var i = a, + _ = u; + return ((a = u = void 0), (j = o), (w = s.apply(_, i))); + } + function shouldInvoke(s) { + var i = s - C; + return void 0 === C || i >= o || i < 0 || (B && s - j >= _); + } + function timerExpired() { + var s = now(); + if (shouldInvoke(s)) return trailingEdge(s); + x = setTimeout( + timerExpired, + (function remainingWait(s) { + var i = o - (s - C); + return B ? U(i, _ - (s - j)) : i; + })(s) + ); + } + function trailingEdge(s) { + return ((x = void 0), V && a ? invokeFunc(s) : ((a = u = void 0), w)); + } + function debounced() { + var s = now(), + i = shouldInvoke(s); + if (((a = arguments), (u = this), (C = s), i)) { + if (void 0 === x) + return (function leadingEdge(s) { + return ((j = s), (x = setTimeout(timerExpired, o)), L ? invokeFunc(s) : w); + })(C); + if (B) return ((x = setTimeout(timerExpired, o)), invokeFunc(C)); + } + return (void 0 === x && (x = setTimeout(timerExpired, o)), w); + } + return ( + (o = toNumber(o) || 0), + isObject(i) && + ((L = !!i.leading), + (_ = (B = 'maxWait' in i) ? $(toNumber(i.maxWait) || 0, o) : _), + (V = 'trailing' in i ? !!i.trailing : V)), + (debounced.cancel = function cancel() { + (void 0 !== x && clearTimeout(x), (j = 0), (a = C = u = x = void 0)); + }), + (debounced.flush = function flush() { + return void 0 === x ? w : trailingEdge(now()); + }), + debounced + ); + }; + }, + 55580(s, o, i) { + var a = i(56110)(i(9325), 'DataView'); + s.exports = a; + }, + 21549(s, o, i) { + var a = i(22032), + u = i(63862), + _ = i(66721), + w = i(12749), + x = i(35749); + function Hash(s) { + var o = -1, + i = null == s ? 0 : s.length; + for (this.clear(); ++o < i; ) { + var a = s[o]; + this.set(a[0], a[1]); + } + } + ((Hash.prototype.clear = a), + (Hash.prototype.delete = u), + (Hash.prototype.get = _), + (Hash.prototype.has = w), + (Hash.prototype.set = x), + (s.exports = Hash)); + }, + 30980(s, o, i) { + var a = i(39344), + u = i(94033); + function LazyWrapper(s) { + ((this.__wrapped__ = s), + (this.__actions__ = []), + (this.__dir__ = 1), + (this.__filtered__ = !1), + (this.__iteratees__ = []), + (this.__takeCount__ = 4294967295), + (this.__views__ = [])); + } + ((LazyWrapper.prototype = a(u.prototype)), + (LazyWrapper.prototype.constructor = LazyWrapper), + (s.exports = LazyWrapper)); + }, + 80079(s, o, i) { + var a = i(63702), + u = i(70080), + _ = i(24739), + w = i(48655), + x = i(31175); + function ListCache(s) { + var o = -1, + i = null == s ? 0 : s.length; + for (this.clear(); ++o < i; ) { + var a = s[o]; + this.set(a[0], a[1]); + } + } + ((ListCache.prototype.clear = a), + (ListCache.prototype.delete = u), + (ListCache.prototype.get = _), + (ListCache.prototype.has = w), + (ListCache.prototype.set = x), + (s.exports = ListCache)); + }, + 56017(s, o, i) { + var a = i(39344), + u = i(94033); + function LodashWrapper(s, o) { + ((this.__wrapped__ = s), + (this.__actions__ = []), + (this.__chain__ = !!o), + (this.__index__ = 0), + (this.__values__ = void 0)); + } + ((LodashWrapper.prototype = a(u.prototype)), + (LodashWrapper.prototype.constructor = LodashWrapper), + (s.exports = LodashWrapper)); + }, + 68223(s, o, i) { + var a = i(56110)(i(9325), 'Map'); + s.exports = a; + }, + 53661(s, o, i) { + var a = i(63040), + u = i(17670), + _ = i(90289), + w = i(4509), + x = i(72949); + function MapCache(s) { + var o = -1, + i = null == s ? 0 : s.length; + for (this.clear(); ++o < i; ) { + var a = s[o]; + this.set(a[0], a[1]); + } + } + ((MapCache.prototype.clear = a), + (MapCache.prototype.delete = u), + (MapCache.prototype.get = _), + (MapCache.prototype.has = w), + (MapCache.prototype.set = x), + (s.exports = MapCache)); + }, + 32804(s, o, i) { + var a = i(56110)(i(9325), 'Promise'); + s.exports = a; + }, + 76545(s, o, i) { + var a = i(56110)(i(9325), 'Set'); + s.exports = a; + }, + 38859(s, o, i) { + var a = i(53661), + u = i(31380), + _ = i(51459); + function SetCache(s) { + var o = -1, + i = null == s ? 0 : s.length; + for (this.__data__ = new a(); ++o < i; ) this.add(s[o]); + } + ((SetCache.prototype.add = SetCache.prototype.push = u), + (SetCache.prototype.has = _), + (s.exports = SetCache)); + }, + 37217(s, o, i) { + var a = i(80079), + u = i(51420), + _ = i(90938), + w = i(63605), + x = i(29817), + C = i(80945); + function Stack(s) { + var o = (this.__data__ = new a(s)); + this.size = o.size; + } + ((Stack.prototype.clear = u), + (Stack.prototype.delete = _), + (Stack.prototype.get = w), + (Stack.prototype.has = x), + (Stack.prototype.set = C), + (s.exports = Stack)); + }, + 51873(s, o, i) { + var a = i(9325).Symbol; + s.exports = a; + }, + 37828(s, o, i) { + var a = i(9325).Uint8Array; + s.exports = a; + }, + 28303(s, o, i) { + var a = i(56110)(i(9325), 'WeakMap'); + s.exports = a; + }, + 91033(s) { + s.exports = function apply(s, o, i) { + switch (i.length) { + case 0: + return s.call(o); + case 1: + return s.call(o, i[0]); + case 2: + return s.call(o, i[0], i[1]); + case 3: + return s.call(o, i[0], i[1], i[2]); + } + return s.apply(o, i); + }; + }, + 83729(s) { + s.exports = function arrayEach(s, o) { + for (var i = -1, a = null == s ? 0 : s.length; ++i < a && !1 !== o(s[i], i, s); ); + return s; + }; + }, + 79770(s) { + s.exports = function arrayFilter(s, o) { + for (var i = -1, a = null == s ? 0 : s.length, u = 0, _ = []; ++i < a; ) { + var w = s[i]; + o(w, i, s) && (_[u++] = w); + } + return _; + }; + }, + 15325(s, o, i) { + var a = i(96131); + s.exports = function arrayIncludes(s, o) { + return !!(null == s ? 0 : s.length) && a(s, o, 0) > -1; + }; + }, + 70695(s, o, i) { + var a = i(78096), + u = i(72428), + _ = i(56449), + w = i(3656), + x = i(30361), + C = i(37167), + j = Object.prototype.hasOwnProperty; + s.exports = function arrayLikeKeys(s, o) { + var i = _(s), + L = !i && u(s), + B = !i && !L && w(s), + $ = !i && !L && !B && C(s), + U = i || L || B || $, + V = U ? a(s.length, String) : [], + z = V.length; + for (var Y in s) + (!o && !j.call(s, Y)) || + (U && + ('length' == Y || + (B && ('offset' == Y || 'parent' == Y)) || + ($ && ('buffer' == Y || 'byteLength' == Y || 'byteOffset' == Y)) || + x(Y, z))) || + V.push(Y); + return V; + }; + }, + 34932(s) { + s.exports = function arrayMap(s, o) { + for (var i = -1, a = null == s ? 0 : s.length, u = Array(a); ++i < a; ) + u[i] = o(s[i], i, s); + return u; + }; + }, + 14528(s) { + s.exports = function arrayPush(s, o) { + for (var i = -1, a = o.length, u = s.length; ++i < a; ) s[u + i] = o[i]; + return s; + }; + }, + 40882(s) { + s.exports = function arrayReduce(s, o, i, a) { + var u = -1, + _ = null == s ? 0 : s.length; + for (a && _ && (i = s[++u]); ++u < _; ) i = o(i, s[u], u, s); + return i; + }; + }, + 14248(s) { + s.exports = function arraySome(s, o) { + for (var i = -1, a = null == s ? 0 : s.length; ++i < a; ) if (o(s[i], i, s)) return !0; + return !1; + }; + }, + 61074(s) { + s.exports = function asciiToArray(s) { + return s.split(''); + }; + }, + 1733(s) { + var o = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + s.exports = function asciiWords(s) { + return s.match(o) || []; + }; + }, + 87805(s, o, i) { + var a = i(43360), + u = i(75288); + s.exports = function assignMergeValue(s, o, i) { + ((void 0 !== i && !u(s[o], i)) || (void 0 === i && !(o in s))) && a(s, o, i); + }; + }, + 16547(s, o, i) { + var a = i(43360), + u = i(75288), + _ = Object.prototype.hasOwnProperty; + s.exports = function assignValue(s, o, i) { + var w = s[o]; + (_.call(s, o) && u(w, i) && (void 0 !== i || o in s)) || a(s, o, i); + }; + }, + 26025(s, o, i) { + var a = i(75288); + s.exports = function assocIndexOf(s, o) { + for (var i = s.length; i--; ) if (a(s[i][0], o)) return i; + return -1; + }; + }, + 74733(s, o, i) { + var a = i(21791), + u = i(95950); + s.exports = function baseAssign(s, o) { + return s && a(o, u(o), s); + }; + }, + 43838(s, o, i) { + var a = i(21791), + u = i(37241); + s.exports = function baseAssignIn(s, o) { + return s && a(o, u(o), s); + }; + }, + 43360(s, o, i) { + var a = i(93243); + s.exports = function baseAssignValue(s, o, i) { + '__proto__' == o && a + ? a(s, o, { configurable: !0, enumerable: !0, value: i, writable: !0 }) + : (s[o] = i); + }; + }, + 9999(s, o, i) { + var a = i(37217), + u = i(83729), + _ = i(16547), + w = i(74733), + x = i(43838), + C = i(93290), + j = i(23007), + L = i(92271), + B = i(48948), + $ = i(50002), + U = i(83349), + V = i(5861), + z = i(76189), + Y = i(77199), + Z = i(35529), + ee = i(56449), + ie = i(3656), + ae = i(87730), + ce = i(23805), + le = i(38440), + pe = i(95950), + de = i(37241), + fe = '[object Arguments]', + ye = '[object Function]', + be = '[object Object]', + Se = {}; + ((Se[fe] = + Se['[object Array]'] = + Se['[object ArrayBuffer]'] = + Se['[object DataView]'] = + Se['[object Boolean]'] = + Se['[object Date]'] = + Se['[object Float32Array]'] = + Se['[object Float64Array]'] = + Se['[object Int8Array]'] = + Se['[object Int16Array]'] = + Se['[object Int32Array]'] = + Se['[object Map]'] = + Se['[object Number]'] = + Se[be] = + Se['[object RegExp]'] = + Se['[object Set]'] = + Se['[object String]'] = + Se['[object Symbol]'] = + Se['[object Uint8Array]'] = + Se['[object Uint8ClampedArray]'] = + Se['[object Uint16Array]'] = + Se['[object Uint32Array]'] = + !0), + (Se['[object Error]'] = Se[ye] = Se['[object WeakMap]'] = !1), + (s.exports = function baseClone(s, o, i, _e, we, xe) { + var Pe, + Te = 1 & o, + Re = 2 & o, + $e = 4 & o; + if ((i && (Pe = we ? i(s, _e, we, xe) : i(s)), void 0 !== Pe)) return Pe; + if (!ce(s)) return s; + var qe = ee(s); + if (qe) { + if (((Pe = z(s)), !Te)) return j(s, Pe); + } else { + var ze = V(s), + We = ze == ye || '[object GeneratorFunction]' == ze; + if (ie(s)) return C(s, Te); + if (ze == be || ze == fe || (We && !we)) { + if (((Pe = Re || We ? {} : Z(s)), !Te)) + return Re ? B(s, x(Pe, s)) : L(s, w(Pe, s)); + } else { + if (!Se[ze]) return we ? s : {}; + Pe = Y(s, ze, Te); + } + } + xe || (xe = new a()); + var He = xe.get(s); + if (He) return He; + (xe.set(s, Pe), + le(s) + ? s.forEach(function (a) { + Pe.add(baseClone(a, o, i, a, s, xe)); + }) + : ae(s) && + s.forEach(function (a, u) { + Pe.set(u, baseClone(a, o, i, u, s, xe)); + })); + var Ye = qe ? void 0 : ($e ? (Re ? U : $) : Re ? de : pe)(s); + return ( + u(Ye || s, function (a, u) { + (Ye && (a = s[(u = a)]), _(Pe, u, baseClone(a, o, i, u, s, xe))); + }), + Pe + ); + })); + }, + 39344(s, o, i) { + var a = i(23805), + u = Object.create, + _ = (function () { + function object() {} + return function (s) { + if (!a(s)) return {}; + if (u) return u(s); + object.prototype = s; + var o = new object(); + return ((object.prototype = void 0), o); + }; + })(); + s.exports = _; + }, + 80909(s, o, i) { + var a = i(30641), + u = i(38329)(a); + s.exports = u; + }, + 2523(s) { + s.exports = function baseFindIndex(s, o, i, a) { + for (var u = s.length, _ = i + (a ? 1 : -1); a ? _-- : ++_ < u; ) + if (o(s[_], _, s)) return _; + return -1; + }; + }, + 83120(s, o, i) { + var a = i(14528), + u = i(45891); + s.exports = function baseFlatten(s, o, i, _, w) { + var x = -1, + C = s.length; + for (i || (i = u), w || (w = []); ++x < C; ) { + var j = s[x]; + o > 0 && i(j) + ? o > 1 + ? baseFlatten(j, o - 1, i, _, w) + : a(w, j) + : _ || (w[w.length] = j); + } + return w; + }; + }, + 86649(s, o, i) { + var a = i(83221)(); + s.exports = a; + }, + 30641(s, o, i) { + var a = i(86649), + u = i(95950); + s.exports = function baseForOwn(s, o) { + return s && a(s, o, u); + }; + }, + 47422(s, o, i) { + var a = i(31769), + u = i(77797); + s.exports = function baseGet(s, o) { + for (var i = 0, _ = (o = a(o, s)).length; null != s && i < _; ) s = s[u(o[i++])]; + return i && i == _ ? s : void 0; + }; + }, + 82199(s, o, i) { + var a = i(14528), + u = i(56449); + s.exports = function baseGetAllKeys(s, o, i) { + var _ = o(s); + return u(s) ? _ : a(_, i(s)); + }; + }, + 72552(s, o, i) { + var a = i(51873), + u = i(659), + _ = i(59350), + w = a ? a.toStringTag : void 0; + s.exports = function baseGetTag(s) { + return null == s + ? void 0 === s + ? '[object Undefined]' + : '[object Null]' + : w && w in Object(s) + ? u(s) + : _(s); + }; + }, + 20426(s) { + var o = Object.prototype.hasOwnProperty; + s.exports = function baseHas(s, i) { + return null != s && o.call(s, i); + }; + }, + 28077(s) { + s.exports = function baseHasIn(s, o) { + return null != s && o in Object(s); + }; + }, + 96131(s, o, i) { + var a = i(2523), + u = i(85463), + _ = i(76959); + s.exports = function baseIndexOf(s, o, i) { + return o == o ? _(s, o, i) : a(s, u, i); + }; + }, + 27534(s, o, i) { + var a = i(72552), + u = i(40346); + s.exports = function baseIsArguments(s) { + return u(s) && '[object Arguments]' == a(s); + }; + }, + 60270(s, o, i) { + var a = i(87068), + u = i(40346); + s.exports = function baseIsEqual(s, o, i, _, w) { + return ( + s === o || + (null == s || null == o || (!u(s) && !u(o)) + ? s != s && o != o + : a(s, o, i, _, baseIsEqual, w)) + ); + }; + }, + 87068(s, o, i) { + var a = i(37217), + u = i(25911), + _ = i(21986), + w = i(50689), + x = i(5861), + C = i(56449), + j = i(3656), + L = i(37167), + B = '[object Arguments]', + $ = '[object Array]', + U = '[object Object]', + V = Object.prototype.hasOwnProperty; + s.exports = function baseIsEqualDeep(s, o, i, z, Y, Z) { + var ee = C(s), + ie = C(o), + ae = ee ? $ : x(s), + ce = ie ? $ : x(o), + le = (ae = ae == B ? U : ae) == U, + pe = (ce = ce == B ? U : ce) == U, + de = ae == ce; + if (de && j(s)) { + if (!j(o)) return !1; + ((ee = !0), (le = !1)); + } + if (de && !le) + return ( + Z || (Z = new a()), + ee || L(s) ? u(s, o, i, z, Y, Z) : _(s, o, ae, i, z, Y, Z) + ); + if (!(1 & i)) { + var fe = le && V.call(s, '__wrapped__'), + ye = pe && V.call(o, '__wrapped__'); + if (fe || ye) { + var be = fe ? s.value() : s, + Se = ye ? o.value() : o; + return (Z || (Z = new a()), Y(be, Se, i, z, Z)); + } + } + return !!de && (Z || (Z = new a()), w(s, o, i, z, Y, Z)); + }; + }, + 29172(s, o, i) { + var a = i(5861), + u = i(40346); + s.exports = function baseIsMap(s) { + return u(s) && '[object Map]' == a(s); + }; + }, + 41799(s, o, i) { + var a = i(37217), + u = i(60270); + s.exports = function baseIsMatch(s, o, i, _) { + var w = i.length, + x = w, + C = !_; + if (null == s) return !x; + for (s = Object(s); w--; ) { + var j = i[w]; + if (C && j[2] ? j[1] !== s[j[0]] : !(j[0] in s)) return !1; + } + for (; ++w < x; ) { + var L = (j = i[w])[0], + B = s[L], + $ = j[1]; + if (C && j[2]) { + if (void 0 === B && !(L in s)) return !1; + } else { + var U = new a(); + if (_) var V = _(B, $, L, s, o, U); + if (!(void 0 === V ? u($, B, 3, _, U) : V)) return !1; + } + } + return !0; + }; + }, + 85463(s) { + s.exports = function baseIsNaN(s) { + return s != s; + }; + }, + 45083(s, o, i) { + var a = i(1882), + u = i(87296), + _ = i(23805), + w = i(47473), + x = /^\[object .+?Constructor\]$/, + C = Function.prototype, + j = Object.prototype, + L = C.toString, + B = j.hasOwnProperty, + $ = RegExp( + '^' + + L.call(B) + .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + + '$' + ); + s.exports = function baseIsNative(s) { + return !(!_(s) || u(s)) && (a(s) ? $ : x).test(w(s)); + }; + }, + 16038(s, o, i) { + var a = i(5861), + u = i(40346); + s.exports = function baseIsSet(s) { + return u(s) && '[object Set]' == a(s); + }; + }, + 4901(s, o, i) { + var a = i(72552), + u = i(30294), + _ = i(40346), + w = {}; + ((w['[object Float32Array]'] = + w['[object Float64Array]'] = + w['[object Int8Array]'] = + w['[object Int16Array]'] = + w['[object Int32Array]'] = + w['[object Uint8Array]'] = + w['[object Uint8ClampedArray]'] = + w['[object Uint16Array]'] = + w['[object Uint32Array]'] = + !0), + (w['[object Arguments]'] = + w['[object Array]'] = + w['[object ArrayBuffer]'] = + w['[object Boolean]'] = + w['[object DataView]'] = + w['[object Date]'] = + w['[object Error]'] = + w['[object Function]'] = + w['[object Map]'] = + w['[object Number]'] = + w['[object Object]'] = + w['[object RegExp]'] = + w['[object Set]'] = + w['[object String]'] = + w['[object WeakMap]'] = + !1), + (s.exports = function baseIsTypedArray(s) { + return _(s) && u(s.length) && !!w[a(s)]; + })); + }, + 15389(s, o, i) { + var a = i(93663), + u = i(87978), + _ = i(83488), + w = i(56449), + x = i(50583); + s.exports = function baseIteratee(s) { + return 'function' == typeof s + ? s + : null == s + ? _ + : 'object' == typeof s + ? w(s) + ? u(s[0], s[1]) + : a(s) + : x(s); + }; + }, + 88984(s, o, i) { + var a = i(55527), + u = i(3650), + _ = Object.prototype.hasOwnProperty; + s.exports = function baseKeys(s) { + if (!a(s)) return u(s); + var o = []; + for (var i in Object(s)) _.call(s, i) && 'constructor' != i && o.push(i); + return o; + }; + }, + 72903(s, o, i) { + var a = i(23805), + u = i(55527), + _ = i(90181), + w = Object.prototype.hasOwnProperty; + s.exports = function baseKeysIn(s) { + if (!a(s)) return _(s); + var o = u(s), + i = []; + for (var x in s) ('constructor' != x || (!o && w.call(s, x))) && i.push(x); + return i; + }; + }, + 94033(s) { + s.exports = function baseLodash() {}; + }, + 93663(s, o, i) { + var a = i(41799), + u = i(10776), + _ = i(67197); + s.exports = function baseMatches(s) { + var o = u(s); + return 1 == o.length && o[0][2] + ? _(o[0][0], o[0][1]) + : function (i) { + return i === s || a(i, s, o); + }; + }; + }, + 87978(s, o, i) { + var a = i(60270), + u = i(58156), + _ = i(80631), + w = i(28586), + x = i(30756), + C = i(67197), + j = i(77797); + s.exports = function baseMatchesProperty(s, o) { + return w(s) && x(o) + ? C(j(s), o) + : function (i) { + var w = u(i, s); + return void 0 === w && w === o ? _(i, s) : a(o, w, 3); + }; + }; + }, + 85250(s, o, i) { + var a = i(37217), + u = i(87805), + _ = i(86649), + w = i(42824), + x = i(23805), + C = i(37241), + j = i(14974); + s.exports = function baseMerge(s, o, i, L, B) { + s !== o && + _( + o, + function (_, C) { + if ((B || (B = new a()), x(_))) w(s, o, C, i, baseMerge, L, B); + else { + var $ = L ? L(j(s, C), _, C + '', s, o, B) : void 0; + (void 0 === $ && ($ = _), u(s, C, $)); + } + }, + C + ); + }; + }, + 42824(s, o, i) { + var a = i(87805), + u = i(93290), + _ = i(71961), + w = i(23007), + x = i(35529), + C = i(72428), + j = i(56449), + L = i(83693), + B = i(3656), + $ = i(1882), + U = i(23805), + V = i(11331), + z = i(37167), + Y = i(14974), + Z = i(69884); + s.exports = function baseMergeDeep(s, o, i, ee, ie, ae, ce) { + var le = Y(s, i), + pe = Y(o, i), + de = ce.get(pe); + if (de) a(s, i, de); + else { + var fe = ae ? ae(le, pe, i + '', s, o, ce) : void 0, + ye = void 0 === fe; + if (ye) { + var be = j(pe), + Se = !be && B(pe), + _e = !be && !Se && z(pe); + ((fe = pe), + be || Se || _e + ? j(le) + ? (fe = le) + : L(le) + ? (fe = w(le)) + : Se + ? ((ye = !1), (fe = u(pe, !0))) + : _e + ? ((ye = !1), (fe = _(pe, !0))) + : (fe = []) + : V(pe) || C(pe) + ? ((fe = le), C(le) ? (fe = Z(le)) : (U(le) && !$(le)) || (fe = x(pe))) + : (ye = !1)); + } + (ye && (ce.set(pe, fe), ie(fe, pe, ee, ae, ce), ce.delete(pe)), a(s, i, fe)); + } + }; + }, + 47237(s) { + s.exports = function baseProperty(s) { + return function (o) { + return null == o ? void 0 : o[s]; + }; + }; + }, + 17255(s, o, i) { + var a = i(47422); + s.exports = function basePropertyDeep(s) { + return function (o) { + return a(o, s); + }; + }; + }, + 54552(s) { + s.exports = function basePropertyOf(s) { + return function (o) { + return null == s ? void 0 : s[o]; + }; + }; + }, + 85558(s) { + s.exports = function baseReduce(s, o, i, a, u) { + return ( + u(s, function (s, u, _) { + i = a ? ((a = !1), s) : o(i, s, u, _); + }), + i + ); + }; + }, + 69302(s, o, i) { + var a = i(83488), + u = i(56757), + _ = i(32865); + s.exports = function baseRest(s, o) { + return _(u(s, o, a), s + ''); + }; + }, + 73170(s, o, i) { + var a = i(16547), + u = i(31769), + _ = i(30361), + w = i(23805), + x = i(77797); + s.exports = function baseSet(s, o, i, C) { + if (!w(s)) return s; + for (var j = -1, L = (o = u(o, s)).length, B = L - 1, $ = s; null != $ && ++j < L; ) { + var U = x(o[j]), + V = i; + if ('__proto__' === U || 'constructor' === U || 'prototype' === U) return s; + if (j != B) { + var z = $[U]; + void 0 === (V = C ? C(z, U, $) : void 0) && (V = w(z) ? z : _(o[j + 1]) ? [] : {}); + } + (a($, U, V), ($ = $[U])); + } + return s; + }; + }, + 68882(s, o, i) { + var a = i(83488), + u = i(48152), + _ = u + ? function (s, o) { + return (u.set(s, o), s); + } + : a; + s.exports = _; + }, + 19570(s, o, i) { + var a = i(37334), + u = i(93243), + _ = i(83488), + w = u + ? function (s, o) { + return u(s, 'toString', { + configurable: !0, + enumerable: !1, + value: a(o), + writable: !0 + }); + } + : _; + s.exports = w; + }, + 25160(s) { + s.exports = function baseSlice(s, o, i) { + var a = -1, + u = s.length; + (o < 0 && (o = -o > u ? 0 : u + o), + (i = i > u ? u : i) < 0 && (i += u), + (u = o > i ? 0 : (i - o) >>> 0), + (o >>>= 0)); + for (var _ = Array(u); ++a < u; ) _[a] = s[a + o]; + return _; + }; + }, + 90916(s, o, i) { + var a = i(80909); + s.exports = function baseSome(s, o) { + var i; + return ( + a(s, function (s, a, u) { + return !(i = o(s, a, u)); + }), + !!i + ); + }; + }, + 78096(s) { + s.exports = function baseTimes(s, o) { + for (var i = -1, a = Array(s); ++i < s; ) a[i] = o(i); + return a; + }; + }, + 77556(s, o, i) { + var a = i(51873), + u = i(34932), + _ = i(56449), + w = i(44394), + x = a ? a.prototype : void 0, + C = x ? x.toString : void 0; + s.exports = function baseToString(s) { + if ('string' == typeof s) return s; + if (_(s)) return u(s, baseToString) + ''; + if (w(s)) return C ? C.call(s) : ''; + var o = s + ''; + return '0' == o && 1 / s == -1 / 0 ? '-0' : o; + }; + }, + 54128(s, o, i) { + var a = i(31800), + u = /^\s+/; + s.exports = function baseTrim(s) { + return s ? s.slice(0, a(s) + 1).replace(u, '') : s; + }; + }, + 27301(s) { + s.exports = function baseUnary(s) { + return function (o) { + return s(o); + }; + }; + }, + 19931(s, o, i) { + var a = i(31769), + u = i(68090), + _ = i(68969), + w = i(77797), + x = Object.prototype.hasOwnProperty; + s.exports = function baseUnset(s, o) { + var i = -1, + C = (o = a(o, s)).length; + if (!C) return !0; + for (; ++i < C; ) { + var j = w(o[i]); + if ('__proto__' === j && !x.call(s, '__proto__')) return !1; + if (('constructor' === j || 'prototype' === j) && i < C - 1) return !1; + } + var L = _(s, o); + return null == L || delete L[w(u(o))]; + }; + }, + 51234(s) { + s.exports = function baseZipObject(s, o, i) { + for (var a = -1, u = s.length, _ = o.length, w = {}; ++a < u; ) { + var x = a < _ ? o[a] : void 0; + i(w, s[a], x); + } + return w; + }; + }, + 19219(s) { + s.exports = function cacheHas(s, o) { + return s.has(o); + }; + }, + 31769(s, o, i) { + var a = i(56449), + u = i(28586), + _ = i(61802), + w = i(13222); + s.exports = function castPath(s, o) { + return a(s) ? s : u(s, o) ? [s] : _(w(s)); + }; + }, + 28754(s, o, i) { + var a = i(25160); + s.exports = function castSlice(s, o, i) { + var u = s.length; + return ((i = void 0 === i ? u : i), !o && i >= u ? s : a(s, o, i)); + }; + }, + 49653(s, o, i) { + var a = i(37828); + s.exports = function cloneArrayBuffer(s) { + var o = new s.constructor(s.byteLength); + return (new a(o).set(new a(s)), o); + }; + }, + 93290(s, o, i) { + s = i.nmd(s); + var a = i(9325), + u = o && !o.nodeType && o, + _ = u && s && !s.nodeType && s, + w = _ && _.exports === u ? a.Buffer : void 0, + x = w ? w.allocUnsafe : void 0; + s.exports = function cloneBuffer(s, o) { + if (o) return s.slice(); + var i = s.length, + a = x ? x(i) : new s.constructor(i); + return (s.copy(a), a); + }; + }, + 76169(s, o, i) { + var a = i(49653); + s.exports = function cloneDataView(s, o) { + var i = o ? a(s.buffer) : s.buffer; + return new s.constructor(i, s.byteOffset, s.byteLength); + }; + }, + 73201(s) { + var o = /\w*$/; + s.exports = function cloneRegExp(s) { + var i = new s.constructor(s.source, o.exec(s)); + return ((i.lastIndex = s.lastIndex), i); + }; + }, + 93736(s, o, i) { + var a = i(51873), + u = a ? a.prototype : void 0, + _ = u ? u.valueOf : void 0; + s.exports = function cloneSymbol(s) { + return _ ? Object(_.call(s)) : {}; + }; + }, + 71961(s, o, i) { + var a = i(49653); + s.exports = function cloneTypedArray(s, o) { + var i = o ? a(s.buffer) : s.buffer; + return new s.constructor(i, s.byteOffset, s.length); + }; + }, + 91596(s) { + var o = Math.max; + s.exports = function composeArgs(s, i, a, u) { + for ( + var _ = -1, + w = s.length, + x = a.length, + C = -1, + j = i.length, + L = o(w - x, 0), + B = Array(j + L), + $ = !u; + ++C < j; + ) + B[C] = i[C]; + for (; ++_ < x; ) ($ || _ < w) && (B[a[_]] = s[_]); + for (; L--; ) B[C++] = s[_++]; + return B; + }; + }, + 53320(s) { + var o = Math.max; + s.exports = function composeArgsRight(s, i, a, u) { + for ( + var _ = -1, + w = s.length, + x = -1, + C = a.length, + j = -1, + L = i.length, + B = o(w - C, 0), + $ = Array(B + L), + U = !u; + ++_ < B; + ) + $[_] = s[_]; + for (var V = _; ++j < L; ) $[V + j] = i[j]; + for (; ++x < C; ) (U || _ < w) && ($[V + a[x]] = s[_++]); + return $; + }; + }, + 23007(s) { + s.exports = function copyArray(s, o) { + var i = -1, + a = s.length; + for (o || (o = Array(a)); ++i < a; ) o[i] = s[i]; + return o; + }; + }, + 21791(s, o, i) { + var a = i(16547), + u = i(43360); + s.exports = function copyObject(s, o, i, _) { + var w = !i; + i || (i = {}); + for (var x = -1, C = o.length; ++x < C; ) { + var j = o[x], + L = _ ? _(i[j], s[j], j, i, s) : void 0; + (void 0 === L && (L = s[j]), w ? u(i, j, L) : a(i, j, L)); + } + return i; + }; + }, + 92271(s, o, i) { + var a = i(21791), + u = i(4664); + s.exports = function copySymbols(s, o) { + return a(s, u(s), o); + }; + }, + 48948(s, o, i) { + var a = i(21791), + u = i(86375); + s.exports = function copySymbolsIn(s, o) { + return a(s, u(s), o); + }; + }, + 55481(s, o, i) { + var a = i(9325)['__core-js_shared__']; + s.exports = a; + }, + 58523(s) { + s.exports = function countHolders(s, o) { + for (var i = s.length, a = 0; i--; ) s[i] === o && ++a; + return a; + }; + }, + 20999(s, o, i) { + var a = i(69302), + u = i(36800); + s.exports = function createAssigner(s) { + return a(function (o, i) { + var a = -1, + _ = i.length, + w = _ > 1 ? i[_ - 1] : void 0, + x = _ > 2 ? i[2] : void 0; + for ( + w = s.length > 3 && 'function' == typeof w ? (_--, w) : void 0, + x && u(i[0], i[1], x) && ((w = _ < 3 ? void 0 : w), (_ = 1)), + o = Object(o); + ++a < _; + ) { + var C = i[a]; + C && s(o, C, a, w); + } + return o; + }); + }; + }, + 38329(s, o, i) { + var a = i(64894); + s.exports = function createBaseEach(s, o) { + return function (i, u) { + if (null == i) return i; + if (!a(i)) return s(i, u); + for ( + var _ = i.length, w = o ? _ : -1, x = Object(i); + (o ? w-- : ++w < _) && !1 !== u(x[w], w, x); + ); + return i; + }; + }; + }, + 83221(s) { + s.exports = function createBaseFor(s) { + return function (o, i, a) { + for (var u = -1, _ = Object(o), w = a(o), x = w.length; x--; ) { + var C = w[s ? x : ++u]; + if (!1 === i(_[C], C, _)) break; + } + return o; + }; + }; + }, + 11842(s, o, i) { + var a = i(82819), + u = i(9325); + s.exports = function createBind(s, o, i) { + var _ = 1 & o, + w = a(s); + return function wrapper() { + return (this && this !== u && this instanceof wrapper ? w : s).apply( + _ ? i : this, + arguments + ); + }; + }; + }, + 12507(s, o, i) { + var a = i(28754), + u = i(49698), + _ = i(63912), + w = i(13222); + s.exports = function createCaseFirst(s) { + return function (o) { + o = w(o); + var i = u(o) ? _(o) : void 0, + x = i ? i[0] : o.charAt(0), + C = i ? a(i, 1).join('') : o.slice(1); + return x[s]() + C; + }; + }; + }, + 45539(s, o, i) { + var a = i(40882), + u = i(50828), + _ = i(66645), + w = RegExp("['’]", 'g'); + s.exports = function createCompounder(s) { + return function (o) { + return a(_(u(o).replace(w, '')), s, ''); + }; + }; + }, + 82819(s, o, i) { + var a = i(39344), + u = i(23805); + s.exports = function createCtor(s) { + return function () { + var o = arguments; + switch (o.length) { + case 0: + return new s(); + case 1: + return new s(o[0]); + case 2: + return new s(o[0], o[1]); + case 3: + return new s(o[0], o[1], o[2]); + case 4: + return new s(o[0], o[1], o[2], o[3]); + case 5: + return new s(o[0], o[1], o[2], o[3], o[4]); + case 6: + return new s(o[0], o[1], o[2], o[3], o[4], o[5]); + case 7: + return new s(o[0], o[1], o[2], o[3], o[4], o[5], o[6]); + } + var i = a(s.prototype), + _ = s.apply(i, o); + return u(_) ? _ : i; + }; + }; + }, + 77078(s, o, i) { + var a = i(91033), + u = i(82819), + _ = i(37471), + w = i(18073), + x = i(11287), + C = i(36306), + j = i(9325); + s.exports = function createCurry(s, o, i) { + var L = u(s); + return function wrapper() { + for (var u = arguments.length, B = Array(u), $ = u, U = x(wrapper); $--; ) + B[$] = arguments[$]; + var V = u < 3 && B[0] !== U && B[u - 1] !== U ? [] : C(B, U); + return (u -= V.length) < i + ? w(s, o, _, wrapper.placeholder, void 0, B, V, void 0, void 0, i - u) + : a(this && this !== j && this instanceof wrapper ? L : s, this, B); + }; + }; + }, + 62006(s, o, i) { + var a = i(15389), + u = i(64894), + _ = i(95950); + s.exports = function createFind(s) { + return function (o, i, w) { + var x = Object(o); + if (!u(o)) { + var C = a(i, 3); + ((o = _(o)), + (i = function (s) { + return C(x[s], s, x); + })); + } + var j = s(o, i, w); + return j > -1 ? x[C ? o[j] : j] : void 0; + }; + }; + }, + 37471(s, o, i) { + var a = i(91596), + u = i(53320), + _ = i(58523), + w = i(82819), + x = i(18073), + C = i(11287), + j = i(68294), + L = i(36306), + B = i(9325); + s.exports = function createHybrid(s, o, i, $, U, V, z, Y, Z, ee) { + var ie = 128 & o, + ae = 1 & o, + ce = 2 & o, + le = 24 & o, + pe = 512 & o, + de = ce ? void 0 : w(s); + return function wrapper() { + for (var fe = arguments.length, ye = Array(fe), be = fe; be--; ) + ye[be] = arguments[be]; + if (le) + var Se = C(wrapper), + _e = _(ye, Se); + if ( + ($ && (ye = a(ye, $, U, le)), + V && (ye = u(ye, V, z, le)), + (fe -= _e), + le && fe < ee) + ) { + var we = L(ye, Se); + return x(s, o, createHybrid, wrapper.placeholder, i, ye, we, Y, Z, ee - fe); + } + var xe = ae ? i : this, + Pe = ce ? xe[s] : s; + return ( + (fe = ye.length), + Y ? (ye = j(ye, Y)) : pe && fe > 1 && ye.reverse(), + ie && Z < fe && (ye.length = Z), + this && this !== B && this instanceof wrapper && (Pe = de || w(Pe)), + Pe.apply(xe, ye) + ); + }; + }; + }, + 24168(s, o, i) { + var a = i(91033), + u = i(82819), + _ = i(9325); + s.exports = function createPartial(s, o, i, w) { + var x = 1 & o, + C = u(s); + return function wrapper() { + for ( + var o = -1, + u = arguments.length, + j = -1, + L = w.length, + B = Array(L + u), + $ = this && this !== _ && this instanceof wrapper ? C : s; + ++j < L; + ) + B[j] = w[j]; + for (; u--; ) B[j++] = arguments[++o]; + return a($, x ? i : this, B); + }; + }; + }, + 18073(s, o, i) { + var a = i(85087), + u = i(54641), + _ = i(70981); + s.exports = function createRecurry(s, o, i, w, x, C, j, L, B, $) { + var U = 8 & o; + ((o |= U ? 32 : 64), 4 & (o &= ~(U ? 64 : 32)) || (o &= -4)); + var V = [ + s, + o, + x, + U ? C : void 0, + U ? j : void 0, + U ? void 0 : C, + U ? void 0 : j, + L, + B, + $ + ], + z = i.apply(void 0, V); + return (a(s) && u(z, V), (z.placeholder = w), _(z, s, o)); + }; + }, + 66977(s, o, i) { + var a = i(68882), + u = i(11842), + _ = i(77078), + w = i(37471), + x = i(24168), + C = i(37381), + j = i(3209), + L = i(54641), + B = i(70981), + $ = i(61489), + U = Math.max; + s.exports = function createWrap(s, o, i, V, z, Y, Z, ee) { + var ie = 2 & o; + if (!ie && 'function' != typeof s) throw new TypeError('Expected a function'); + var ae = V ? V.length : 0; + if ( + (ae || ((o &= -97), (V = z = void 0)), + (Z = void 0 === Z ? Z : U($(Z), 0)), + (ee = void 0 === ee ? ee : $(ee)), + (ae -= z ? z.length : 0), + 64 & o) + ) { + var ce = V, + le = z; + V = z = void 0; + } + var pe = ie ? void 0 : C(s), + de = [s, o, i, V, z, ce, le, Y, Z, ee]; + if ( + (pe && j(de, pe), + (s = de[0]), + (o = de[1]), + (i = de[2]), + (V = de[3]), + (z = de[4]), + !(ee = de[9] = void 0 === de[9] ? (ie ? 0 : s.length) : U(de[9] - ae, 0)) && + 24 & o && + (o &= -25), + o && 1 != o) + ) + fe = + 8 == o || 16 == o + ? _(s, o, ee) + : (32 != o && 33 != o) || z.length + ? w.apply(void 0, de) + : x(s, o, i, V); + else var fe = u(s, o, i); + return B((pe ? a : L)(fe, de), s, o); + }; + }, + 53138(s, o, i) { + var a = i(11331); + s.exports = function customOmitClone(s) { + return a(s) ? void 0 : s; + }; + }, + 24647(s, o, i) { + var a = i(54552)({ + À: 'A', + Á: 'A', + Â: 'A', + Ã: 'A', + Ä: 'A', + Å: 'A', + à: 'a', + á: 'a', + â: 'a', + ã: 'a', + ä: 'a', + å: 'a', + Ç: 'C', + ç: 'c', + Ð: 'D', + ð: 'd', + È: 'E', + É: 'E', + Ê: 'E', + Ë: 'E', + è: 'e', + é: 'e', + ê: 'e', + ë: 'e', + Ì: 'I', + Í: 'I', + Î: 'I', + Ï: 'I', + ì: 'i', + í: 'i', + î: 'i', + ï: 'i', + Ñ: 'N', + ñ: 'n', + Ò: 'O', + Ó: 'O', + Ô: 'O', + Õ: 'O', + Ö: 'O', + Ø: 'O', + ò: 'o', + ó: 'o', + ô: 'o', + õ: 'o', + ö: 'o', + ø: 'o', + Ù: 'U', + Ú: 'U', + Û: 'U', + Ü: 'U', + ù: 'u', + ú: 'u', + û: 'u', + ü: 'u', + Ý: 'Y', + ý: 'y', + ÿ: 'y', + Æ: 'Ae', + æ: 'ae', + Þ: 'Th', + þ: 'th', + ß: 'ss', + Ā: 'A', + Ă: 'A', + Ą: 'A', + ā: 'a', + ă: 'a', + ą: 'a', + Ć: 'C', + Ĉ: 'C', + Ċ: 'C', + Č: 'C', + ć: 'c', + ĉ: 'c', + ċ: 'c', + č: 'c', + Ď: 'D', + Đ: 'D', + ď: 'd', + đ: 'd', + Ē: 'E', + Ĕ: 'E', + Ė: 'E', + Ę: 'E', + Ě: 'E', + ē: 'e', + ĕ: 'e', + ė: 'e', + ę: 'e', + ě: 'e', + Ĝ: 'G', + Ğ: 'G', + Ġ: 'G', + Ģ: 'G', + ĝ: 'g', + ğ: 'g', + ġ: 'g', + ģ: 'g', + Ĥ: 'H', + Ħ: 'H', + ĥ: 'h', + ħ: 'h', + Ĩ: 'I', + Ī: 'I', + Ĭ: 'I', + Į: 'I', + İ: 'I', + ĩ: 'i', + ī: 'i', + ĭ: 'i', + į: 'i', + ı: 'i', + Ĵ: 'J', + ĵ: 'j', + Ķ: 'K', + ķ: 'k', + ĸ: 'k', + Ĺ: 'L', + Ļ: 'L', + Ľ: 'L', + Ŀ: 'L', + Ł: 'L', + ĺ: 'l', + ļ: 'l', + ľ: 'l', + ŀ: 'l', + ł: 'l', + Ń: 'N', + Ņ: 'N', + Ň: 'N', + Ŋ: 'N', + ń: 'n', + ņ: 'n', + ň: 'n', + ŋ: 'n', + Ō: 'O', + Ŏ: 'O', + Ő: 'O', + ō: 'o', + ŏ: 'o', + ő: 'o', + Ŕ: 'R', + Ŗ: 'R', + Ř: 'R', + ŕ: 'r', + ŗ: 'r', + ř: 'r', + Ś: 'S', + Ŝ: 'S', + Ş: 'S', + Š: 'S', + ś: 's', + ŝ: 's', + ş: 's', + š: 's', + Ţ: 'T', + Ť: 'T', + Ŧ: 'T', + ţ: 't', + ť: 't', + ŧ: 't', + Ũ: 'U', + Ū: 'U', + Ŭ: 'U', + Ů: 'U', + Ű: 'U', + Ų: 'U', + ũ: 'u', + ū: 'u', + ŭ: 'u', + ů: 'u', + ű: 'u', + ų: 'u', + Ŵ: 'W', + ŵ: 'w', + Ŷ: 'Y', + ŷ: 'y', + Ÿ: 'Y', + Ź: 'Z', + Ż: 'Z', + Ž: 'Z', + ź: 'z', + ż: 'z', + ž: 'z', + IJ: 'IJ', + ij: 'ij', + Œ: 'Oe', + œ: 'oe', + ʼn: "'n", + ſ: 's' + }); + s.exports = a; + }, + 93243(s, o, i) { + var a = i(56110), + u = (function () { + try { + var s = a(Object, 'defineProperty'); + return (s({}, '', {}), s); + } catch (s) {} + })(); + s.exports = u; + }, + 25911(s, o, i) { + var a = i(38859), + u = i(14248), + _ = i(19219); + s.exports = function equalArrays(s, o, i, w, x, C) { + var j = 1 & i, + L = s.length, + B = o.length; + if (L != B && !(j && B > L)) return !1; + var $ = C.get(s), + U = C.get(o); + if ($ && U) return $ == o && U == s; + var V = -1, + z = !0, + Y = 2 & i ? new a() : void 0; + for (C.set(s, o), C.set(o, s); ++V < L; ) { + var Z = s[V], + ee = o[V]; + if (w) var ie = j ? w(ee, Z, V, o, s, C) : w(Z, ee, V, s, o, C); + if (void 0 !== ie) { + if (ie) continue; + z = !1; + break; + } + if (Y) { + if ( + !u(o, function (s, o) { + if (!_(Y, o) && (Z === s || x(Z, s, i, w, C))) return Y.push(o); + }) + ) { + z = !1; + break; + } + } else if (Z !== ee && !x(Z, ee, i, w, C)) { + z = !1; + break; + } + } + return (C.delete(s), C.delete(o), z); + }; + }, + 21986(s, o, i) { + var a = i(51873), + u = i(37828), + _ = i(75288), + w = i(25911), + x = i(20317), + C = i(84247), + j = a ? a.prototype : void 0, + L = j ? j.valueOf : void 0; + s.exports = function equalByTag(s, o, i, a, j, B, $) { + switch (i) { + case '[object DataView]': + if (s.byteLength != o.byteLength || s.byteOffset != o.byteOffset) return !1; + ((s = s.buffer), (o = o.buffer)); + case '[object ArrayBuffer]': + return !(s.byteLength != o.byteLength || !B(new u(s), new u(o))); + case '[object Boolean]': + case '[object Date]': + case '[object Number]': + return _(+s, +o); + case '[object Error]': + return s.name == o.name && s.message == o.message; + case '[object RegExp]': + case '[object String]': + return s == o + ''; + case '[object Map]': + var U = x; + case '[object Set]': + var V = 1 & a; + if ((U || (U = C), s.size != o.size && !V)) return !1; + var z = $.get(s); + if (z) return z == o; + ((a |= 2), $.set(s, o)); + var Y = w(U(s), U(o), a, j, B, $); + return ($.delete(s), Y); + case '[object Symbol]': + if (L) return L.call(s) == L.call(o); + } + return !1; + }; + }, + 50689(s, o, i) { + var a = i(50002), + u = Object.prototype.hasOwnProperty; + s.exports = function equalObjects(s, o, i, _, w, x) { + var C = 1 & i, + j = a(s), + L = j.length; + if (L != a(o).length && !C) return !1; + for (var B = L; B--; ) { + var $ = j[B]; + if (!(C ? $ in o : u.call(o, $))) return !1; + } + var U = x.get(s), + V = x.get(o); + if (U && V) return U == o && V == s; + var z = !0; + (x.set(s, o), x.set(o, s)); + for (var Y = C; ++B < L; ) { + var Z = s[($ = j[B])], + ee = o[$]; + if (_) var ie = C ? _(ee, Z, $, o, s, x) : _(Z, ee, $, s, o, x); + if (!(void 0 === ie ? Z === ee || w(Z, ee, i, _, x) : ie)) { + z = !1; + break; + } + Y || (Y = 'constructor' == $); + } + if (z && !Y) { + var ae = s.constructor, + ce = o.constructor; + ae == ce || + !('constructor' in s) || + !('constructor' in o) || + ('function' == typeof ae && + ae instanceof ae && + 'function' == typeof ce && + ce instanceof ce) || + (z = !1); + } + return (x.delete(s), x.delete(o), z); + }; + }, + 38816(s, o, i) { + var a = i(35970), + u = i(56757), + _ = i(32865); + s.exports = function flatRest(s) { + return _(u(s, void 0, a), s + ''); + }; + }, + 34840(s, o, i) { + var a = 'object' == typeof i.g && i.g && i.g.Object === Object && i.g; + s.exports = a; + }, + 50002(s, o, i) { + var a = i(82199), + u = i(4664), + _ = i(95950); + s.exports = function getAllKeys(s) { + return a(s, _, u); + }; + }, + 83349(s, o, i) { + var a = i(82199), + u = i(86375), + _ = i(37241); + s.exports = function getAllKeysIn(s) { + return a(s, _, u); + }; + }, + 37381(s, o, i) { + var a = i(48152), + u = i(63950), + _ = a + ? function (s) { + return a.get(s); + } + : u; + s.exports = _; + }, + 62284(s, o, i) { + var a = i(84629), + u = Object.prototype.hasOwnProperty; + s.exports = function getFuncName(s) { + for (var o = s.name + '', i = a[o], _ = u.call(a, o) ? i.length : 0; _--; ) { + var w = i[_], + x = w.func; + if (null == x || x == s) return w.name; + } + return o; + }; + }, + 11287(s) { + s.exports = function getHolder(s) { + return s.placeholder; + }; + }, + 12651(s, o, i) { + var a = i(74218); + s.exports = function getMapData(s, o) { + var i = s.__data__; + return a(o) ? i['string' == typeof o ? 'string' : 'hash'] : i.map; + }; + }, + 10776(s, o, i) { + var a = i(30756), + u = i(95950); + s.exports = function getMatchData(s) { + for (var o = u(s), i = o.length; i--; ) { + var _ = o[i], + w = s[_]; + o[i] = [_, w, a(w)]; + } + return o; + }; + }, + 56110(s, o, i) { + var a = i(45083), + u = i(10392); + s.exports = function getNative(s, o) { + var i = u(s, o); + return a(i) ? i : void 0; + }; + }, + 28879(s, o, i) { + var a = i(74335)(Object.getPrototypeOf, Object); + s.exports = a; + }, + 659(s, o, i) { + var a = i(51873), + u = Object.prototype, + _ = u.hasOwnProperty, + w = u.toString, + x = a ? a.toStringTag : void 0; + s.exports = function getRawTag(s) { + var o = _.call(s, x), + i = s[x]; + try { + s[x] = void 0; + var a = !0; + } catch (s) {} + var u = w.call(s); + return (a && (o ? (s[x] = i) : delete s[x]), u); + }; + }, + 4664(s, o, i) { + var a = i(79770), + u = i(63345), + _ = Object.prototype.propertyIsEnumerable, + w = Object.getOwnPropertySymbols, + x = w + ? function (s) { + return null == s + ? [] + : ((s = Object(s)), + a(w(s), function (o) { + return _.call(s, o); + })); + } + : u; + s.exports = x; + }, + 86375(s, o, i) { + var a = i(14528), + u = i(28879), + _ = i(4664), + w = i(63345), + x = Object.getOwnPropertySymbols + ? function (s) { + for (var o = []; s; ) (a(o, _(s)), (s = u(s))); + return o; + } + : w; + s.exports = x; + }, + 5861(s, o, i) { + var a = i(55580), + u = i(68223), + _ = i(32804), + w = i(76545), + x = i(28303), + C = i(72552), + j = i(47473), + L = '[object Map]', + B = '[object Promise]', + $ = '[object Set]', + U = '[object WeakMap]', + V = '[object DataView]', + z = j(a), + Y = j(u), + Z = j(_), + ee = j(w), + ie = j(x), + ae = C; + (((a && ae(new a(new ArrayBuffer(1))) != V) || + (u && ae(new u()) != L) || + (_ && ae(_.resolve()) != B) || + (w && ae(new w()) != $) || + (x && ae(new x()) != U)) && + (ae = function (s) { + var o = C(s), + i = '[object Object]' == o ? s.constructor : void 0, + a = i ? j(i) : ''; + if (a) + switch (a) { + case z: + return V; + case Y: + return L; + case Z: + return B; + case ee: + return $; + case ie: + return U; + } + return o; + }), + (s.exports = ae)); + }, + 10392(s) { + s.exports = function getValue(s, o) { + return null == s ? void 0 : s[o]; + }; + }, + 75251(s) { + var o = /\{\n\/\* \[wrapped with (.+)\] \*/, + i = /,? & /; + s.exports = function getWrapDetails(s) { + var a = s.match(o); + return a ? a[1].split(i) : []; + }; + }, + 49326(s, o, i) { + var a = i(31769), + u = i(72428), + _ = i(56449), + w = i(30361), + x = i(30294), + C = i(77797); + s.exports = function hasPath(s, o, i) { + for (var j = -1, L = (o = a(o, s)).length, B = !1; ++j < L; ) { + var $ = C(o[j]); + if (!(B = null != s && i(s, $))) break; + s = s[$]; + } + return B || ++j != L + ? B + : !!(L = null == s ? 0 : s.length) && x(L) && w($, L) && (_(s) || u(s)); + }; + }, + 49698(s) { + var o = RegExp( + '[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]' + ); + s.exports = function hasUnicode(s) { + return o.test(s); + }; + }, + 45434(s) { + var o = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + s.exports = function hasUnicodeWord(s) { + return o.test(s); + }; + }, + 22032(s, o, i) { + var a = i(81042); + s.exports = function hashClear() { + ((this.__data__ = a ? a(null) : {}), (this.size = 0)); + }; + }, + 63862(s) { + s.exports = function hashDelete(s) { + var o = this.has(s) && delete this.__data__[s]; + return ((this.size -= o ? 1 : 0), o); + }; + }, + 66721(s, o, i) { + var a = i(81042), + u = Object.prototype.hasOwnProperty; + s.exports = function hashGet(s) { + var o = this.__data__; + if (a) { + var i = o[s]; + return '__lodash_hash_undefined__' === i ? void 0 : i; + } + return u.call(o, s) ? o[s] : void 0; + }; + }, + 12749(s, o, i) { + var a = i(81042), + u = Object.prototype.hasOwnProperty; + s.exports = function hashHas(s) { + var o = this.__data__; + return a ? void 0 !== o[s] : u.call(o, s); + }; + }, + 35749(s, o, i) { + var a = i(81042); + s.exports = function hashSet(s, o) { + var i = this.__data__; + return ( + (this.size += this.has(s) ? 0 : 1), + (i[s] = a && void 0 === o ? '__lodash_hash_undefined__' : o), + this + ); + }; + }, + 76189(s) { + var o = Object.prototype.hasOwnProperty; + s.exports = function initCloneArray(s) { + var i = s.length, + a = new s.constructor(i); + return ( + i && + 'string' == typeof s[0] && + o.call(s, 'index') && + ((a.index = s.index), (a.input = s.input)), + a + ); + }; + }, + 77199(s, o, i) { + var a = i(49653), + u = i(76169), + _ = i(73201), + w = i(93736), + x = i(71961); + s.exports = function initCloneByTag(s, o, i) { + var C = s.constructor; + switch (o) { + case '[object ArrayBuffer]': + return a(s); + case '[object Boolean]': + case '[object Date]': + return new C(+s); + case '[object DataView]': + return u(s, i); + case '[object Float32Array]': + case '[object Float64Array]': + case '[object Int8Array]': + case '[object Int16Array]': + case '[object Int32Array]': + case '[object Uint8Array]': + case '[object Uint8ClampedArray]': + case '[object Uint16Array]': + case '[object Uint32Array]': + return x(s, i); + case '[object Map]': + case '[object Set]': + return new C(); + case '[object Number]': + case '[object String]': + return new C(s); + case '[object RegExp]': + return _(s); + case '[object Symbol]': + return w(s); + } + }; + }, + 35529(s, o, i) { + var a = i(39344), + u = i(28879), + _ = i(55527); + s.exports = function initCloneObject(s) { + return 'function' != typeof s.constructor || _(s) ? {} : a(u(s)); + }; + }, + 62060(s) { + var o = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; + s.exports = function insertWrapDetails(s, i) { + var a = i.length; + if (!a) return s; + var u = a - 1; + return ( + (i[u] = (a > 1 ? '& ' : '') + i[u]), + (i = i.join(a > 2 ? ', ' : ' ')), + s.replace(o, '{\n/* [wrapped with ' + i + '] */\n') + ); + }; + }, + 45891(s, o, i) { + var a = i(51873), + u = i(72428), + _ = i(56449), + w = a ? a.isConcatSpreadable : void 0; + s.exports = function isFlattenable(s) { + return _(s) || u(s) || !!(w && s && s[w]); + }; + }, + 30361(s) { + var o = /^(?:0|[1-9]\d*)$/; + s.exports = function isIndex(s, i) { + var a = typeof s; + return ( + !!(i = null == i ? 9007199254740991 : i) && + ('number' == a || ('symbol' != a && o.test(s))) && + s > -1 && + s % 1 == 0 && + s < i + ); + }; + }, + 36800(s, o, i) { + var a = i(75288), + u = i(64894), + _ = i(30361), + w = i(23805); + s.exports = function isIterateeCall(s, o, i) { + if (!w(i)) return !1; + var x = typeof o; + return ( + !!('number' == x ? u(i) && _(o, i.length) : 'string' == x && o in i) && a(i[o], s) + ); + }; + }, + 28586(s, o, i) { + var a = i(56449), + u = i(44394), + _ = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + w = /^\w*$/; + s.exports = function isKey(s, o) { + if (a(s)) return !1; + var i = typeof s; + return ( + !('number' != i && 'symbol' != i && 'boolean' != i && null != s && !u(s)) || + w.test(s) || + !_.test(s) || + (null != o && s in Object(o)) + ); + }; + }, + 74218(s) { + s.exports = function isKeyable(s) { + var o = typeof s; + return 'string' == o || 'number' == o || 'symbol' == o || 'boolean' == o + ? '__proto__' !== s + : null === s; + }; + }, + 85087(s, o, i) { + var a = i(30980), + u = i(37381), + _ = i(62284), + w = i(53758); + s.exports = function isLaziable(s) { + var o = _(s), + i = w[o]; + if ('function' != typeof i || !(o in a.prototype)) return !1; + if (s === i) return !0; + var x = u(i); + return !!x && s === x[0]; + }; + }, + 87296(s, o, i) { + var a, + u = i(55481), + _ = (a = /[^.]+$/.exec((u && u.keys && u.keys.IE_PROTO) || '')) + ? 'Symbol(src)_1.' + a + : ''; + s.exports = function isMasked(s) { + return !!_ && _ in s; + }; + }, + 55527(s) { + var o = Object.prototype; + s.exports = function isPrototype(s) { + var i = s && s.constructor; + return s === (('function' == typeof i && i.prototype) || o); + }; + }, + 30756(s, o, i) { + var a = i(23805); + s.exports = function isStrictComparable(s) { + return s == s && !a(s); + }; + }, + 63702(s) { + s.exports = function listCacheClear() { + ((this.__data__ = []), (this.size = 0)); + }; + }, + 70080(s, o, i) { + var a = i(26025), + u = Array.prototype.splice; + s.exports = function listCacheDelete(s) { + var o = this.__data__, + i = a(o, s); + return !(i < 0) && (i == o.length - 1 ? o.pop() : u.call(o, i, 1), --this.size, !0); + }; + }, + 24739(s, o, i) { + var a = i(26025); + s.exports = function listCacheGet(s) { + var o = this.__data__, + i = a(o, s); + return i < 0 ? void 0 : o[i][1]; + }; + }, + 48655(s, o, i) { + var a = i(26025); + s.exports = function listCacheHas(s) { + return a(this.__data__, s) > -1; + }; + }, + 31175(s, o, i) { + var a = i(26025); + s.exports = function listCacheSet(s, o) { + var i = this.__data__, + u = a(i, s); + return (u < 0 ? (++this.size, i.push([s, o])) : (i[u][1] = o), this); + }; + }, + 63040(s, o, i) { + var a = i(21549), + u = i(80079), + _ = i(68223); + s.exports = function mapCacheClear() { + ((this.size = 0), + (this.__data__ = { hash: new a(), map: new (_ || u)(), string: new a() })); + }; + }, + 17670(s, o, i) { + var a = i(12651); + s.exports = function mapCacheDelete(s) { + var o = a(this, s).delete(s); + return ((this.size -= o ? 1 : 0), o); + }; + }, + 90289(s, o, i) { + var a = i(12651); + s.exports = function mapCacheGet(s) { + return a(this, s).get(s); + }; + }, + 4509(s, o, i) { + var a = i(12651); + s.exports = function mapCacheHas(s) { + return a(this, s).has(s); + }; + }, + 72949(s, o, i) { + var a = i(12651); + s.exports = function mapCacheSet(s, o) { + var i = a(this, s), + u = i.size; + return (i.set(s, o), (this.size += i.size == u ? 0 : 1), this); + }; + }, + 20317(s) { + s.exports = function mapToArray(s) { + var o = -1, + i = Array(s.size); + return ( + s.forEach(function (s, a) { + i[++o] = [a, s]; + }), + i + ); + }; + }, + 67197(s) { + s.exports = function matchesStrictComparable(s, o) { + return function (i) { + return null != i && i[s] === o && (void 0 !== o || s in Object(i)); + }; + }; + }, + 62224(s, o, i) { + var a = i(50104); + s.exports = function memoizeCapped(s) { + var o = a(s, function (s) { + return (500 === i.size && i.clear(), s); + }), + i = o.cache; + return o; + }; + }, + 3209(s, o, i) { + var a = i(91596), + u = i(53320), + _ = i(36306), + w = '__lodash_placeholder__', + x = 128, + C = Math.min; + s.exports = function mergeData(s, o) { + var i = s[1], + j = o[1], + L = i | j, + B = L < 131, + $ = + (j == x && 8 == i) || + (j == x && 256 == i && s[7].length <= o[8]) || + (384 == j && o[7].length <= o[8] && 8 == i); + if (!B && !$) return s; + 1 & j && ((s[2] = o[2]), (L |= 1 & i ? 0 : 4)); + var U = o[3]; + if (U) { + var V = s[3]; + ((s[3] = V ? a(V, U, o[4]) : U), (s[4] = V ? _(s[3], w) : o[4])); + } + return ( + (U = o[5]) && + ((V = s[5]), (s[5] = V ? u(V, U, o[6]) : U), (s[6] = V ? _(s[5], w) : o[6])), + (U = o[7]) && (s[7] = U), + j & x && (s[8] = null == s[8] ? o[8] : C(s[8], o[8])), + null == s[9] && (s[9] = o[9]), + (s[0] = o[0]), + (s[1] = L), + s + ); + }; + }, + 48152(s, o, i) { + var a = i(28303), + u = a && new a(); + s.exports = u; + }, + 81042(s, o, i) { + var a = i(56110)(Object, 'create'); + s.exports = a; + }, + 3650(s, o, i) { + var a = i(74335)(Object.keys, Object); + s.exports = a; + }, + 90181(s) { + s.exports = function nativeKeysIn(s) { + var o = []; + if (null != s) for (var i in Object(s)) o.push(i); + return o; + }; + }, + 86009(s, o, i) { + s = i.nmd(s); + var a = i(34840), + u = o && !o.nodeType && o, + _ = u && s && !s.nodeType && s, + w = _ && _.exports === u && a.process, + x = (function () { + try { + var s = _ && _.require && _.require('util').types; + return s || (w && w.binding && w.binding('util')); + } catch (s) {} + })(); + s.exports = x; + }, + 59350(s) { + var o = Object.prototype.toString; + s.exports = function objectToString(s) { + return o.call(s); + }; + }, + 74335(s) { + s.exports = function overArg(s, o) { + return function (i) { + return s(o(i)); + }; + }; + }, + 56757(s, o, i) { + var a = i(91033), + u = Math.max; + s.exports = function overRest(s, o, i) { + return ( + (o = u(void 0 === o ? s.length - 1 : o, 0)), + function () { + for (var _ = arguments, w = -1, x = u(_.length - o, 0), C = Array(x); ++w < x; ) + C[w] = _[o + w]; + w = -1; + for (var j = Array(o + 1); ++w < o; ) j[w] = _[w]; + return ((j[o] = i(C)), a(s, this, j)); + } + ); + }; + }, + 68969(s, o, i) { + var a = i(47422), + u = i(25160); + s.exports = function parent(s, o) { + return o.length < 2 ? s : a(s, u(o, 0, -1)); + }; + }, + 84629(s) { + s.exports = {}; + }, + 68294(s, o, i) { + var a = i(23007), + u = i(30361), + _ = Math.min; + s.exports = function reorder(s, o) { + for (var i = s.length, w = _(o.length, i), x = a(s); w--; ) { + var C = o[w]; + s[w] = u(C, i) ? x[C] : void 0; + } + return s; + }; + }, + 36306(s) { + var o = '__lodash_placeholder__'; + s.exports = function replaceHolders(s, i) { + for (var a = -1, u = s.length, _ = 0, w = []; ++a < u; ) { + var x = s[a]; + (x !== i && x !== o) || ((s[a] = o), (w[_++] = a)); + } + return w; + }; + }, + 9325(s, o, i) { + var a = i(34840), + u = 'object' == typeof self && self && self.Object === Object && self, + _ = a || u || Function('return this')(); + s.exports = _; + }, + 14974(s) { + s.exports = function safeGet(s, o) { + if (('constructor' !== o || 'function' != typeof s[o]) && '__proto__' != o) return s[o]; + }; + }, + 31380(s) { + s.exports = function setCacheAdd(s) { + return (this.__data__.set(s, '__lodash_hash_undefined__'), this); + }; + }, + 51459(s) { + s.exports = function setCacheHas(s) { + return this.__data__.has(s); + }; + }, + 54641(s, o, i) { + var a = i(68882), + u = i(51811)(a); + s.exports = u; + }, + 84247(s) { + s.exports = function setToArray(s) { + var o = -1, + i = Array(s.size); + return ( + s.forEach(function (s) { + i[++o] = s; + }), + i + ); + }; + }, + 32865(s, o, i) { + var a = i(19570), + u = i(51811)(a); + s.exports = u; + }, + 70981(s, o, i) { + var a = i(75251), + u = i(62060), + _ = i(32865), + w = i(75948); + s.exports = function setWrapToString(s, o, i) { + var x = o + ''; + return _(s, u(x, w(a(x), i))); + }; + }, + 51811(s) { + var o = Date.now; + s.exports = function shortOut(s) { + var i = 0, + a = 0; + return function () { + var u = o(), + _ = 16 - (u - a); + if (((a = u), _ > 0)) { + if (++i >= 800) return arguments[0]; + } else i = 0; + return s.apply(void 0, arguments); + }; + }; + }, + 51420(s, o, i) { + var a = i(80079); + s.exports = function stackClear() { + ((this.__data__ = new a()), (this.size = 0)); + }; + }, + 90938(s) { + s.exports = function stackDelete(s) { + var o = this.__data__, + i = o.delete(s); + return ((this.size = o.size), i); + }; + }, + 63605(s) { + s.exports = function stackGet(s) { + return this.__data__.get(s); + }; + }, + 29817(s) { + s.exports = function stackHas(s) { + return this.__data__.has(s); + }; + }, + 80945(s, o, i) { + var a = i(80079), + u = i(68223), + _ = i(53661); + s.exports = function stackSet(s, o) { + var i = this.__data__; + if (i instanceof a) { + var w = i.__data__; + if (!u || w.length < 199) return (w.push([s, o]), (this.size = ++i.size), this); + i = this.__data__ = new _(w); + } + return (i.set(s, o), (this.size = i.size), this); + }; + }, + 76959(s) { + s.exports = function strictIndexOf(s, o, i) { + for (var a = i - 1, u = s.length; ++a < u; ) if (s[a] === o) return a; + return -1; + }; + }, + 63912(s, o, i) { + var a = i(61074), + u = i(49698), + _ = i(42054); + s.exports = function stringToArray(s) { + return u(s) ? _(s) : a(s); + }; + }, + 61802(s, o, i) { + var a = i(62224), + u = + /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g, + _ = /\\(\\)?/g, + w = a(function (s) { + var o = []; + return ( + 46 === s.charCodeAt(0) && o.push(''), + s.replace(u, function (s, i, a, u) { + o.push(a ? u.replace(_, '$1') : i || s); + }), + o + ); + }); + s.exports = w; + }, + 77797(s, o, i) { + var a = i(44394); + s.exports = function toKey(s) { + if ('string' == typeof s || a(s)) return s; + var o = s + ''; + return '0' == o && 1 / s == -1 / 0 ? '-0' : o; + }; + }, + 47473(s) { + var o = Function.prototype.toString; + s.exports = function toSource(s) { + if (null != s) { + try { + return o.call(s); + } catch (s) {} + try { + return s + ''; + } catch (s) {} + } + return ''; + }; + }, + 31800(s) { + var o = /\s/; + s.exports = function trimmedEndIndex(s) { + for (var i = s.length; i-- && o.test(s.charAt(i)); ); + return i; + }; + }, + 42054(s) { + var o = '\\ud800-\\udfff', + i = '[' + o + ']', + a = '[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]', + u = '\\ud83c[\\udffb-\\udfff]', + _ = '[^' + o + ']', + w = '(?:\\ud83c[\\udde6-\\uddff]){2}', + x = '[\\ud800-\\udbff][\\udc00-\\udfff]', + C = '(?:' + a + '|' + u + ')' + '?', + j = '[\\ufe0e\\ufe0f]?', + L = j + C + ('(?:\\u200d(?:' + [_, w, x].join('|') + ')' + j + C + ')*'), + B = '(?:' + [_ + a + '?', a, w, x, i].join('|') + ')', + $ = RegExp(u + '(?=' + u + ')|' + B + L, 'g'); + s.exports = function unicodeToArray(s) { + return s.match($) || []; + }; + }, + 22225(s) { + var o = '\\ud800-\\udfff', + i = '\\u2700-\\u27bf', + a = 'a-z\\xdf-\\xf6\\xf8-\\xff', + u = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + _ = + '\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + w = '[' + _ + ']', + x = '\\d+', + C = '[' + i + ']', + j = '[' + a + ']', + L = '[^' + o + _ + x + i + a + u + ']', + B = '(?:\\ud83c[\\udde6-\\uddff]){2}', + $ = '[\\ud800-\\udbff][\\udc00-\\udfff]', + U = '[' + u + ']', + V = '(?:' + j + '|' + L + ')', + z = '(?:' + U + '|' + L + ')', + Y = "(?:['’](?:d|ll|m|re|s|t|ve))?", + Z = "(?:['’](?:D|LL|M|RE|S|T|VE))?", + ee = '(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?', + ie = '[\\ufe0e\\ufe0f]?', + ae = + ie + ee + ('(?:\\u200d(?:' + ['[^' + o + ']', B, $].join('|') + ')' + ie + ee + ')*'), + ce = '(?:' + [C, B, $].join('|') + ')' + ae, + le = RegExp( + [ + U + '?' + j + '+' + Y + '(?=' + [w, U, '$'].join('|') + ')', + z + '+' + Z + '(?=' + [w, U + V, '$'].join('|') + ')', + U + '?' + V + '+' + Y, + U + '+' + Z, + '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + x, + ce + ].join('|'), + 'g' + ); + s.exports = function unicodeWords(s) { + return s.match(le) || []; + }; + }, + 75948(s, o, i) { + var a = i(83729), + u = i(15325), + _ = [ + ['ary', 128], + ['bind', 1], + ['bindKey', 2], + ['curry', 8], + ['curryRight', 16], + ['flip', 512], + ['partial', 32], + ['partialRight', 64], + ['rearg', 256] + ]; + s.exports = function updateWrapDetails(s, o) { + return ( + a(_, function (i) { + var a = '_.' + i[0]; + o & i[1] && !u(s, a) && s.push(a); + }), + s.sort() + ); + }; + }, + 80257(s, o, i) { + var a = i(30980), + u = i(56017), + _ = i(23007); + s.exports = function wrapperClone(s) { + if (s instanceof a) return s.clone(); + var o = new u(s.__wrapped__, s.__chain__); + return ( + (o.__actions__ = _(s.__actions__)), + (o.__index__ = s.__index__), + (o.__values__ = s.__values__), + o + ); + }; + }, + 64626(s, o, i) { + var a = i(66977); + s.exports = function ary(s, o, i) { + return ( + (o = i ? void 0 : o), + (o = s && null == o ? s.length : o), + a(s, 128, void 0, void 0, void 0, void 0, o) + ); + }; + }, + 84058(s, o, i) { + var a = i(14792), + u = i(45539)(function (s, o, i) { + return ((o = o.toLowerCase()), s + (i ? a(o) : o)); + }); + s.exports = u; + }, + 14792(s, o, i) { + var a = i(13222), + u = i(55808); + s.exports = function capitalize(s) { + return u(a(s).toLowerCase()); + }; + }, + 32629(s, o, i) { + var a = i(9999); + s.exports = function clone(s) { + return a(s, 4); + }; + }, + 37334(s) { + s.exports = function constant(s) { + return function () { + return s; + }; + }; + }, + 49747(s, o, i) { + var a = i(66977); + function curry(s, o, i) { + var u = a(s, 8, void 0, void 0, void 0, void 0, void 0, (o = i ? void 0 : o)); + return ((u.placeholder = curry.placeholder), u); + } + ((curry.placeholder = {}), (s.exports = curry)); + }, + 38221(s, o, i) { + var a = i(23805), + u = i(10124), + _ = i(99374), + w = Math.max, + x = Math.min; + s.exports = function debounce(s, o, i) { + var C, + j, + L, + B, + $, + U, + V = 0, + z = !1, + Y = !1, + Z = !0; + if ('function' != typeof s) throw new TypeError('Expected a function'); + function invokeFunc(o) { + var i = C, + a = j; + return ((C = j = void 0), (V = o), (B = s.apply(a, i))); + } + function shouldInvoke(s) { + var i = s - U; + return void 0 === U || i >= o || i < 0 || (Y && s - V >= L); + } + function timerExpired() { + var s = u(); + if (shouldInvoke(s)) return trailingEdge(s); + $ = setTimeout( + timerExpired, + (function remainingWait(s) { + var i = o - (s - U); + return Y ? x(i, L - (s - V)) : i; + })(s) + ); + } + function trailingEdge(s) { + return (($ = void 0), Z && C ? invokeFunc(s) : ((C = j = void 0), B)); + } + function debounced() { + var s = u(), + i = shouldInvoke(s); + if (((C = arguments), (j = this), (U = s), i)) { + if (void 0 === $) + return (function leadingEdge(s) { + return ((V = s), ($ = setTimeout(timerExpired, o)), z ? invokeFunc(s) : B); + })(U); + if (Y) return (clearTimeout($), ($ = setTimeout(timerExpired, o)), invokeFunc(U)); + } + return (void 0 === $ && ($ = setTimeout(timerExpired, o)), B); + } + return ( + (o = _(o) || 0), + a(i) && + ((z = !!i.leading), + (L = (Y = 'maxWait' in i) ? w(_(i.maxWait) || 0, o) : L), + (Z = 'trailing' in i ? !!i.trailing : Z)), + (debounced.cancel = function cancel() { + (void 0 !== $ && clearTimeout($), (V = 0), (C = U = j = $ = void 0)); + }), + (debounced.flush = function flush() { + return void 0 === $ ? B : trailingEdge(u()); + }), + debounced + ); + }; + }, + 50828(s, o, i) { + var a = i(24647), + u = i(13222), + _ = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g, + w = RegExp('[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]', 'g'); + s.exports = function deburr(s) { + return (s = u(s)) && s.replace(_, a).replace(w, ''); + }; + }, + 75288(s) { + s.exports = function eq(s, o) { + return s === o || (s != s && o != o); + }; + }, + 60680(s, o, i) { + var a = i(13222), + u = /[\\^$.*+?()[\]{}|]/g, + _ = RegExp(u.source); + s.exports = function escapeRegExp(s) { + return (s = a(s)) && _.test(s) ? s.replace(u, '\\$&') : s; + }; + }, + 7309(s, o, i) { + var a = i(62006)(i(24713)); + s.exports = a; + }, + 24713(s, o, i) { + var a = i(2523), + u = i(15389), + _ = i(61489), + w = Math.max; + s.exports = function findIndex(s, o, i) { + var x = null == s ? 0 : s.length; + if (!x) return -1; + var C = null == i ? 0 : _(i); + return (C < 0 && (C = w(x + C, 0)), a(s, u(o, 3), C)); + }; + }, + 35970(s, o, i) { + var a = i(83120); + s.exports = function flatten(s) { + return (null == s ? 0 : s.length) ? a(s, 1) : []; + }; + }, + 73424(s, o, i) { + var a = i(16962), + u = i(2874), + _ = Array.prototype.push; + function baseAry(s, o) { + return 2 == o + ? function (o, i) { + return s(o, i); + } + : function (o) { + return s(o); + }; + } + function cloneArray(s) { + for (var o = s ? s.length : 0, i = Array(o); o--; ) i[o] = s[o]; + return i; + } + function wrapImmutable(s, o) { + return function () { + var i = arguments.length; + if (i) { + for (var a = Array(i); i--; ) a[i] = arguments[i]; + var u = (a[0] = o.apply(void 0, a)); + return (s.apply(void 0, a), u); + } + }; + } + s.exports = function baseConvert(s, o, i, w) { + var x = 'function' == typeof o, + C = o === Object(o); + if ((C && ((w = i), (i = o), (o = void 0)), null == i)) throw new TypeError(); + w || (w = {}); + var j = !('cap' in w) || w.cap, + L = !('curry' in w) || w.curry, + B = !('fixed' in w) || w.fixed, + $ = !('immutable' in w) || w.immutable, + U = !('rearg' in w) || w.rearg, + V = x ? i : u, + z = 'curry' in w && w.curry, + Y = 'fixed' in w && w.fixed, + Z = 'rearg' in w && w.rearg, + ee = x ? i.runInContext() : void 0, + ie = x + ? i + : { + ary: s.ary, + assign: s.assign, + clone: s.clone, + curry: s.curry, + forEach: s.forEach, + isArray: s.isArray, + isError: s.isError, + isFunction: s.isFunction, + isWeakMap: s.isWeakMap, + iteratee: s.iteratee, + keys: s.keys, + rearg: s.rearg, + toInteger: s.toInteger, + toPath: s.toPath + }, + ae = ie.ary, + ce = ie.assign, + le = ie.clone, + pe = ie.curry, + de = ie.forEach, + fe = ie.isArray, + ye = ie.isError, + be = ie.isFunction, + Se = ie.isWeakMap, + _e = ie.keys, + we = ie.rearg, + xe = ie.toInteger, + Pe = ie.toPath, + Te = _e(a.aryMethod), + Re = { + castArray: function (s) { + return function () { + var o = arguments[0]; + return fe(o) ? s(cloneArray(o)) : s.apply(void 0, arguments); + }; + }, + iteratee: function (s) { + return function () { + var o = arguments[1], + i = s(arguments[0], o), + a = i.length; + return j && 'number' == typeof o + ? ((o = o > 2 ? o - 2 : 1), a && a <= o ? i : baseAry(i, o)) + : i; + }; + }, + mixin: function (s) { + return function (o) { + var i = this; + if (!be(i)) return s(i, Object(o)); + var a = []; + return ( + de(_e(o), function (s) { + be(o[s]) && a.push([s, i.prototype[s]]); + }), + s(i, Object(o)), + de(a, function (s) { + var o = s[1]; + be(o) ? (i.prototype[s[0]] = o) : delete i.prototype[s[0]]; + }), + i + ); + }; + }, + nthArg: function (s) { + return function (o) { + var i = o < 0 ? 1 : xe(o) + 1; + return pe(s(o), i); + }; + }, + rearg: function (s) { + return function (o, i) { + var a = i ? i.length : 0; + return pe(s(o, i), a); + }; + }, + runInContext: function (o) { + return function (i) { + return baseConvert(s, o(i), w); + }; + } + }; + function castCap(s, o) { + if (j) { + var i = a.iterateeRearg[s]; + if (i) + return (function iterateeRearg(s, o) { + return overArg(s, function (s) { + var i = o.length; + return (function baseArity(s, o) { + return 2 == o + ? function (o, i) { + return s.apply(void 0, arguments); + } + : function (o) { + return s.apply(void 0, arguments); + }; + })(we(baseAry(s, i), o), i); + }); + })(o, i); + var u = !x && a.iterateeAry[s]; + if (u) + return (function iterateeAry(s, o) { + return overArg(s, function (s) { + return 'function' == typeof s ? baseAry(s, o) : s; + }); + })(o, u); + } + return o; + } + function castFixed(s, o, i) { + if (B && (Y || !a.skipFixed[s])) { + var u = a.methodSpread[s], + w = u && u.start; + return void 0 === w + ? ae(o, i) + : (function flatSpread(s, o) { + return function () { + for (var i = arguments.length, a = i - 1, u = Array(i); i--; ) + u[i] = arguments[i]; + var w = u[o], + x = u.slice(0, o); + return ( + w && _.apply(x, w), + o != a && _.apply(x, u.slice(o + 1)), + s.apply(this, x) + ); + }; + })(o, w); + } + return o; + } + function castRearg(s, o, i) { + return U && i > 1 && (Z || !a.skipRearg[s]) + ? we(o, a.methodRearg[s] || a.aryRearg[i]) + : o; + } + function cloneByPath(s, o) { + for ( + var i = -1, a = (o = Pe(o)).length, u = a - 1, _ = le(Object(s)), w = _; + null != w && ++i < a; + ) { + var x = o[i], + C = w[x]; + (null == C || be(C) || ye(C) || Se(C) || (w[x] = le(i == u ? C : Object(C))), + (w = w[x])); + } + return _; + } + function createConverter(s, o) { + var i = a.aliasToReal[s] || s, + u = a.remap[i] || i, + _ = w; + return function (s) { + var a = x ? ee : ie, + w = x ? ee[u] : o, + C = ce(ce({}, _), s); + return baseConvert(a, i, w, C); + }; + } + function overArg(s, o) { + return function () { + var i = arguments.length; + if (!i) return s(); + for (var a = Array(i); i--; ) a[i] = arguments[i]; + var u = U ? 0 : i - 1; + return ((a[u] = o(a[u])), s.apply(void 0, a)); + }; + } + function wrap(s, o, i) { + var u, + _ = a.aliasToReal[s] || s, + w = o, + x = Re[_]; + return ( + x + ? (w = x(o)) + : $ && + (a.mutate.array[_] + ? (w = wrapImmutable(o, cloneArray)) + : a.mutate.object[_] + ? (w = wrapImmutable( + o, + (function createCloner(s) { + return function (o) { + return s({}, o); + }; + })(o) + )) + : a.mutate.set[_] && (w = wrapImmutable(o, cloneByPath))), + de(Te, function (s) { + return ( + de(a.aryMethod[s], function (o) { + if (_ == o) { + var i = a.methodSpread[_], + x = i && i.afterRearg; + return ( + (u = x + ? castFixed(_, castRearg(_, w, s), s) + : castRearg(_, castFixed(_, w, s), s)), + (u = (function castCurry(s, o, i) { + return z || (L && i > 1) ? pe(o, i) : o; + })(0, (u = castCap(_, u)), s)), + !1 + ); + } + }), + !u + ); + }), + u || (u = w), + u == o && + (u = z + ? pe(u, 1) + : function () { + return o.apply(this, arguments); + }), + (u.convert = createConverter(_, o)), + (u.placeholder = o.placeholder = i), + u + ); + } + if (!C) return wrap(o, i, V); + var $e = i, + qe = []; + return ( + de(Te, function (s) { + de(a.aryMethod[s], function (s) { + var o = $e[a.remap[s] || s]; + o && qe.push([s, wrap(s, o, $e)]); + }); + }), + de(_e($e), function (s) { + var o = $e[s]; + if ('function' == typeof o) { + for (var i = qe.length; i--; ) if (qe[i][0] == s) return; + ((o.convert = createConverter(s, o)), qe.push([s, o])); + } + }), + de(qe, function (s) { + $e[s[0]] = s[1]; + }), + ($e.convert = function convertLib(s) { + return $e.runInContext.convert(s)(void 0); + }), + ($e.placeholder = $e), + de(_e($e), function (s) { + de(a.realToAlias[s] || [], function (o) { + $e[o] = $e[s]; + }); + }), + $e + ); + }; + }, + 16962(s, o) { + ((o.aliasToReal = { + each: 'forEach', + eachRight: 'forEachRight', + entries: 'toPairs', + entriesIn: 'toPairsIn', + extend: 'assignIn', + extendAll: 'assignInAll', + extendAllWith: 'assignInAllWith', + extendWith: 'assignInWith', + first: 'head', + conforms: 'conformsTo', + matches: 'isMatch', + property: 'get', + __: 'placeholder', + F: 'stubFalse', + T: 'stubTrue', + all: 'every', + allPass: 'overEvery', + always: 'constant', + any: 'some', + anyPass: 'overSome', + apply: 'spread', + assoc: 'set', + assocPath: 'set', + complement: 'negate', + compose: 'flowRight', + contains: 'includes', + dissoc: 'unset', + dissocPath: 'unset', + dropLast: 'dropRight', + dropLastWhile: 'dropRightWhile', + equals: 'isEqual', + identical: 'eq', + indexBy: 'keyBy', + init: 'initial', + invertObj: 'invert', + juxt: 'over', + omitAll: 'omit', + nAry: 'ary', + path: 'get', + pathEq: 'matchesProperty', + pathOr: 'getOr', + paths: 'at', + pickAll: 'pick', + pipe: 'flow', + pluck: 'map', + prop: 'get', + propEq: 'matchesProperty', + propOr: 'getOr', + props: 'at', + symmetricDifference: 'xor', + symmetricDifferenceBy: 'xorBy', + symmetricDifferenceWith: 'xorWith', + takeLast: 'takeRight', + takeLastWhile: 'takeRightWhile', + unapply: 'rest', + unnest: 'flatten', + useWith: 'overArgs', + where: 'conformsTo', + whereEq: 'isMatch', + zipObj: 'zipObject' + }), + (o.aryMethod = { + 1: [ + 'assignAll', + 'assignInAll', + 'attempt', + 'castArray', + 'ceil', + 'create', + 'curry', + 'curryRight', + 'defaultsAll', + 'defaultsDeepAll', + 'floor', + 'flow', + 'flowRight', + 'fromPairs', + 'invert', + 'iteratee', + 'memoize', + 'method', + 'mergeAll', + 'methodOf', + 'mixin', + 'nthArg', + 'over', + 'overEvery', + 'overSome', + 'rest', + 'reverse', + 'round', + 'runInContext', + 'spread', + 'template', + 'trim', + 'trimEnd', + 'trimStart', + 'uniqueId', + 'words', + 'zipAll' + ], + 2: [ + 'add', + 'after', + 'ary', + 'assign', + 'assignAllWith', + 'assignIn', + 'assignInAllWith', + 'at', + 'before', + 'bind', + 'bindAll', + 'bindKey', + 'chunk', + 'cloneDeepWith', + 'cloneWith', + 'concat', + 'conformsTo', + 'countBy', + 'curryN', + 'curryRightN', + 'debounce', + 'defaults', + 'defaultsDeep', + 'defaultTo', + 'delay', + 'difference', + 'divide', + 'drop', + 'dropRight', + 'dropRightWhile', + 'dropWhile', + 'endsWith', + 'eq', + 'every', + 'filter', + 'find', + 'findIndex', + 'findKey', + 'findLast', + 'findLastIndex', + 'findLastKey', + 'flatMap', + 'flatMapDeep', + 'flattenDepth', + 'forEach', + 'forEachRight', + 'forIn', + 'forInRight', + 'forOwn', + 'forOwnRight', + 'get', + 'groupBy', + 'gt', + 'gte', + 'has', + 'hasIn', + 'includes', + 'indexOf', + 'intersection', + 'invertBy', + 'invoke', + 'invokeMap', + 'isEqual', + 'isMatch', + 'join', + 'keyBy', + 'lastIndexOf', + 'lt', + 'lte', + 'map', + 'mapKeys', + 'mapValues', + 'matchesProperty', + 'maxBy', + 'meanBy', + 'merge', + 'mergeAllWith', + 'minBy', + 'multiply', + 'nth', + 'omit', + 'omitBy', + 'overArgs', + 'pad', + 'padEnd', + 'padStart', + 'parseInt', + 'partial', + 'partialRight', + 'partition', + 'pick', + 'pickBy', + 'propertyOf', + 'pull', + 'pullAll', + 'pullAt', + 'random', + 'range', + 'rangeRight', + 'rearg', + 'reject', + 'remove', + 'repeat', + 'restFrom', + 'result', + 'sampleSize', + 'some', + 'sortBy', + 'sortedIndex', + 'sortedIndexOf', + 'sortedLastIndex', + 'sortedLastIndexOf', + 'sortedUniqBy', + 'split', + 'spreadFrom', + 'startsWith', + 'subtract', + 'sumBy', + 'take', + 'takeRight', + 'takeRightWhile', + 'takeWhile', + 'tap', + 'throttle', + 'thru', + 'times', + 'trimChars', + 'trimCharsEnd', + 'trimCharsStart', + 'truncate', + 'union', + 'uniqBy', + 'uniqWith', + 'unset', + 'unzipWith', + 'without', + 'wrap', + 'xor', + 'zip', + 'zipObject', + 'zipObjectDeep' + ], + 3: [ + 'assignInWith', + 'assignWith', + 'clamp', + 'differenceBy', + 'differenceWith', + 'findFrom', + 'findIndexFrom', + 'findLastFrom', + 'findLastIndexFrom', + 'getOr', + 'includesFrom', + 'indexOfFrom', + 'inRange', + 'intersectionBy', + 'intersectionWith', + 'invokeArgs', + 'invokeArgsMap', + 'isEqualWith', + 'isMatchWith', + 'flatMapDepth', + 'lastIndexOfFrom', + 'mergeWith', + 'orderBy', + 'padChars', + 'padCharsEnd', + 'padCharsStart', + 'pullAllBy', + 'pullAllWith', + 'rangeStep', + 'rangeStepRight', + 'reduce', + 'reduceRight', + 'replace', + 'set', + 'slice', + 'sortedIndexBy', + 'sortedLastIndexBy', + 'transform', + 'unionBy', + 'unionWith', + 'update', + 'xorBy', + 'xorWith', + 'zipWith' + ], + 4: ['fill', 'setWith', 'updateWith'] + }), + (o.aryRearg = { 2: [1, 0], 3: [2, 0, 1], 4: [3, 2, 0, 1] }), + (o.iterateeAry = { + dropRightWhile: 1, + dropWhile: 1, + every: 1, + filter: 1, + find: 1, + findFrom: 1, + findIndex: 1, + findIndexFrom: 1, + findKey: 1, + findLast: 1, + findLastFrom: 1, + findLastIndex: 1, + findLastIndexFrom: 1, + findLastKey: 1, + flatMap: 1, + flatMapDeep: 1, + flatMapDepth: 1, + forEach: 1, + forEachRight: 1, + forIn: 1, + forInRight: 1, + forOwn: 1, + forOwnRight: 1, + map: 1, + mapKeys: 1, + mapValues: 1, + partition: 1, + reduce: 2, + reduceRight: 2, + reject: 1, + remove: 1, + some: 1, + takeRightWhile: 1, + takeWhile: 1, + times: 1, + transform: 2 + }), + (o.iterateeRearg = { mapKeys: [1], reduceRight: [1, 0] }), + (o.methodRearg = { + assignInAllWith: [1, 0], + assignInWith: [1, 2, 0], + assignAllWith: [1, 0], + assignWith: [1, 2, 0], + differenceBy: [1, 2, 0], + differenceWith: [1, 2, 0], + getOr: [2, 1, 0], + intersectionBy: [1, 2, 0], + intersectionWith: [1, 2, 0], + isEqualWith: [1, 2, 0], + isMatchWith: [2, 1, 0], + mergeAllWith: [1, 0], + mergeWith: [1, 2, 0], + padChars: [2, 1, 0], + padCharsEnd: [2, 1, 0], + padCharsStart: [2, 1, 0], + pullAllBy: [2, 1, 0], + pullAllWith: [2, 1, 0], + rangeStep: [1, 2, 0], + rangeStepRight: [1, 2, 0], + setWith: [3, 1, 2, 0], + sortedIndexBy: [2, 1, 0], + sortedLastIndexBy: [2, 1, 0], + unionBy: [1, 2, 0], + unionWith: [1, 2, 0], + updateWith: [3, 1, 2, 0], + xorBy: [1, 2, 0], + xorWith: [1, 2, 0], + zipWith: [1, 2, 0] + }), + (o.methodSpread = { + assignAll: { start: 0 }, + assignAllWith: { start: 0 }, + assignInAll: { start: 0 }, + assignInAllWith: { start: 0 }, + defaultsAll: { start: 0 }, + defaultsDeepAll: { start: 0 }, + invokeArgs: { start: 2 }, + invokeArgsMap: { start: 2 }, + mergeAll: { start: 0 }, + mergeAllWith: { start: 0 }, + partial: { start: 1 }, + partialRight: { start: 1 }, + without: { start: 1 }, + zipAll: { start: 0 } + }), + (o.mutate = { + array: { + fill: !0, + pull: !0, + pullAll: !0, + pullAllBy: !0, + pullAllWith: !0, + pullAt: !0, + remove: !0, + reverse: !0 + }, + object: { + assign: !0, + assignAll: !0, + assignAllWith: !0, + assignIn: !0, + assignInAll: !0, + assignInAllWith: !0, + assignInWith: !0, + assignWith: !0, + defaults: !0, + defaultsAll: !0, + defaultsDeep: !0, + defaultsDeepAll: !0, + merge: !0, + mergeAll: !0, + mergeAllWith: !0, + mergeWith: !0 + }, + set: { set: !0, setWith: !0, unset: !0, update: !0, updateWith: !0 } + }), + (o.realToAlias = (function () { + var s = Object.prototype.hasOwnProperty, + i = o.aliasToReal, + a = {}; + for (var u in i) { + var _ = i[u]; + s.call(a, _) ? a[_].push(u) : (a[_] = [u]); + } + return a; + })()), + (o.remap = { + assignAll: 'assign', + assignAllWith: 'assignWith', + assignInAll: 'assignIn', + assignInAllWith: 'assignInWith', + curryN: 'curry', + curryRightN: 'curryRight', + defaultsAll: 'defaults', + defaultsDeepAll: 'defaultsDeep', + findFrom: 'find', + findIndexFrom: 'findIndex', + findLastFrom: 'findLast', + findLastIndexFrom: 'findLastIndex', + getOr: 'get', + includesFrom: 'includes', + indexOfFrom: 'indexOf', + invokeArgs: 'invoke', + invokeArgsMap: 'invokeMap', + lastIndexOfFrom: 'lastIndexOf', + mergeAll: 'merge', + mergeAllWith: 'mergeWith', + padChars: 'pad', + padCharsEnd: 'padEnd', + padCharsStart: 'padStart', + propertyOf: 'get', + rangeStep: 'range', + rangeStepRight: 'rangeRight', + restFrom: 'rest', + spreadFrom: 'spread', + trimChars: 'trim', + trimCharsEnd: 'trimEnd', + trimCharsStart: 'trimStart', + zipAll: 'zip' + }), + (o.skipFixed = { + castArray: !0, + flow: !0, + flowRight: !0, + iteratee: !0, + mixin: !0, + rearg: !0, + runInContext: !0 + }), + (o.skipRearg = { + add: !0, + assign: !0, + assignIn: !0, + bind: !0, + bindKey: !0, + concat: !0, + difference: !0, + divide: !0, + eq: !0, + gt: !0, + gte: !0, + isEqual: !0, + lt: !0, + lte: !0, + matchesProperty: !0, + merge: !0, + multiply: !0, + overArgs: !0, + partial: !0, + partialRight: !0, + propertyOf: !0, + random: !0, + range: !0, + rangeRight: !0, + subtract: !0, + zip: !0, + zipObject: !0, + zipObjectDeep: !0 + })); + }, + 47934(s, o, i) { + s.exports = { + ary: i(64626), + assign: i(74733), + clone: i(32629), + curry: i(49747), + forEach: i(83729), + isArray: i(56449), + isError: i(23546), + isFunction: i(1882), + isWeakMap: i(47886), + iteratee: i(33855), + keys: i(88984), + rearg: i(84195), + toInteger: i(61489), + toPath: i(42072) + }; + }, + 56367(s, o, i) { + s.exports = i(77731); + }, + 79920(s, o, i) { + var a = i(73424), + u = i(47934); + s.exports = function convert(s, o, i) { + return a(u, s, o, i); + }; + }, + 2874(s) { + s.exports = {}; + }, + 77731(s, o, i) { + var a = i(79920)('set', i(63560)); + ((a.placeholder = i(2874)), (s.exports = a)); + }, + 58156(s, o, i) { + var a = i(47422); + s.exports = function get(s, o, i) { + var u = null == s ? void 0 : a(s, o); + return void 0 === u ? i : u; + }; + }, + 61448(s, o, i) { + var a = i(20426), + u = i(49326); + s.exports = function has(s, o) { + return null != s && u(s, o, a); + }; + }, + 80631(s, o, i) { + var a = i(28077), + u = i(49326); + s.exports = function hasIn(s, o) { + return null != s && u(s, o, a); + }; + }, + 83488(s) { + s.exports = function identity(s) { + return s; + }; + }, + 72428(s, o, i) { + var a = i(27534), + u = i(40346), + _ = Object.prototype, + w = _.hasOwnProperty, + x = _.propertyIsEnumerable, + C = a( + (function () { + return arguments; + })() + ) + ? a + : function (s) { + return u(s) && w.call(s, 'callee') && !x.call(s, 'callee'); + }; + s.exports = C; + }, + 56449(s) { + var o = Array.isArray; + s.exports = o; + }, + 64894(s, o, i) { + var a = i(1882), + u = i(30294); + s.exports = function isArrayLike(s) { + return null != s && u(s.length) && !a(s); + }; + }, + 83693(s, o, i) { + var a = i(64894), + u = i(40346); + s.exports = function isArrayLikeObject(s) { + return u(s) && a(s); + }; + }, + 53812(s, o, i) { + var a = i(72552), + u = i(40346); + s.exports = function isBoolean(s) { + return !0 === s || !1 === s || (u(s) && '[object Boolean]' == a(s)); + }; + }, + 3656(s, o, i) { + s = i.nmd(s); + var a = i(9325), + u = i(89935), + _ = o && !o.nodeType && o, + w = _ && s && !s.nodeType && s, + x = w && w.exports === _ ? a.Buffer : void 0, + C = (x ? x.isBuffer : void 0) || u; + s.exports = C; + }, + 62193(s, o, i) { + var a = i(88984), + u = i(5861), + _ = i(72428), + w = i(56449), + x = i(64894), + C = i(3656), + j = i(55527), + L = i(37167), + B = Object.prototype.hasOwnProperty; + s.exports = function isEmpty(s) { + if (null == s) return !0; + if ( + x(s) && + (w(s) || + 'string' == typeof s || + 'function' == typeof s.splice || + C(s) || + L(s) || + _(s)) + ) + return !s.length; + var o = u(s); + if ('[object Map]' == o || '[object Set]' == o) return !s.size; + if (j(s)) return !a(s).length; + for (var i in s) if (B.call(s, i)) return !1; + return !0; + }; + }, + 2404(s, o, i) { + var a = i(60270); + s.exports = function isEqual(s, o) { + return a(s, o); + }; + }, + 23546(s, o, i) { + var a = i(72552), + u = i(40346), + _ = i(11331); + s.exports = function isError(s) { + if (!u(s)) return !1; + var o = a(s); + return ( + '[object Error]' == o || + '[object DOMException]' == o || + ('string' == typeof s.message && 'string' == typeof s.name && !_(s)) + ); + }; + }, + 1882(s, o, i) { + var a = i(72552), + u = i(23805); + s.exports = function isFunction(s) { + if (!u(s)) return !1; + var o = a(s); + return ( + '[object Function]' == o || + '[object GeneratorFunction]' == o || + '[object AsyncFunction]' == o || + '[object Proxy]' == o + ); + }; + }, + 30294(s) { + s.exports = function isLength(s) { + return 'number' == typeof s && s > -1 && s % 1 == 0 && s <= 9007199254740991; + }; + }, + 87730(s, o, i) { + var a = i(29172), + u = i(27301), + _ = i(86009), + w = _ && _.isMap, + x = w ? u(w) : a; + s.exports = x; + }, + 5187(s) { + s.exports = function isNull(s) { + return null === s; + }; + }, + 98023(s, o, i) { + var a = i(72552), + u = i(40346); + s.exports = function isNumber(s) { + return 'number' == typeof s || (u(s) && '[object Number]' == a(s)); + }; + }, + 23805(s) { + s.exports = function isObject(s) { + var o = typeof s; + return null != s && ('object' == o || 'function' == o); + }; + }, + 40346(s) { + s.exports = function isObjectLike(s) { + return null != s && 'object' == typeof s; + }; + }, + 11331(s, o, i) { + var a = i(72552), + u = i(28879), + _ = i(40346), + w = Function.prototype, + x = Object.prototype, + C = w.toString, + j = x.hasOwnProperty, + L = C.call(Object); + s.exports = function isPlainObject(s) { + if (!_(s) || '[object Object]' != a(s)) return !1; + var o = u(s); + if (null === o) return !0; + var i = j.call(o, 'constructor') && o.constructor; + return 'function' == typeof i && i instanceof i && C.call(i) == L; + }; + }, + 38440(s, o, i) { + var a = i(16038), + u = i(27301), + _ = i(86009), + w = _ && _.isSet, + x = w ? u(w) : a; + s.exports = x; + }, + 85015(s, o, i) { + var a = i(72552), + u = i(56449), + _ = i(40346); + s.exports = function isString(s) { + return 'string' == typeof s || (!u(s) && _(s) && '[object String]' == a(s)); + }; + }, + 44394(s, o, i) { + var a = i(72552), + u = i(40346); + s.exports = function isSymbol(s) { + return 'symbol' == typeof s || (u(s) && '[object Symbol]' == a(s)); + }; + }, + 37167(s, o, i) { + var a = i(4901), + u = i(27301), + _ = i(86009), + w = _ && _.isTypedArray, + x = w ? u(w) : a; + s.exports = x; + }, + 47886(s, o, i) { + var a = i(5861), + u = i(40346); + s.exports = function isWeakMap(s) { + return u(s) && '[object WeakMap]' == a(s); + }; + }, + 33855(s, o, i) { + var a = i(9999), + u = i(15389); + s.exports = function iteratee(s) { + return u('function' == typeof s ? s : a(s, 1)); + }; + }, + 95950(s, o, i) { + var a = i(70695), + u = i(88984), + _ = i(64894); + s.exports = function keys(s) { + return _(s) ? a(s) : u(s); + }; + }, + 37241(s, o, i) { + var a = i(70695), + u = i(72903), + _ = i(64894); + s.exports = function keysIn(s) { + return _(s) ? a(s, !0) : u(s); + }; + }, + 68090(s) { + s.exports = function last(s) { + var o = null == s ? 0 : s.length; + return o ? s[o - 1] : void 0; + }; + }, + 50104(s, o, i) { + var a = i(53661); + function memoize(s, o) { + if ('function' != typeof s || (null != o && 'function' != typeof o)) + throw new TypeError('Expected a function'); + var memoized = function () { + var i = arguments, + a = o ? o.apply(this, i) : i[0], + u = memoized.cache; + if (u.has(a)) return u.get(a); + var _ = s.apply(this, i); + return ((memoized.cache = u.set(a, _) || u), _); + }; + return ((memoized.cache = new (memoize.Cache || a)()), memoized); + } + ((memoize.Cache = a), (s.exports = memoize)); + }, + 55364(s, o, i) { + var a = i(85250), + u = i(20999)(function (s, o, i) { + a(s, o, i); + }); + s.exports = u; + }, + 6048(s) { + s.exports = function negate(s) { + if ('function' != typeof s) throw new TypeError('Expected a function'); + return function () { + var o = arguments; + switch (o.length) { + case 0: + return !s.call(this); + case 1: + return !s.call(this, o[0]); + case 2: + return !s.call(this, o[0], o[1]); + case 3: + return !s.call(this, o[0], o[1], o[2]); + } + return !s.apply(this, o); + }; + }; + }, + 63950(s) { + s.exports = function noop() {}; + }, + 10124(s, o, i) { + var a = i(9325); + s.exports = function () { + return a.Date.now(); + }; + }, + 90179(s, o, i) { + var a = i(34932), + u = i(9999), + _ = i(19931), + w = i(31769), + x = i(21791), + C = i(53138), + j = i(38816), + L = i(83349), + B = j(function (s, o) { + var i = {}; + if (null == s) return i; + var j = !1; + ((o = a(o, function (o) { + return ((o = w(o, s)), j || (j = o.length > 1), o); + })), + x(s, L(s), i), + j && (i = u(i, 7, C))); + for (var B = o.length; B--; ) _(i, o[B]); + return i; + }); + s.exports = B; + }, + 50583(s, o, i) { + var a = i(47237), + u = i(17255), + _ = i(28586), + w = i(77797); + s.exports = function property(s) { + return _(s) ? a(w(s)) : u(s); + }; + }, + 84195(s, o, i) { + var a = i(66977), + u = i(38816), + _ = u(function (s, o) { + return a(s, 256, void 0, void 0, void 0, o); + }); + s.exports = _; + }, + 40860(s, o, i) { + var a = i(40882), + u = i(80909), + _ = i(15389), + w = i(85558), + x = i(56449); + s.exports = function reduce(s, o, i) { + var C = x(s) ? a : w, + j = arguments.length < 3; + return C(s, _(o, 4), i, j, u); + }; + }, + 63560(s, o, i) { + var a = i(73170); + s.exports = function set(s, o, i) { + return null == s ? s : a(s, o, i); + }; + }, + 42426(s, o, i) { + var a = i(14248), + u = i(15389), + _ = i(90916), + w = i(56449), + x = i(36800); + s.exports = function some(s, o, i) { + var C = w(s) ? a : _; + return (i && x(s, o, i) && (o = void 0), C(s, u(o, 3))); + }; + }, + 63345(s) { + s.exports = function stubArray() { + return []; + }; + }, + 89935(s) { + s.exports = function stubFalse() { + return !1; + }; + }, + 17400(s, o, i) { + var a = i(99374), + u = 1 / 0; + s.exports = function toFinite(s) { + return s + ? (s = a(s)) === u || s === -1 / 0 + ? 17976931348623157e292 * (s < 0 ? -1 : 1) + : s == s + ? s + : 0 + : 0 === s + ? s + : 0; + }; + }, + 61489(s, o, i) { + var a = i(17400); + s.exports = function toInteger(s) { + var o = a(s), + i = o % 1; + return o == o ? (i ? o - i : o) : 0; + }; + }, + 80218(s, o, i) { + var a = i(13222); + s.exports = function toLower(s) { + return a(s).toLowerCase(); + }; + }, + 99374(s, o, i) { + var a = i(54128), + u = i(23805), + _ = i(44394), + w = /^[-+]0x[0-9a-f]+$/i, + x = /^0b[01]+$/i, + C = /^0o[0-7]+$/i, + j = parseInt; + s.exports = function toNumber(s) { + if ('number' == typeof s) return s; + if (_(s)) return NaN; + if (u(s)) { + var o = 'function' == typeof s.valueOf ? s.valueOf() : s; + s = u(o) ? o + '' : o; + } + if ('string' != typeof s) return 0 === s ? s : +s; + s = a(s); + var i = x.test(s); + return i || C.test(s) ? j(s.slice(2), i ? 2 : 8) : w.test(s) ? NaN : +s; + }; + }, + 42072(s, o, i) { + var a = i(34932), + u = i(23007), + _ = i(56449), + w = i(44394), + x = i(61802), + C = i(77797), + j = i(13222); + s.exports = function toPath(s) { + return _(s) ? a(s, C) : w(s) ? [s] : u(x(j(s))); + }; + }, + 69884(s, o, i) { + var a = i(21791), + u = i(37241); + s.exports = function toPlainObject(s) { + return a(s, u(s)); + }; + }, + 13222(s, o, i) { + var a = i(77556); + s.exports = function toString(s) { + return null == s ? '' : a(s); + }; + }, + 55808(s, o, i) { + var a = i(12507)('toUpperCase'); + s.exports = a; + }, + 66645(s, o, i) { + var a = i(1733), + u = i(45434), + _ = i(13222), + w = i(22225); + s.exports = function words(s, o, i) { + return ( + (s = _(s)), + void 0 === (o = i ? void 0 : o) ? (u(s) ? w(s) : a(s)) : s.match(o) || [] + ); + }; + }, + 53758(s, o, i) { + var a = i(30980), + u = i(56017), + _ = i(94033), + w = i(56449), + x = i(40346), + C = i(80257), + j = Object.prototype.hasOwnProperty; + function lodash(s) { + if (x(s) && !w(s) && !(s instanceof a)) { + if (s instanceof u) return s; + if (j.call(s, '__wrapped__')) return C(s); + } + return new u(s); + } + ((lodash.prototype = _.prototype), + (lodash.prototype.constructor = lodash), + (s.exports = lodash)); + }, + 47248(s, o, i) { + var a = i(16547), + u = i(51234); + s.exports = function zipObject(s, o) { + return u(s || [], o || [], a); + }; + }, + 43768(s, o, i) { + 'use strict'; + var a = i(45981), + u = i(85587); + ((o.highlight = highlight), + (o.highlightAuto = function highlightAuto(s, o) { + var i, + w, + x, + C, + j = o || {}, + L = j.subset || a.listLanguages(), + B = j.prefix, + $ = L.length, + U = -1; + null == B && (B = _); + if ('string' != typeof s) throw u('Expected `string` for value, got `%s`', s); + ((w = { relevance: 0, language: null, value: [] }), + (i = { relevance: 0, language: null, value: [] })); + for (; ++U < $; ) + ((C = L[U]), + a.getLanguage(C) && + (((x = highlight(C, s, o)).language = C), + x.relevance > w.relevance && (w = x), + x.relevance > i.relevance && ((w = i), (i = x)))); + w.language && (i.secondBest = w); + return i; + }), + (o.registerLanguage = function registerLanguage(s, o) { + a.registerLanguage(s, o); + }), + (o.listLanguages = function listLanguages() { + return a.listLanguages(); + }), + (o.registerAlias = function registerAlias(s, o) { + var i, + u = s; + o && ((u = {})[s] = o); + for (i in u) a.registerAliases(u[i], { languageName: i }); + }), + (Emitter.prototype.addText = function text(s) { + var o, + i, + a = this.stack; + if ('' === s) return; + ((o = a[a.length - 1]), + (i = o.children[o.children.length - 1]) && 'text' === i.type + ? (i.value += s) + : o.children.push({ type: 'text', value: s })); + }), + (Emitter.prototype.addKeyword = function addKeyword(s, o) { + (this.openNode(o), this.addText(s), this.closeNode()); + }), + (Emitter.prototype.addSublanguage = function addSublanguage(s, o) { + var i = this.stack, + a = i[i.length - 1], + u = s.rootNode.children, + _ = o + ? { + type: 'element', + tagName: 'span', + properties: { className: [o] }, + children: u + } + : u; + a.children = a.children.concat(_); + }), + (Emitter.prototype.openNode = function open(s) { + var o = this.stack, + i = this.options.classPrefix + s, + a = o[o.length - 1], + u = { + type: 'element', + tagName: 'span', + properties: { className: [i] }, + children: [] + }; + (a.children.push(u), o.push(u)); + }), + (Emitter.prototype.closeNode = function close() { + this.stack.pop(); + }), + (Emitter.prototype.closeAllNodes = noop), + (Emitter.prototype.finalize = noop), + (Emitter.prototype.toHTML = function toHtmlNoop() { + return ''; + })); + var _ = 'hljs-'; + function highlight(s, o, i) { + var w, + x = a.configure({}), + C = (i || {}).prefix; + if ('string' != typeof s) throw u('Expected `string` for name, got `%s`', s); + if (!a.getLanguage(s)) throw u('Unknown language: `%s` is not registered', s); + if ('string' != typeof o) throw u('Expected `string` for value, got `%s`', o); + if ( + (null == C && (C = _), + a.configure({ __emitter: Emitter, classPrefix: C }), + (w = a.highlight(o, { language: s, ignoreIllegals: !0 })), + a.configure(x || {}), + w.errorRaised) + ) + throw w.errorRaised; + return { + relevance: w.relevance, + language: w.language, + value: w.emitter.rootNode.children + }; + } + function Emitter(s) { + ((this.options = s), + (this.rootNode = { children: [] }), + (this.stack = [this.rootNode])); + } + function noop() {} + }, + 71514(s) { + 'use strict'; + s.exports = Math.abs; + }, + 58968(s) { + 'use strict'; + s.exports = Math.floor; + }, + 94459(s) { + 'use strict'; + s.exports = + Number.isNaN || + function isNaN(s) { + return s != s; + }; + }, + 6188(s) { + 'use strict'; + s.exports = Math.max; + }, + 68002(s) { + 'use strict'; + s.exports = Math.min; + }, + 75880(s) { + 'use strict'; + s.exports = Math.pow; + }, + 70414(s) { + 'use strict'; + s.exports = Math.round; + }, + 73093(s, o, i) { + 'use strict'; + var a = i(94459); + s.exports = function sign(s) { + return a(s) || 0 === s ? s : s < 0 ? -1 : 1; + }; + }, + 92340(s, o, i) { + const a = i(6048); + function coerceElementMatchingCallback(s) { + return 'string' == typeof s + ? (o) => o.element === s + : s.constructor && s.extend + ? (o) => o instanceof s + : s; + } + class ArraySlice { + constructor(s) { + this.elements = s || []; + } + toValue() { + return this.elements.map((s) => s.toValue()); + } + map(s, o) { + return this.elements.map(s, o); + } + flatMap(s, o) { + return this.map(s, o).reduce((s, o) => s.concat(o), []); + } + compactMap(s, o) { + const i = []; + return ( + this.forEach((a) => { + const u = s.bind(o)(a); + u && i.push(u); + }), + i + ); + } + filter(s, o) { + return ( + (s = coerceElementMatchingCallback(s)), + new ArraySlice(this.elements.filter(s, o)) + ); + } + reject(s, o) { + return ( + (s = coerceElementMatchingCallback(s)), + new ArraySlice(this.elements.filter(a(s), o)) + ); + } + find(s, o) { + return ((s = coerceElementMatchingCallback(s)), this.elements.find(s, o)); + } + forEach(s, o) { + this.elements.forEach(s, o); + } + reduce(s, o) { + return this.elements.reduce(s, o); + } + includes(s) { + return this.elements.some((o) => o.equals(s)); + } + shift() { + return this.elements.shift(); + } + unshift(s) { + this.elements.unshift(this.refract(s)); + } + push(s) { + return (this.elements.push(this.refract(s)), this); + } + add(s) { + this.push(s); + } + get(s) { + return this.elements[s]; + } + getValue(s) { + const o = this.elements[s]; + if (o) return o.toValue(); + } + get length() { + return this.elements.length; + } + get isEmpty() { + return 0 === this.elements.length; + } + get first() { + return this.elements[0]; + } + } + ('undefined' != typeof Symbol && + (ArraySlice.prototype[Symbol.iterator] = function symbol() { + return this.elements[Symbol.iterator](); + }), + (s.exports = ArraySlice)); + }, + 55973(s) { + class KeyValuePair { + constructor(s, o) { + ((this.key = s), (this.value = o)); + } + clone() { + const s = new KeyValuePair(); + return ( + this.key && (s.key = this.key.clone()), + this.value && (s.value = this.value.clone()), + s + ); + } + } + s.exports = KeyValuePair; + }, + 3110(s, o, i) { + const a = i(5187), + u = i(85015), + _ = i(98023), + w = i(53812), + x = i(23805), + C = i(85105), + j = i(86804); + class Namespace { + constructor(s) { + ((this.elementMap = {}), + (this.elementDetection = []), + (this.Element = j.Element), + (this.KeyValuePair = j.KeyValuePair), + (s && s.noDefault) || this.useDefault(), + (this._attributeElementKeys = []), + (this._attributeElementArrayKeys = [])); + } + use(s) { + return ( + s.namespace && s.namespace({ base: this }), + s.load && s.load({ base: this }), + this + ); + } + useDefault() { + return ( + this.register('null', j.NullElement) + .register('string', j.StringElement) + .register('number', j.NumberElement) + .register('boolean', j.BooleanElement) + .register('array', j.ArrayElement) + .register('object', j.ObjectElement) + .register('member', j.MemberElement) + .register('ref', j.RefElement) + .register('link', j.LinkElement), + this.detect(a, j.NullElement, !1) + .detect(u, j.StringElement, !1) + .detect(_, j.NumberElement, !1) + .detect(w, j.BooleanElement, !1) + .detect(Array.isArray, j.ArrayElement, !1) + .detect(x, j.ObjectElement, !1), + this + ); + } + register(s, o) { + return ((this._elements = void 0), (this.elementMap[s] = o), this); + } + unregister(s) { + return ((this._elements = void 0), delete this.elementMap[s], this); + } + detect(s, o, i) { + return ( + void 0 === i || i + ? this.elementDetection.unshift([s, o]) + : this.elementDetection.push([s, o]), + this + ); + } + toElement(s) { + if (s instanceof this.Element) return s; + let o; + for (let i = 0; i < this.elementDetection.length; i += 1) { + const a = this.elementDetection[i][0], + u = this.elementDetection[i][1]; + if (a(s)) { + o = new u(s); + break; + } + } + return o; + } + getElementClass(s) { + const o = this.elementMap[s]; + return void 0 === o ? this.Element : o; + } + fromRefract(s) { + return this.serialiser.deserialise(s); + } + toRefract(s) { + return this.serialiser.serialise(s); + } + get elements() { + return ( + void 0 === this._elements && + ((this._elements = { Element: this.Element }), + Object.keys(this.elementMap).forEach((s) => { + const o = s[0].toUpperCase() + s.substr(1); + this._elements[o] = this.elementMap[s]; + })), + this._elements + ); + } + get serialiser() { + return new C(this); + } + } + ((C.prototype.Namespace = Namespace), (s.exports = Namespace)); + }, + 10866(s, o, i) { + const a = i(6048), + u = i(92340); + class ObjectSlice extends u { + map(s, o) { + return this.elements.map((i) => s.bind(o)(i.value, i.key, i)); + } + filter(s, o) { + return new ObjectSlice(this.elements.filter((i) => s.bind(o)(i.value, i.key, i))); + } + reject(s, o) { + return this.filter(a(s.bind(o))); + } + forEach(s, o) { + return this.elements.forEach((i, a) => { + s.bind(o)(i.value, i.key, i, a); + }); + } + keys() { + return this.map((s, o) => o.toValue()); + } + values() { + return this.map((s) => s.toValue()); + } + } + s.exports = ObjectSlice; + }, + 86804(s, o, i) { + const a = i(10316), + u = i(41067), + _ = i(71167), + w = i(40239), + x = i(12242), + C = i(6233), + j = i(87726), + L = i(61045), + B = i(86303), + $ = i(14540), + U = i(92340), + V = i(10866), + z = i(55973); + function refract(s) { + if (s instanceof a) return s; + if ('string' == typeof s) return new _(s); + if ('number' == typeof s) return new w(s); + if ('boolean' == typeof s) return new x(s); + if (null === s) return new u(); + if (Array.isArray(s)) return new C(s.map(refract)); + if ('object' == typeof s) { + return new L(s); + } + return s; + } + ((a.prototype.ObjectElement = L), + (a.prototype.RefElement = $), + (a.prototype.MemberElement = j), + (a.prototype.refract = refract), + (U.prototype.refract = refract), + (s.exports = { + Element: a, + NullElement: u, + StringElement: _, + NumberElement: w, + BooleanElement: x, + ArrayElement: C, + MemberElement: j, + ObjectElement: L, + LinkElement: B, + RefElement: $, + refract, + ArraySlice: U, + ObjectSlice: V, + KeyValuePair: z + })); + }, + 86303(s, o, i) { + const a = i(10316); + s.exports = class LinkElement extends a { + constructor(s, o, i) { + (super(s || [], o, i), (this.element = 'link')); + } + get relation() { + return this.attributes.get('relation'); + } + set relation(s) { + this.attributes.set('relation', s); + } + get href() { + return this.attributes.get('href'); + } + set href(s) { + this.attributes.set('href', s); + } + }; + }, + 14540(s, o, i) { + const a = i(10316); + s.exports = class RefElement extends a { + constructor(s, o, i) { + (super(s || [], o, i), (this.element = 'ref'), this.path || (this.path = 'element')); + } + get path() { + return this.attributes.get('path'); + } + set path(s) { + this.attributes.set('path', s); + } + }; + }, + 34035(s, o, i) { + const a = i(3110), + u = i(86804); + ((o.g$ = a), + (o.KeyValuePair = i(55973)), + (o.G6 = u.ArraySlice), + (o.ot = u.ObjectSlice), + (o.Hg = u.Element), + (o.Om = u.StringElement), + (o.kT = u.NumberElement), + (o.bd = u.BooleanElement), + (o.Os = u.NullElement), + (o.wE = u.ArrayElement), + (o.Sh = u.ObjectElement), + (o.Pr = u.MemberElement), + (o.sI = u.RefElement), + (o.Ft = u.LinkElement), + (o.e = u.refract), + i(85105), + i(75147)); + }, + 6233(s, o, i) { + const a = i(6048), + u = i(10316), + _ = i(92340); + class ArrayElement extends u { + constructor(s, o, i) { + (super(s || [], o, i), (this.element = 'array')); + } + primitive() { + return 'array'; + } + get(s) { + return this.content[s]; + } + getValue(s) { + const o = this.get(s); + if (o) return o.toValue(); + } + getIndex(s) { + return this.content[s]; + } + set(s, o) { + return ((this.content[s] = this.refract(o)), this); + } + remove(s) { + const o = this.content.splice(s, 1); + return o.length ? o[0] : null; + } + map(s, o) { + return this.content.map(s, o); + } + flatMap(s, o) { + return this.map(s, o).reduce((s, o) => s.concat(o), []); + } + compactMap(s, o) { + const i = []; + return ( + this.forEach((a) => { + const u = s.bind(o)(a); + u && i.push(u); + }), + i + ); + } + filter(s, o) { + return new _(this.content.filter(s, o)); + } + reject(s, o) { + return this.filter(a(s), o); + } + reduce(s, o) { + let i, a; + void 0 !== o + ? ((i = 0), (a = this.refract(o))) + : ((i = 1), (a = 'object' === this.primitive() ? this.first.value : this.first)); + for (let o = i; o < this.length; o += 1) { + const i = this.content[o]; + a = + 'object' === this.primitive() + ? this.refract(s(a, i.value, i.key, i, this)) + : this.refract(s(a, i, o, this)); + } + return a; + } + forEach(s, o) { + this.content.forEach((i, a) => { + s.bind(o)(i, this.refract(a)); + }); + } + shift() { + return this.content.shift(); + } + unshift(s) { + this.content.unshift(this.refract(s)); + } + push(s) { + return (this.content.push(this.refract(s)), this); + } + add(s) { + this.push(s); + } + findElements(s, o) { + const i = o || {}, + a = !!i.recursive, + u = void 0 === i.results ? [] : i.results; + return ( + this.forEach((o, i, _) => { + (a && + void 0 !== o.findElements && + o.findElements(s, { results: u, recursive: a }), + s(o, i, _) && u.push(o)); + }), + u + ); + } + find(s) { + return new _(this.findElements(s, { recursive: !0 })); + } + findByElement(s) { + return this.find((o) => o.element === s); + } + findByClass(s) { + return this.find((o) => o.classes.includes(s)); + } + getById(s) { + return this.find((o) => o.id.toValue() === s).first; + } + includes(s) { + return this.content.some((o) => o.equals(s)); + } + contains(s) { + return this.includes(s); + } + empty() { + return new this.constructor([]); + } + 'fantasy-land/empty'() { + return this.empty(); + } + concat(s) { + return new this.constructor(this.content.concat(s.content)); + } + 'fantasy-land/concat'(s) { + return this.concat(s); + } + 'fantasy-land/map'(s) { + return new this.constructor(this.map(s)); + } + 'fantasy-land/chain'(s) { + return this.map((o) => s(o), this).reduce((s, o) => s.concat(o), this.empty()); + } + 'fantasy-land/filter'(s) { + return new this.constructor(this.content.filter(s)); + } + 'fantasy-land/reduce'(s, o) { + return this.content.reduce(s, o); + } + get length() { + return this.content.length; + } + get isEmpty() { + return 0 === this.content.length; + } + get first() { + return this.getIndex(0); + } + get second() { + return this.getIndex(1); + } + get last() { + return this.getIndex(this.length - 1); + } + } + ((ArrayElement.empty = function empty() { + return new this(); + }), + (ArrayElement['fantasy-land/empty'] = ArrayElement.empty), + 'undefined' != typeof Symbol && + (ArrayElement.prototype[Symbol.iterator] = function symbol() { + return this.content[Symbol.iterator](); + }), + (s.exports = ArrayElement)); + }, + 12242(s, o, i) { + const a = i(10316); + s.exports = class BooleanElement extends a { + constructor(s, o, i) { + (super(s, o, i), (this.element = 'boolean')); + } + primitive() { + return 'boolean'; + } + }; + }, + 10316(s, o, i) { + const a = i(2404), + u = i(55973), + _ = i(92340); + class Element { + constructor(s, o, i) { + (o && (this.meta = o), i && (this.attributes = i), (this.content = s)); + } + freeze() { + Object.isFrozen(this) || + (this._meta && ((this.meta.parent = this), this.meta.freeze()), + this._attributes && ((this.attributes.parent = this), this.attributes.freeze()), + this.children.forEach((s) => { + ((s.parent = this), s.freeze()); + }, this), + this.content && Array.isArray(this.content) && Object.freeze(this.content), + Object.freeze(this)); + } + primitive() {} + clone() { + const s = new this.constructor(); + return ( + (s.element = this.element), + this.meta.length && (s._meta = this.meta.clone()), + this.attributes.length && (s._attributes = this.attributes.clone()), + this.content + ? this.content.clone + ? (s.content = this.content.clone()) + : Array.isArray(this.content) + ? (s.content = this.content.map((s) => s.clone())) + : (s.content = this.content) + : (s.content = this.content), + s + ); + } + toValue() { + return this.content instanceof Element + ? this.content.toValue() + : this.content instanceof u + ? { + key: this.content.key.toValue(), + value: this.content.value ? this.content.value.toValue() : void 0 + } + : this.content && this.content.map + ? this.content.map((s) => s.toValue(), this) + : this.content; + } + toRef(s) { + if ('' === this.id.toValue()) + throw Error('Cannot create reference to an element that does not contain an ID'); + const o = new this.RefElement(this.id.toValue()); + return (s && (o.path = s), o); + } + findRecursive(...s) { + if (arguments.length > 1 && !this.isFrozen) + throw new Error( + 'Cannot find recursive with multiple element names without first freezing the element. Call `element.freeze()`' + ); + const o = s.pop(); + let i = new _(); + const append = (s, o) => (s.push(o), s), + checkElement = (s, i) => { + i.element === o && s.push(i); + const a = i.findRecursive(o); + return ( + a && a.reduce(append, s), + i.content instanceof u && + (i.content.key && checkElement(s, i.content.key), + i.content.value && checkElement(s, i.content.value)), + s + ); + }; + return ( + this.content && + (this.content.element && checkElement(i, this.content), + Array.isArray(this.content) && this.content.reduce(checkElement, i)), + s.isEmpty || + (i = i.filter((o) => { + let i = o.parents.map((s) => s.element); + for (const o in s) { + const a = s[o], + u = i.indexOf(a); + if (-1 === u) return !1; + i = i.splice(0, u); + } + return !0; + })), + i + ); + } + set(s) { + return ((this.content = s), this); + } + equals(s) { + return a(this.toValue(), s); + } + getMetaProperty(s, o) { + if (!this.meta.hasKey(s)) { + if (this.isFrozen) { + const s = this.refract(o); + return (s.freeze(), s); + } + this.meta.set(s, o); + } + return this.meta.get(s); + } + setMetaProperty(s, o) { + this.meta.set(s, o); + } + get element() { + return this._storedElement || 'element'; + } + set element(s) { + this._storedElement = s; + } + get content() { + return this._content; + } + set content(s) { + if (s instanceof Element) this._content = s; + else if (s instanceof _) this.content = s.elements; + else if ( + 'string' == typeof s || + 'number' == typeof s || + 'boolean' == typeof s || + 'null' === s || + null == s + ) + this._content = s; + else if (s instanceof u) this._content = s; + else if (Array.isArray(s)) this._content = s.map(this.refract); + else { + if ('object' != typeof s) throw new Error('Cannot set content to given value'); + this._content = Object.keys(s).map((o) => new this.MemberElement(o, s[o])); + } + } + get meta() { + if (!this._meta) { + if (this.isFrozen) { + const s = new this.ObjectElement(); + return (s.freeze(), s); + } + this._meta = new this.ObjectElement(); + } + return this._meta; + } + set meta(s) { + s instanceof this.ObjectElement ? (this._meta = s) : this.meta.set(s || {}); + } + get attributes() { + if (!this._attributes) { + if (this.isFrozen) { + const s = new this.ObjectElement(); + return (s.freeze(), s); + } + this._attributes = new this.ObjectElement(); + } + return this._attributes; + } + set attributes(s) { + s instanceof this.ObjectElement + ? (this._attributes = s) + : this.attributes.set(s || {}); + } + get id() { + return this.getMetaProperty('id', ''); + } + set id(s) { + this.setMetaProperty('id', s); + } + get classes() { + return this.getMetaProperty('classes', []); + } + set classes(s) { + this.setMetaProperty('classes', s); + } + get title() { + return this.getMetaProperty('title', ''); + } + set title(s) { + this.setMetaProperty('title', s); + } + get description() { + return this.getMetaProperty('description', ''); + } + set description(s) { + this.setMetaProperty('description', s); + } + get links() { + return this.getMetaProperty('links', []); + } + set links(s) { + this.setMetaProperty('links', s); + } + get isFrozen() { + return Object.isFrozen(this); + } + get parents() { + let { parent: s } = this; + const o = new _(); + for (; s; ) (o.push(s), (s = s.parent)); + return o; + } + get children() { + if (Array.isArray(this.content)) return new _(this.content); + if (this.content instanceof u) { + const s = new _([this.content.key]); + return (this.content.value && s.push(this.content.value), s); + } + return this.content instanceof Element ? new _([this.content]) : new _(); + } + get recursiveChildren() { + const s = new _(); + return ( + this.children.forEach((o) => { + (s.push(o), + o.recursiveChildren.forEach((o) => { + s.push(o); + })); + }), + s + ); + } + } + s.exports = Element; + }, + 87726(s, o, i) { + const a = i(55973), + u = i(10316); + s.exports = class MemberElement extends u { + constructor(s, o, i, u) { + (super(new a(), i, u), (this.element = 'member'), (this.key = s), (this.value = o)); + } + get key() { + return this.content.key; + } + set key(s) { + this.content.key = this.refract(s); + } + get value() { + return this.content.value; + } + set value(s) { + this.content.value = this.refract(s); + } + }; + }, + 41067(s, o, i) { + const a = i(10316); + s.exports = class NullElement extends a { + constructor(s, o, i) { + (super(s || null, o, i), (this.element = 'null')); + } + primitive() { + return 'null'; + } + set() { + return new Error('Cannot set the value of null'); + } + }; + }, + 40239(s, o, i) { + const a = i(10316); + s.exports = class NumberElement extends a { + constructor(s, o, i) { + (super(s, o, i), (this.element = 'number')); + } + primitive() { + return 'number'; + } + }; + }, + 61045(s, o, i) { + const a = i(6048), + u = i(23805), + _ = i(6233), + w = i(87726), + x = i(10866); + s.exports = class ObjectElement extends _ { + constructor(s, o, i) { + (super(s || [], o, i), (this.element = 'object')); + } + primitive() { + return 'object'; + } + toValue() { + return this.content.reduce( + (s, o) => ((s[o.key.toValue()] = o.value ? o.value.toValue() : void 0), s), + {} + ); + } + get(s) { + const o = this.getMember(s); + if (o) return o.value; + } + getMember(s) { + if (void 0 !== s) return this.content.find((o) => o.key.toValue() === s); + } + remove(s) { + let o = null; + return ( + (this.content = this.content.filter((i) => i.key.toValue() !== s || ((o = i), !1))), + o + ); + } + getKey(s) { + const o = this.getMember(s); + if (o) return o.key; + } + set(s, o) { + if (u(s)) + return ( + Object.keys(s).forEach((o) => { + this.set(o, s[o]); + }), + this + ); + const i = s, + a = this.getMember(i); + return (a ? (a.value = o) : this.content.push(new w(i, o)), this); + } + keys() { + return this.content.map((s) => s.key.toValue()); + } + values() { + return this.content.map((s) => s.value.toValue()); + } + hasKey(s) { + return this.content.some((o) => o.key.equals(s)); + } + items() { + return this.content.map((s) => [s.key.toValue(), s.value.toValue()]); + } + map(s, o) { + return this.content.map((i) => s.bind(o)(i.value, i.key, i)); + } + compactMap(s, o) { + const i = []; + return ( + this.forEach((a, u, _) => { + const w = s.bind(o)(a, u, _); + w && i.push(w); + }), + i + ); + } + filter(s, o) { + return new x(this.content).filter(s, o); + } + reject(s, o) { + return this.filter(a(s), o); + } + forEach(s, o) { + return this.content.forEach((i) => s.bind(o)(i.value, i.key, i)); + } + }; + }, + 71167(s, o, i) { + const a = i(10316); + s.exports = class StringElement extends a { + constructor(s, o, i) { + (super(s, o, i), (this.element = 'string')); + } + primitive() { + return 'string'; + } + get length() { + return this.content.length; + } + }; + }, + 75147(s, o, i) { + const a = i(85105); + s.exports = class JSON06Serialiser extends a { + serialise(s) { + if (!(s instanceof this.namespace.elements.Element)) + throw new TypeError(`Given element \`${s}\` is not an Element instance`); + let o; + s._attributes && s.attributes.get('variable') && (o = s.attributes.get('variable')); + const i = { element: s.element }; + s._meta && s._meta.length > 0 && (i.meta = this.serialiseObject(s.meta)); + const a = 'enum' === s.element || -1 !== s.attributes.keys().indexOf('enumerations'); + if (a) { + const o = this.enumSerialiseAttributes(s); + o && (i.attributes = o); + } else if (s._attributes && s._attributes.length > 0) { + let { attributes: a } = s; + (a.get('metadata') && + ((a = a.clone()), a.set('meta', a.get('metadata')), a.remove('metadata')), + 'member' === s.element && o && ((a = a.clone()), a.remove('variable')), + a.length > 0 && (i.attributes = this.serialiseObject(a))); + } + if (a) i.content = this.enumSerialiseContent(s, i); + else if (this[`${s.element}SerialiseContent`]) + i.content = this[`${s.element}SerialiseContent`](s, i); + else if (void 0 !== s.content) { + let a; + (o && s.content.key + ? ((a = s.content.clone()), + a.key.attributes.set('variable', o), + (a = this.serialiseContent(a))) + : (a = this.serialiseContent(s.content)), + this.shouldSerialiseContent(s, a) && (i.content = a)); + } else + this.shouldSerialiseContent(s, s.content) && + s instanceof this.namespace.elements.Array && + (i.content = []); + return i; + } + shouldSerialiseContent(s, o) { + return ( + 'parseResult' === s.element || + 'httpRequest' === s.element || + 'httpResponse' === s.element || + 'category' === s.element || + 'link' === s.element || + (void 0 !== o && (!Array.isArray(o) || 0 !== o.length)) + ); + } + refSerialiseContent(s, o) { + return (delete o.attributes, { href: s.toValue(), path: s.path.toValue() }); + } + sourceMapSerialiseContent(s) { + return s.toValue(); + } + dataStructureSerialiseContent(s) { + return [this.serialiseContent(s.content)]; + } + enumSerialiseAttributes(s) { + const o = s.attributes.clone(), + i = o.remove('enumerations') || new this.namespace.elements.Array([]), + a = o.get('default'); + let u = o.get('samples') || new this.namespace.elements.Array([]); + if ( + (a && + a.content && + (a.content.attributes && a.content.attributes.remove('typeAttributes'), + o.set('default', new this.namespace.elements.Array([a.content]))), + u.forEach((s) => { + s.content && s.content.element && s.content.attributes.remove('typeAttributes'); + }), + s.content && 0 !== i.length && u.unshift(s.content), + (u = u.map((s) => + s instanceof this.namespace.elements.Array + ? [s] + : new this.namespace.elements.Array([s.content]) + )), + u.length && o.set('samples', u), + o.length > 0) + ) + return this.serialiseObject(o); + } + enumSerialiseContent(s) { + if (s._attributes) { + const o = s.attributes.get('enumerations'); + if (o && o.length > 0) + return o.content.map((s) => { + const o = s.clone(); + return (o.attributes.remove('typeAttributes'), this.serialise(o)); + }); + } + if (s.content) { + const o = s.content.clone(); + return (o.attributes.remove('typeAttributes'), [this.serialise(o)]); + } + return []; + } + deserialise(s) { + if ('string' == typeof s) return new this.namespace.elements.String(s); + if ('number' == typeof s) return new this.namespace.elements.Number(s); + if ('boolean' == typeof s) return new this.namespace.elements.Boolean(s); + if (null === s) return new this.namespace.elements.Null(); + if (Array.isArray(s)) + return new this.namespace.elements.Array(s.map(this.deserialise, this)); + const o = this.namespace.getElementClass(s.element), + i = new o(); + (i.element !== s.element && (i.element = s.element), + s.meta && this.deserialiseObject(s.meta, i.meta), + s.attributes && this.deserialiseObject(s.attributes, i.attributes)); + const a = this.deserialiseContent(s.content); + if (((void 0 === a && null !== i.content) || (i.content = a), 'enum' === i.element)) { + i.content && i.attributes.set('enumerations', i.content); + let s = i.attributes.get('samples'); + if ((i.attributes.remove('samples'), s)) { + const a = s; + ((s = new this.namespace.elements.Array()), + a.forEach((a) => { + a.forEach((a) => { + const u = new o(a); + ((u.element = i.element), s.push(u)); + }); + })); + const u = s.shift(); + ((i.content = u ? u.content : void 0), i.attributes.set('samples', s)); + } else i.content = void 0; + let a = i.attributes.get('default'); + if (a && a.length > 0) { + a = a.get(0); + const s = new o(a); + ((s.element = i.element), i.attributes.set('default', s)); + } + } else if ('dataStructure' === i.element && Array.isArray(i.content)) + [i.content] = i.content; + else if ('category' === i.element) { + const s = i.attributes.get('meta'); + s && (i.attributes.set('metadata', s), i.attributes.remove('meta')); + } else + 'member' === i.element && + i.key && + i.key._attributes && + i.key._attributes.getValue('variable') && + (i.attributes.set('variable', i.key.attributes.get('variable')), + i.key.attributes.remove('variable')); + return i; + } + serialiseContent(s) { + if (s instanceof this.namespace.elements.Element) return this.serialise(s); + if (s instanceof this.namespace.KeyValuePair) { + const o = { key: this.serialise(s.key) }; + return (s.value && (o.value = this.serialise(s.value)), o); + } + return s && s.map ? s.map(this.serialise, this) : s; + } + deserialiseContent(s) { + if (s) { + if (s.element) return this.deserialise(s); + if (s.key) { + const o = new this.namespace.KeyValuePair(this.deserialise(s.key)); + return (s.value && (o.value = this.deserialise(s.value)), o); + } + if (s.map) return s.map(this.deserialise, this); + } + return s; + } + shouldRefract(s) { + return ( + !!( + (s._attributes && s.attributes.keys().length) || + (s._meta && s.meta.keys().length) + ) || + ('enum' !== s.element && (s.element !== s.primitive() || 'member' === s.element)) + ); + } + convertKeyToRefract(s, o) { + return this.shouldRefract(o) + ? this.serialise(o) + : 'enum' === o.element + ? this.serialiseEnum(o) + : 'array' === o.element + ? o.map((o) => + this.shouldRefract(o) || 'default' === s + ? this.serialise(o) + : 'array' === o.element || 'object' === o.element || 'enum' === o.element + ? o.children.map((s) => this.serialise(s)) + : o.toValue() + ) + : 'object' === o.element + ? (o.content || []).map(this.serialise, this) + : o.toValue(); + } + serialiseEnum(s) { + return s.children.map((s) => this.serialise(s)); + } + serialiseObject(s) { + const o = {}; + return ( + s.forEach((s, i) => { + if (s) { + const a = i.toValue(); + o[a] = this.convertKeyToRefract(a, s); + } + }), + o + ); + } + deserialiseObject(s, o) { + Object.keys(s).forEach((i) => { + o.set(i, this.deserialise(s[i])); + }); + } + }; + }, + 85105(s) { + s.exports = class JSONSerialiser { + constructor(s) { + this.namespace = s || new this.Namespace(); + } + serialise(s) { + if (!(s instanceof this.namespace.elements.Element)) + throw new TypeError(`Given element \`${s}\` is not an Element instance`); + const o = { element: s.element }; + (s._meta && s._meta.length > 0 && (o.meta = this.serialiseObject(s.meta)), + s._attributes && + s._attributes.length > 0 && + (o.attributes = this.serialiseObject(s.attributes))); + const i = this.serialiseContent(s.content); + return (void 0 !== i && (o.content = i), o); + } + deserialise(s) { + if (!s.element) + throw new Error('Given value is not an object containing an element name'); + const o = new (this.namespace.getElementClass(s.element))(); + (o.element !== s.element && (o.element = s.element), + s.meta && this.deserialiseObject(s.meta, o.meta), + s.attributes && this.deserialiseObject(s.attributes, o.attributes)); + const i = this.deserialiseContent(s.content); + return ((void 0 === i && null !== o.content) || (o.content = i), o); + } + serialiseContent(s) { + if (s instanceof this.namespace.elements.Element) return this.serialise(s); + if (s instanceof this.namespace.KeyValuePair) { + const o = { key: this.serialise(s.key) }; + return (s.value && (o.value = this.serialise(s.value)), o); + } + if (s && s.map) { + if (0 === s.length) return; + return s.map(this.serialise, this); + } + return s; + } + deserialiseContent(s) { + if (s) { + if (s.element) return this.deserialise(s); + if (s.key) { + const o = new this.namespace.KeyValuePair(this.deserialise(s.key)); + return (s.value && (o.value = this.deserialise(s.value)), o); + } + if (s.map) return s.map(this.deserialise, this); + } + return s; + } + serialiseObject(s) { + const o = {}; + if ( + (s.forEach((s, i) => { + s && (o[i.toValue()] = this.serialise(s)); + }), + 0 !== Object.keys(o).length) + ) + return o; + } + deserialiseObject(s, o) { + Object.keys(s).forEach((i) => { + o.set(i, this.deserialise(s[i])); + }); + } + }; + }, + 76578(s) { + 'use strict'; + s.exports = [ + 'Float16Array', + 'Float32Array', + 'Float64Array', + 'Int8Array', + 'Int16Array', + 'Int32Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Uint16Array', + 'Uint32Array', + 'BigInt64Array', + 'BigUint64Array' + ]; + }, + 65606(s) { + var o, + i, + a = (s.exports = {}); + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined'); + } + function runTimeout(s) { + if (o === setTimeout) return setTimeout(s, 0); + if ((o === defaultSetTimout || !o) && setTimeout) + return ((o = setTimeout), setTimeout(s, 0)); + try { + return o(s, 0); + } catch (i) { + try { + return o.call(null, s, 0); + } catch (i) { + return o.call(this, s, 0); + } + } + } + !(function () { + try { + o = 'function' == typeof setTimeout ? setTimeout : defaultSetTimout; + } catch (s) { + o = defaultSetTimout; + } + try { + i = 'function' == typeof clearTimeout ? clearTimeout : defaultClearTimeout; + } catch (s) { + i = defaultClearTimeout; + } + })(); + var u, + _ = [], + w = !1, + x = -1; + function cleanUpNextTick() { + w && u && ((w = !1), u.length ? (_ = u.concat(_)) : (x = -1), _.length && drainQueue()); + } + function drainQueue() { + if (!w) { + var s = runTimeout(cleanUpNextTick); + w = !0; + for (var o = _.length; o; ) { + for (u = _, _ = []; ++x < o; ) u && u[x].run(); + ((x = -1), (o = _.length)); + } + ((u = null), + (w = !1), + (function runClearTimeout(s) { + if (i === clearTimeout) return clearTimeout(s); + if ((i === defaultClearTimeout || !i) && clearTimeout) + return ((i = clearTimeout), clearTimeout(s)); + try { + return i(s); + } catch (o) { + try { + return i.call(null, s); + } catch (o) { + return i.call(this, s); + } + } + })(s)); + } + } + function Item(s, o) { + ((this.fun = s), (this.array = o)); + } + function noop() {} + ((a.nextTick = function (s) { + var o = new Array(arguments.length - 1); + if (arguments.length > 1) + for (var i = 1; i < arguments.length; i++) o[i - 1] = arguments[i]; + (_.push(new Item(s, o)), 1 !== _.length || w || runTimeout(drainQueue)); + }), + (Item.prototype.run = function () { + this.fun.apply(null, this.array); + }), + (a.title = 'browser'), + (a.browser = !0), + (a.env = {}), + (a.argv = []), + (a.version = ''), + (a.versions = {}), + (a.on = noop), + (a.addListener = noop), + (a.once = noop), + (a.off = noop), + (a.removeListener = noop), + (a.removeAllListeners = noop), + (a.emit = noop), + (a.prependListener = noop), + (a.prependOnceListener = noop), + (a.listeners = function (s) { + return []; + }), + (a.binding = function (s) { + throw new Error('process.binding is not supported'); + }), + (a.cwd = function () { + return '/'; + }), + (a.chdir = function (s) { + throw new Error('process.chdir is not supported'); + }), + (a.umask = function () { + return 0; + })); + }, + 2694(s, o, i) { + 'use strict'; + var a = i(6925); + function emptyFunction() {} + function emptyFunctionWithReset() {} + ((emptyFunctionWithReset.resetWarningCache = emptyFunction), + (s.exports = function () { + function shim(s, o, i, u, _, w) { + if (w !== a) { + var x = new Error( + 'Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types' + ); + throw ((x.name = 'Invariant Violation'), x); + } + } + function getShim() { + return shim; + } + shim.isRequired = shim; + var s = { + array: shim, + bigint: shim, + bool: shim, + func: shim, + number: shim, + object: shim, + string: shim, + symbol: shim, + any: shim, + arrayOf: getShim, + element: shim, + elementType: shim, + instanceOf: getShim, + node: shim, + objectOf: getShim, + oneOf: getShim, + oneOfType: getShim, + shape: getShim, + exact: getShim, + checkPropTypes: emptyFunctionWithReset, + resetWarningCache: emptyFunction + }; + return ((s.PropTypes = s), s); + })); + }, + 5556(s, o, i) { + s.exports = i(2694)(); + }, + 6925(s) { + 'use strict'; + s.exports = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + }, + 73992(s, o) { + 'use strict'; + var i = Object.prototype.hasOwnProperty; + function decode(s) { + try { + return decodeURIComponent(s.replace(/\+/g, ' ')); + } catch (s) { + return null; + } + } + function encode(s) { + try { + return encodeURIComponent(s); + } catch (s) { + return null; + } + } + ((o.stringify = function querystringify(s, o) { + o = o || ''; + var a, + u, + _ = []; + for (u in ('string' != typeof o && (o = '?'), s)) + if (i.call(s, u)) { + if ( + ((a = s[u]) || (null != a && !isNaN(a)) || (a = ''), + (u = encode(u)), + (a = encode(a)), + null === u || null === a) + ) + continue; + _.push(u + '=' + a); + } + return _.length ? o + _.join('&') : ''; + }), + (o.parse = function querystring(s) { + for (var o, i = /([^=?#&]+)=?([^&]*)/g, a = {}; (o = i.exec(s)); ) { + var u = decode(o[1]), + _ = decode(o[2]); + null === u || null === _ || u in a || (a[u] = _); + } + return a; + })); + }, + 41859(s, o, i) { + const a = i(27096), + u = i(78004), + _ = a.types; + s.exports = class RandExp { + constructor(s, o) { + if ((this._setDefaults(s), s instanceof RegExp)) + ((this.ignoreCase = s.ignoreCase), (this.multiline = s.multiline), (s = s.source)); + else { + if ('string' != typeof s) throw new Error('Expected a regexp or string'); + ((this.ignoreCase = o && -1 !== o.indexOf('i')), + (this.multiline = o && -1 !== o.indexOf('m'))); + } + this.tokens = a(s); + } + _setDefaults(s) { + ((this.max = + null != s.max + ? s.max + : null != RandExp.prototype.max + ? RandExp.prototype.max + : 100), + (this.defaultRange = s.defaultRange ? s.defaultRange : this.defaultRange.clone()), + s.randInt && (this.randInt = s.randInt)); + } + gen() { + return this._gen(this.tokens, []); + } + _gen(s, o) { + var i, a, u, w, x; + switch (s.type) { + case _.ROOT: + case _.GROUP: + if (s.followedBy || s.notFollowedBy) return ''; + for ( + s.remember && void 0 === s.groupNumber && (s.groupNumber = o.push(null) - 1), + a = '', + w = 0, + x = (i = s.options ? this._randSelect(s.options) : s.stack).length; + w < x; + w++ + ) + a += this._gen(i[w], o); + return (s.remember && (o[s.groupNumber] = a), a); + case _.POSITION: + return ''; + case _.SET: + var C = this._expand(s); + return C.length ? String.fromCharCode(this._randSelect(C)) : ''; + case _.REPETITION: + for ( + u = this.randInt(s.min, s.max === 1 / 0 ? s.min + this.max : s.max), + a = '', + w = 0; + w < u; + w++ + ) + a += this._gen(s.value, o); + return a; + case _.REFERENCE: + return o[s.value - 1] || ''; + case _.CHAR: + var j = + this.ignoreCase && this._randBool() ? this._toOtherCase(s.value) : s.value; + return String.fromCharCode(j); + } + } + _toOtherCase(s) { + return s + (97 <= s && s <= 122 ? -32 : 65 <= s && s <= 90 ? 32 : 0); + } + _randBool() { + return !this.randInt(0, 1); + } + _randSelect(s) { + return s instanceof u + ? s.index(this.randInt(0, s.length - 1)) + : s[this.randInt(0, s.length - 1)]; + } + _expand(s) { + if (s.type === a.types.CHAR) return new u(s.value); + if (s.type === a.types.RANGE) return new u(s.from, s.to); + { + let o = new u(); + for (let i = 0; i < s.set.length; i++) { + let a = this._expand(s.set[i]); + if ((o.add(a), this.ignoreCase)) + for (let s = 0; s < a.length; s++) { + let i = a.index(s), + u = this._toOtherCase(i); + i !== u && o.add(u); + } + } + return s.not + ? this.defaultRange.clone().subtract(o) + : this.defaultRange.clone().intersect(o); + } + } + randInt(s, o) { + return s + Math.floor(Math.random() * (1 + o - s)); + } + get defaultRange() { + return (this._range = this._range || new u(32, 126)); + } + set defaultRange(s) { + this._range = s; + } + static randexp(s, o) { + var i; + return ( + 'string' == typeof s && (s = new RegExp(s, o)), + void 0 === s._randexp + ? ((i = new RandExp(s, o)), (s._randexp = i)) + : (i = s._randexp)._setDefaults(s), + i.gen() + ); + } + static sugar() { + RegExp.prototype.gen = function () { + return RandExp.randexp(this); + }; + } + }; + }, + 53209(s, o, i) { + 'use strict'; + var a = i(65606), + u = 65536, + _ = 4294967295; + var w = i(92861).Buffer, + x = i.g.crypto || i.g.msCrypto; + x && x.getRandomValues + ? (s.exports = function randomBytes(s, o) { + if (s > _) throw new RangeError('requested too many random bytes'); + var i = w.allocUnsafe(s); + if (s > 0) + if (s > u) for (var C = 0; C < s; C += u) x.getRandomValues(i.slice(C, C + u)); + else x.getRandomValues(i); + if ('function' == typeof o) + return a.nextTick(function () { + o(null, i); + }); + return i; + }) + : (s.exports = function oldBrowser() { + throw new Error( + 'Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11' + ); + }); + }, + 25264(s, o, i) { + 'use strict'; + function _typeof(s) { + return ( + (_typeof = + 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator + ? function (s) { + return typeof s; + } + : function (s) { + return s && + 'function' == typeof Symbol && + s.constructor === Symbol && + s !== Symbol.prototype + ? 'symbol' + : typeof s; + }), + _typeof(s) + ); + } + (Object.defineProperty(o, '__esModule', { value: !0 }), (o.CopyToClipboard = void 0)); + var a = _interopRequireDefault(i(96540)), + u = _interopRequireDefault(i(17965)), + _ = ['text', 'onCopy', 'options', 'children']; + function _interopRequireDefault(s) { + return s && s.__esModule ? s : { default: s }; + } + function ownKeys(s, o) { + var i = Object.keys(s); + if (Object.getOwnPropertySymbols) { + var a = Object.getOwnPropertySymbols(s); + (o && + (a = a.filter(function (o) { + return Object.getOwnPropertyDescriptor(s, o).enumerable; + })), + i.push.apply(i, a)); + } + return i; + } + function _objectSpread(s) { + for (var o = 1; o < arguments.length; o++) { + var i = null != arguments[o] ? arguments[o] : {}; + o % 2 + ? ownKeys(Object(i), !0).forEach(function (o) { + _defineProperty(s, o, i[o]); + }) + : Object.getOwnPropertyDescriptors + ? Object.defineProperties(s, Object.getOwnPropertyDescriptors(i)) + : ownKeys(Object(i)).forEach(function (o) { + Object.defineProperty(s, o, Object.getOwnPropertyDescriptor(i, o)); + }); + } + return s; + } + function _objectWithoutProperties(s, o) { + if (null == s) return {}; + var i, + a, + u = (function _objectWithoutPropertiesLoose(s, o) { + if (null == s) return {}; + var i, + a, + u = {}, + _ = Object.keys(s); + for (a = 0; a < _.length; a++) ((i = _[a]), o.indexOf(i) >= 0 || (u[i] = s[i])); + return u; + })(s, o); + if (Object.getOwnPropertySymbols) { + var _ = Object.getOwnPropertySymbols(s); + for (a = 0; a < _.length; a++) + ((i = _[a]), + o.indexOf(i) >= 0 || + (Object.prototype.propertyIsEnumerable.call(s, i) && (u[i] = s[i]))); + } + return u; + } + function _defineProperties(s, o) { + for (var i = 0; i < o.length; i++) { + var a = o[i]; + ((a.enumerable = a.enumerable || !1), + (a.configurable = !0), + 'value' in a && (a.writable = !0), + Object.defineProperty(s, a.key, a)); + } + } + function _setPrototypeOf(s, o) { + return ( + (_setPrototypeOf = + Object.setPrototypeOf || + function _setPrototypeOf(s, o) { + return ((s.__proto__ = o), s); + }), + _setPrototypeOf(s, o) + ); + } + function _createSuper(s) { + var o = (function _isNativeReflectConstruct() { + if ('undefined' == typeof Reflect || !Reflect.construct) return !1; + if (Reflect.construct.sham) return !1; + if ('function' == typeof Proxy) return !0; + try { + return ( + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})), + !0 + ); + } catch (s) { + return !1; + } + })(); + return function _createSuperInternal() { + var i, + a = _getPrototypeOf(s); + if (o) { + var u = _getPrototypeOf(this).constructor; + i = Reflect.construct(a, arguments, u); + } else i = a.apply(this, arguments); + return (function _possibleConstructorReturn(s, o) { + if (o && ('object' === _typeof(o) || 'function' == typeof o)) return o; + if (void 0 !== o) + throw new TypeError('Derived constructors may only return object or undefined'); + return _assertThisInitialized(s); + })(this, i); + }; + } + function _assertThisInitialized(s) { + if (void 0 === s) + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return s; + } + function _getPrototypeOf(s) { + return ( + (_getPrototypeOf = Object.setPrototypeOf + ? Object.getPrototypeOf + : function _getPrototypeOf(s) { + return s.__proto__ || Object.getPrototypeOf(s); + }), + _getPrototypeOf(s) + ); + } + function _defineProperty(s, o, i) { + return ( + o in s + ? Object.defineProperty(s, o, { + value: i, + enumerable: !0, + configurable: !0, + writable: !0 + }) + : (s[o] = i), + s + ); + } + var w = (function (s) { + !(function _inherits(s, o) { + if ('function' != typeof o && null !== o) + throw new TypeError('Super expression must either be null or a function'); + ((s.prototype = Object.create(o && o.prototype, { + constructor: { value: s, writable: !0, configurable: !0 } + })), + Object.defineProperty(s, 'prototype', { writable: !1 }), + o && _setPrototypeOf(s, o)); + })(CopyToClipboard, s); + var o = _createSuper(CopyToClipboard); + function CopyToClipboard() { + var s; + !(function _classCallCheck(s, o) { + if (!(s instanceof o)) throw new TypeError('Cannot call a class as a function'); + })(this, CopyToClipboard); + for (var i = arguments.length, _ = new Array(i), w = 0; w < i; w++) + _[w] = arguments[w]; + return ( + _defineProperty( + _assertThisInitialized((s = o.call.apply(o, [this].concat(_)))), + 'onClick', + function (o) { + var i = s.props, + _ = i.text, + w = i.onCopy, + x = i.children, + C = i.options, + j = a.default.Children.only(x), + L = (0, u.default)(_, C); + (w && w(_, L), + j && j.props && 'function' == typeof j.props.onClick && j.props.onClick(o)); + } + ), + s + ); + } + return ( + (function _createClass(s, o, i) { + return ( + o && _defineProperties(s.prototype, o), + i && _defineProperties(s, i), + Object.defineProperty(s, 'prototype', { writable: !1 }), + s + ); + })(CopyToClipboard, [ + { + key: 'render', + value: function render() { + var s = this.props, + o = (s.text, s.onCopy, s.options, s.children), + i = _objectWithoutProperties(s, _), + u = a.default.Children.only(o); + return a.default.cloneElement( + u, + _objectSpread(_objectSpread({}, i), {}, { onClick: this.onClick }) + ); + } + } + ]), + CopyToClipboard + ); + })(a.default.PureComponent); + ((o.CopyToClipboard = w), + _defineProperty(w, 'defaultProps', { onCopy: void 0, options: void 0 })); + }, + 59399(s, o, i) { + 'use strict'; + var a = i(25264).CopyToClipboard; + ((a.CopyToClipboard = a), (s.exports = a)); + }, + 81214(s, o, i) { + 'use strict'; + function _typeof(s) { + return ( + (_typeof = + 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator + ? function (s) { + return typeof s; + } + : function (s) { + return s && + 'function' == typeof Symbol && + s.constructor === Symbol && + s !== Symbol.prototype + ? 'symbol' + : typeof s; + }), + _typeof(s) + ); + } + (Object.defineProperty(o, '__esModule', { value: !0 }), (o.DebounceInput = void 0)); + var a = _interopRequireDefault(i(96540)), + u = _interopRequireDefault(i(20181)), + _ = [ + 'element', + 'onChange', + 'value', + 'minLength', + 'debounceTimeout', + 'forceNotifyByEnter', + 'forceNotifyOnBlur', + 'onKeyDown', + 'onBlur', + 'inputRef' + ]; + function _interopRequireDefault(s) { + return s && s.__esModule ? s : { default: s }; + } + function _objectWithoutProperties(s, o) { + if (null == s) return {}; + var i, + a, + u = (function _objectWithoutPropertiesLoose(s, o) { + if (null == s) return {}; + var i, + a, + u = {}, + _ = Object.keys(s); + for (a = 0; a < _.length; a++) ((i = _[a]), o.indexOf(i) >= 0 || (u[i] = s[i])); + return u; + })(s, o); + if (Object.getOwnPropertySymbols) { + var _ = Object.getOwnPropertySymbols(s); + for (a = 0; a < _.length; a++) + ((i = _[a]), + o.indexOf(i) >= 0 || + (Object.prototype.propertyIsEnumerable.call(s, i) && (u[i] = s[i]))); + } + return u; + } + function ownKeys(s, o) { + var i = Object.keys(s); + if (Object.getOwnPropertySymbols) { + var a = Object.getOwnPropertySymbols(s); + (o && + (a = a.filter(function (o) { + return Object.getOwnPropertyDescriptor(s, o).enumerable; + })), + i.push.apply(i, a)); + } + return i; + } + function _objectSpread(s) { + for (var o = 1; o < arguments.length; o++) { + var i = null != arguments[o] ? arguments[o] : {}; + o % 2 + ? ownKeys(Object(i), !0).forEach(function (o) { + _defineProperty(s, o, i[o]); + }) + : Object.getOwnPropertyDescriptors + ? Object.defineProperties(s, Object.getOwnPropertyDescriptors(i)) + : ownKeys(Object(i)).forEach(function (o) { + Object.defineProperty(s, o, Object.getOwnPropertyDescriptor(i, o)); + }); + } + return s; + } + function _defineProperties(s, o) { + for (var i = 0; i < o.length; i++) { + var a = o[i]; + ((a.enumerable = a.enumerable || !1), + (a.configurable = !0), + 'value' in a && (a.writable = !0), + Object.defineProperty(s, a.key, a)); + } + } + function _setPrototypeOf(s, o) { + return ( + (_setPrototypeOf = + Object.setPrototypeOf || + function _setPrototypeOf(s, o) { + return ((s.__proto__ = o), s); + }), + _setPrototypeOf(s, o) + ); + } + function _createSuper(s) { + var o = (function _isNativeReflectConstruct() { + if ('undefined' == typeof Reflect || !Reflect.construct) return !1; + if (Reflect.construct.sham) return !1; + if ('function' == typeof Proxy) return !0; + try { + return ( + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})), + !0 + ); + } catch (s) { + return !1; + } + })(); + return function _createSuperInternal() { + var i, + a = _getPrototypeOf(s); + if (o) { + var u = _getPrototypeOf(this).constructor; + i = Reflect.construct(a, arguments, u); + } else i = a.apply(this, arguments); + return (function _possibleConstructorReturn(s, o) { + if (o && ('object' === _typeof(o) || 'function' == typeof o)) return o; + if (void 0 !== o) + throw new TypeError('Derived constructors may only return object or undefined'); + return _assertThisInitialized(s); + })(this, i); + }; + } + function _assertThisInitialized(s) { + if (void 0 === s) + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return s; + } + function _getPrototypeOf(s) { + return ( + (_getPrototypeOf = Object.setPrototypeOf + ? Object.getPrototypeOf + : function _getPrototypeOf(s) { + return s.__proto__ || Object.getPrototypeOf(s); + }), + _getPrototypeOf(s) + ); + } + function _defineProperty(s, o, i) { + return ( + o in s + ? Object.defineProperty(s, o, { + value: i, + enumerable: !0, + configurable: !0, + writable: !0 + }) + : (s[o] = i), + s + ); + } + var w = (function (s) { + !(function _inherits(s, o) { + if ('function' != typeof o && null !== o) + throw new TypeError('Super expression must either be null or a function'); + ((s.prototype = Object.create(o && o.prototype, { + constructor: { value: s, writable: !0, configurable: !0 } + })), + Object.defineProperty(s, 'prototype', { writable: !1 }), + o && _setPrototypeOf(s, o)); + })(DebounceInput, s); + var o = _createSuper(DebounceInput); + function DebounceInput(s) { + var i; + (!(function _classCallCheck(s, o) { + if (!(s instanceof o)) throw new TypeError('Cannot call a class as a function'); + })(this, DebounceInput), + _defineProperty( + _assertThisInitialized((i = o.call(this, s))), + 'onChange', + function (s) { + s.persist(); + var o = i.state.value, + a = i.props.minLength; + i.setState({ value: s.target.value }, function () { + var u = i.state.value; + u.length >= a + ? i.notify(s) + : o.length > u.length && + i.notify( + _objectSpread( + _objectSpread({}, s), + {}, + { + target: _objectSpread( + _objectSpread({}, s.target), + {}, + { value: '' } + ) + } + ) + ); + }); + } + ), + _defineProperty(_assertThisInitialized(i), 'onKeyDown', function (s) { + 'Enter' === s.key && i.forceNotify(s); + var o = i.props.onKeyDown; + o && (s.persist(), o(s)); + }), + _defineProperty(_assertThisInitialized(i), 'onBlur', function (s) { + i.forceNotify(s); + var o = i.props.onBlur; + o && (s.persist(), o(s)); + }), + _defineProperty(_assertThisInitialized(i), 'createNotifier', function (s) { + if (s < 0) + i.notify = function () { + return null; + }; + else if (0 === s) i.notify = i.doNotify; + else { + var o = (0, u.default)(function (s) { + ((i.isDebouncing = !1), i.doNotify(s)); + }, s); + ((i.notify = function (s) { + ((i.isDebouncing = !0), o(s)); + }), + (i.flush = function () { + return o.flush(); + }), + (i.cancel = function () { + ((i.isDebouncing = !1), o.cancel()); + })); + } + }), + _defineProperty(_assertThisInitialized(i), 'doNotify', function () { + i.props.onChange.apply(void 0, arguments); + }), + _defineProperty(_assertThisInitialized(i), 'forceNotify', function (s) { + var o = i.props.debounceTimeout; + if (i.isDebouncing || !(o > 0)) { + i.cancel && i.cancel(); + var a = i.state.value, + u = i.props.minLength; + a.length >= u + ? i.doNotify(s) + : i.doNotify( + _objectSpread( + _objectSpread({}, s), + {}, + { target: _objectSpread(_objectSpread({}, s.target), {}, { value: a }) } + ) + ); + } + }), + (i.isDebouncing = !1), + (i.state = { value: void 0 === s.value || null === s.value ? '' : s.value })); + var a = i.props.debounceTimeout; + return (i.createNotifier(a), i); + } + return ( + (function _createClass(s, o, i) { + return ( + o && _defineProperties(s.prototype, o), + i && _defineProperties(s, i), + Object.defineProperty(s, 'prototype', { writable: !1 }), + s + ); + })(DebounceInput, [ + { + key: 'componentDidUpdate', + value: function componentDidUpdate(s) { + if (!this.isDebouncing) { + var o = this.props, + i = o.value, + a = o.debounceTimeout, + u = s.debounceTimeout, + _ = s.value, + w = this.state.value; + (void 0 !== i && _ !== i && w !== i && this.setState({ value: i }), + a !== u && this.createNotifier(a)); + } + } + }, + { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.flush && this.flush(); + } + }, + { + key: 'render', + value: function render() { + var s, + o, + i = this.props, + u = i.element, + w = + (i.onChange, i.value, i.minLength, i.debounceTimeout, i.forceNotifyByEnter), + x = i.forceNotifyOnBlur, + C = i.onKeyDown, + j = i.onBlur, + L = i.inputRef, + B = _objectWithoutProperties(i, _), + $ = this.state.value; + ((s = w ? { onKeyDown: this.onKeyDown } : C ? { onKeyDown: C } : {}), + (o = x ? { onBlur: this.onBlur } : j ? { onBlur: j } : {})); + var U = L ? { ref: L } : {}; + return a.default.createElement( + u, + _objectSpread( + _objectSpread( + _objectSpread( + _objectSpread({}, B), + {}, + { onChange: this.onChange, value: $ }, + s + ), + o + ), + U + ) + ); + } + } + ]), + DebounceInput + ); + })(a.default.PureComponent); + ((o.DebounceInput = w), + _defineProperty(w, 'defaultProps', { + element: 'input', + type: 'text', + onKeyDown: void 0, + onBlur: void 0, + value: void 0, + minLength: 0, + debounceTimeout: 100, + forceNotifyByEnter: !0, + forceNotifyOnBlur: !0, + inputRef: void 0 + })); + }, + 24677(s, o, i) { + 'use strict'; + var a = i(81214).DebounceInput; + ((a.DebounceInput = a), (s.exports = a)); + }, + 22551(s, o, i) { + 'use strict'; + var a = i(96540), + u = i(69982); + function p(s) { + for ( + var o = 'https://reactjs.org/docs/error-decoder.html?invariant=' + s, i = 1; + i < arguments.length; + i++ + ) + o += '&args[]=' + encodeURIComponent(arguments[i]); + return ( + 'Minified React error #' + + s + + '; visit ' + + o + + ' for the full message or use the non-minified dev environment for full errors and additional helpful warnings.' + ); + } + var _ = new Set(), + w = {}; + function fa(s, o) { + (ha(s, o), ha(s + 'Capture', o)); + } + function ha(s, o) { + for (w[s] = o, s = 0; s < o.length; s++) _.add(o[s]); + } + var x = !( + 'undefined' == typeof window || + void 0 === window.document || + void 0 === window.document.createElement + ), + C = Object.prototype.hasOwnProperty, + j = + /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, + L = {}, + B = {}; + function v(s, o, i, a, u, _, w) { + ((this.acceptsBooleans = 2 === o || 3 === o || 4 === o), + (this.attributeName = a), + (this.attributeNamespace = u), + (this.mustUseProperty = i), + (this.propertyName = s), + (this.type = o), + (this.sanitizeURL = _), + (this.removeEmptyString = w)); + } + var $ = {}; + ('children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style' + .split(' ') + .forEach(function (s) { + $[s] = new v(s, 0, !1, s, null, !1, !1); + }), + [ + ['acceptCharset', 'accept-charset'], + ['className', 'class'], + ['htmlFor', 'for'], + ['httpEquiv', 'http-equiv'] + ].forEach(function (s) { + var o = s[0]; + $[o] = new v(o, 1, !1, s[1], null, !1, !1); + }), + ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (s) { + $[s] = new v(s, 2, !1, s.toLowerCase(), null, !1, !1); + }), + ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach( + function (s) { + $[s] = new v(s, 2, !1, s, null, !1, !1); + } + ), + 'allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope' + .split(' ') + .forEach(function (s) { + $[s] = new v(s, 3, !1, s.toLowerCase(), null, !1, !1); + }), + ['checked', 'multiple', 'muted', 'selected'].forEach(function (s) { + $[s] = new v(s, 3, !0, s, null, !1, !1); + }), + ['capture', 'download'].forEach(function (s) { + $[s] = new v(s, 4, !1, s, null, !1, !1); + }), + ['cols', 'rows', 'size', 'span'].forEach(function (s) { + $[s] = new v(s, 6, !1, s, null, !1, !1); + }), + ['rowSpan', 'start'].forEach(function (s) { + $[s] = new v(s, 5, !1, s.toLowerCase(), null, !1, !1); + })); + var U = /[\-:]([a-z])/g; + function sa(s) { + return s[1].toUpperCase(); + } + function ta(s, o, i, a) { + var u = $.hasOwnProperty(o) ? $[o] : null; + (null !== u + ? 0 !== u.type + : a || + !(2 < o.length) || + ('o' !== o[0] && 'O' !== o[0]) || + ('n' !== o[1] && 'N' !== o[1])) && + ((function qa(s, o, i, a) { + if ( + null == o || + (function pa(s, o, i, a) { + if (null !== i && 0 === i.type) return !1; + switch (typeof o) { + case 'function': + case 'symbol': + return !0; + case 'boolean': + return ( + !a && + (null !== i + ? !i.acceptsBooleans + : 'data-' !== (s = s.toLowerCase().slice(0, 5)) && 'aria-' !== s) + ); + default: + return !1; + } + })(s, o, i, a) + ) + return !0; + if (a) return !1; + if (null !== i) + switch (i.type) { + case 3: + return !o; + case 4: + return !1 === o; + case 5: + return isNaN(o); + case 6: + return isNaN(o) || 1 > o; + } + return !1; + })(o, i, u, a) && (i = null), + a || null === u + ? (function oa(s) { + return ( + !!C.call(B, s) || + (!C.call(L, s) && (j.test(s) ? (B[s] = !0) : ((L[s] = !0), !1))) + ); + })(o) && (null === i ? s.removeAttribute(o) : s.setAttribute(o, '' + i)) + : u.mustUseProperty + ? (s[u.propertyName] = null === i ? 3 !== u.type && '' : i) + : ((o = u.attributeName), + (a = u.attributeNamespace), + null === i + ? s.removeAttribute(o) + : ((i = 3 === (u = u.type) || (4 === u && !0 === i) ? '' : '' + i), + a ? s.setAttributeNS(a, o, i) : s.setAttribute(o, i)))); + } + ('accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height' + .split(' ') + .forEach(function (s) { + var o = s.replace(U, sa); + $[o] = new v(o, 1, !1, s, null, !1, !1); + }), + 'xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type' + .split(' ') + .forEach(function (s) { + var o = s.replace(U, sa); + $[o] = new v(o, 1, !1, s, 'http://www.w3.org/1999/xlink', !1, !1); + }), + ['xml:base', 'xml:lang', 'xml:space'].forEach(function (s) { + var o = s.replace(U, sa); + $[o] = new v(o, 1, !1, s, 'http://www.w3.org/XML/1998/namespace', !1, !1); + }), + ['tabIndex', 'crossOrigin'].forEach(function (s) { + $[s] = new v(s, 1, !1, s.toLowerCase(), null, !1, !1); + }), + ($.xlinkHref = new v( + 'xlinkHref', + 1, + !1, + 'xlink:href', + 'http://www.w3.org/1999/xlink', + !0, + !1 + )), + ['src', 'href', 'action', 'formAction'].forEach(function (s) { + $[s] = new v(s, 1, !1, s.toLowerCase(), null, !0, !0); + })); + var V = a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, + z = Symbol.for('react.element'), + Y = Symbol.for('react.portal'), + Z = Symbol.for('react.fragment'), + ee = Symbol.for('react.strict_mode'), + ie = Symbol.for('react.profiler'), + ae = Symbol.for('react.provider'), + ce = Symbol.for('react.context'), + le = Symbol.for('react.forward_ref'), + pe = Symbol.for('react.suspense'), + de = Symbol.for('react.suspense_list'), + fe = Symbol.for('react.memo'), + ye = Symbol.for('react.lazy'); + (Symbol.for('react.scope'), Symbol.for('react.debug_trace_mode')); + var be = Symbol.for('react.offscreen'); + (Symbol.for('react.legacy_hidden'), + Symbol.for('react.cache'), + Symbol.for('react.tracing_marker')); + var Se = Symbol.iterator; + function Ka(s) { + return null === s || 'object' != typeof s + ? null + : 'function' == typeof (s = (Se && s[Se]) || s['@@iterator']) + ? s + : null; + } + var _e, + we = Object.assign; + function Ma(s) { + if (void 0 === _e) + try { + throw Error(); + } catch (s) { + var o = s.stack.trim().match(/\n( *(at )?)/); + _e = (o && o[1]) || ''; + } + return '\n' + _e + s; + } + var xe = !1; + function Oa(s, o) { + if (!s || xe) return ''; + xe = !0; + var i = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + try { + if (o) + if ( + ((o = function () { + throw Error(); + }), + Object.defineProperty(o.prototype, 'props', { + set: function () { + throw Error(); + } + }), + 'object' == typeof Reflect && Reflect.construct) + ) { + try { + Reflect.construct(o, []); + } catch (s) { + var a = s; + } + Reflect.construct(s, [], o); + } else { + try { + o.call(); + } catch (s) { + a = s; + } + s.call(o.prototype); + } + else { + try { + throw Error(); + } catch (s) { + a = s; + } + s(); + } + } catch (o) { + if (o && a && 'string' == typeof o.stack) { + for ( + var u = o.stack.split('\n'), + _ = a.stack.split('\n'), + w = u.length - 1, + x = _.length - 1; + 1 <= w && 0 <= x && u[w] !== _[x]; + ) + x--; + for (; 1 <= w && 0 <= x; w--, x--) + if (u[w] !== _[x]) { + if (1 !== w || 1 !== x) + do { + if ((w--, 0 > --x || u[w] !== _[x])) { + var C = '\n' + u[w].replace(' at new ', ' at '); + return ( + s.displayName && + C.includes('') && + (C = C.replace('', s.displayName)), + C + ); + } + } while (1 <= w && 0 <= x); + break; + } + } + } finally { + ((xe = !1), (Error.prepareStackTrace = i)); + } + return (s = s ? s.displayName || s.name : '') ? Ma(s) : ''; + } + function Pa(s) { + switch (s.tag) { + case 5: + return Ma(s.type); + case 16: + return Ma('Lazy'); + case 13: + return Ma('Suspense'); + case 19: + return Ma('SuspenseList'); + case 0: + case 2: + case 15: + return (s = Oa(s.type, !1)); + case 11: + return (s = Oa(s.type.render, !1)); + case 1: + return (s = Oa(s.type, !0)); + default: + return ''; + } + } + function Qa(s) { + if (null == s) return null; + if ('function' == typeof s) return s.displayName || s.name || null; + if ('string' == typeof s) return s; + switch (s) { + case Z: + return 'Fragment'; + case Y: + return 'Portal'; + case ie: + return 'Profiler'; + case ee: + return 'StrictMode'; + case pe: + return 'Suspense'; + case de: + return 'SuspenseList'; + } + if ('object' == typeof s) + switch (s.$$typeof) { + case ce: + return (s.displayName || 'Context') + '.Consumer'; + case ae: + return (s._context.displayName || 'Context') + '.Provider'; + case le: + var o = s.render; + return ( + (s = s.displayName) || + (s = + '' !== (s = o.displayName || o.name || '') + ? 'ForwardRef(' + s + ')' + : 'ForwardRef'), + s + ); + case fe: + return null !== (o = s.displayName || null) ? o : Qa(s.type) || 'Memo'; + case ye: + ((o = s._payload), (s = s._init)); + try { + return Qa(s(o)); + } catch (s) {} + } + return null; + } + function Ra(s) { + var o = s.type; + switch (s.tag) { + case 24: + return 'Cache'; + case 9: + return (o.displayName || 'Context') + '.Consumer'; + case 10: + return (o._context.displayName || 'Context') + '.Provider'; + case 18: + return 'DehydratedFragment'; + case 11: + return ( + (s = (s = o.render).displayName || s.name || ''), + o.displayName || ('' !== s ? 'ForwardRef(' + s + ')' : 'ForwardRef') + ); + case 7: + return 'Fragment'; + case 5: + return o; + case 4: + return 'Portal'; + case 3: + return 'Root'; + case 6: + return 'Text'; + case 16: + return Qa(o); + case 8: + return o === ee ? 'StrictMode' : 'Mode'; + case 22: + return 'Offscreen'; + case 12: + return 'Profiler'; + case 21: + return 'Scope'; + case 13: + return 'Suspense'; + case 19: + return 'SuspenseList'; + case 25: + return 'TracingMarker'; + case 1: + case 0: + case 17: + case 2: + case 14: + case 15: + if ('function' == typeof o) return o.displayName || o.name || null; + if ('string' == typeof o) return o; + } + return null; + } + function Sa(s) { + switch (typeof s) { + case 'boolean': + case 'number': + case 'string': + case 'undefined': + case 'object': + return s; + default: + return ''; + } + } + function Ta(s) { + var o = s.type; + return ( + (s = s.nodeName) && 'input' === s.toLowerCase() && ('checkbox' === o || 'radio' === o) + ); + } + function Va(s) { + s._valueTracker || + (s._valueTracker = (function Ua(s) { + var o = Ta(s) ? 'checked' : 'value', + i = Object.getOwnPropertyDescriptor(s.constructor.prototype, o), + a = '' + s[o]; + if ( + !s.hasOwnProperty(o) && + void 0 !== i && + 'function' == typeof i.get && + 'function' == typeof i.set + ) { + var u = i.get, + _ = i.set; + return ( + Object.defineProperty(s, o, { + configurable: !0, + get: function () { + return u.call(this); + }, + set: function (s) { + ((a = '' + s), _.call(this, s)); + } + }), + Object.defineProperty(s, o, { enumerable: i.enumerable }), + { + getValue: function () { + return a; + }, + setValue: function (s) { + a = '' + s; + }, + stopTracking: function () { + ((s._valueTracker = null), delete s[o]); + } + } + ); + } + })(s)); + } + function Wa(s) { + if (!s) return !1; + var o = s._valueTracker; + if (!o) return !0; + var i = o.getValue(), + a = ''; + return ( + s && (a = Ta(s) ? (s.checked ? 'true' : 'false') : s.value), + (s = a) !== i && (o.setValue(s), !0) + ); + } + function Xa(s) { + if (void 0 === (s = s || ('undefined' != typeof document ? document : void 0))) + return null; + try { + return s.activeElement || s.body; + } catch (o) { + return s.body; + } + } + function Ya(s, o) { + var i = o.checked; + return we({}, o, { + defaultChecked: void 0, + defaultValue: void 0, + value: void 0, + checked: null != i ? i : s._wrapperState.initialChecked + }); + } + function Za(s, o) { + var i = null == o.defaultValue ? '' : o.defaultValue, + a = null != o.checked ? o.checked : o.defaultChecked; + ((i = Sa(null != o.value ? o.value : i)), + (s._wrapperState = { + initialChecked: a, + initialValue: i, + controlled: + 'checkbox' === o.type || 'radio' === o.type ? null != o.checked : null != o.value + })); + } + function ab(s, o) { + null != (o = o.checked) && ta(s, 'checked', o, !1); + } + function bb(s, o) { + ab(s, o); + var i = Sa(o.value), + a = o.type; + if (null != i) + 'number' === a + ? ((0 === i && '' === s.value) || s.value != i) && (s.value = '' + i) + : s.value !== '' + i && (s.value = '' + i); + else if ('submit' === a || 'reset' === a) return void s.removeAttribute('value'); + (o.hasOwnProperty('value') + ? cb(s, o.type, i) + : o.hasOwnProperty('defaultValue') && cb(s, o.type, Sa(o.defaultValue)), + null == o.checked && + null != o.defaultChecked && + (s.defaultChecked = !!o.defaultChecked)); + } + function db(s, o, i) { + if (o.hasOwnProperty('value') || o.hasOwnProperty('defaultValue')) { + var a = o.type; + if (!(('submit' !== a && 'reset' !== a) || (void 0 !== o.value && null !== o.value))) + return; + ((o = '' + s._wrapperState.initialValue), + i || o === s.value || (s.value = o), + (s.defaultValue = o)); + } + ('' !== (i = s.name) && (s.name = ''), + (s.defaultChecked = !!s._wrapperState.initialChecked), + '' !== i && (s.name = i)); + } + function cb(s, o, i) { + ('number' === o && Xa(s.ownerDocument) === s) || + (null == i + ? (s.defaultValue = '' + s._wrapperState.initialValue) + : s.defaultValue !== '' + i && (s.defaultValue = '' + i)); + } + var Pe = Array.isArray; + function fb(s, o, i, a) { + if (((s = s.options), o)) { + o = {}; + for (var u = 0; u < i.length; u++) o['$' + i[u]] = !0; + for (i = 0; i < s.length; i++) + ((u = o.hasOwnProperty('$' + s[i].value)), + s[i].selected !== u && (s[i].selected = u), + u && a && (s[i].defaultSelected = !0)); + } else { + for (i = '' + Sa(i), o = null, u = 0; u < s.length; u++) { + if (s[u].value === i) + return ((s[u].selected = !0), void (a && (s[u].defaultSelected = !0))); + null !== o || s[u].disabled || (o = s[u]); + } + null !== o && (o.selected = !0); + } + } + function gb(s, o) { + if (null != o.dangerouslySetInnerHTML) throw Error(p(91)); + return we({}, o, { + value: void 0, + defaultValue: void 0, + children: '' + s._wrapperState.initialValue + }); + } + function hb(s, o) { + var i = o.value; + if (null == i) { + if (((i = o.children), (o = o.defaultValue), null != i)) { + if (null != o) throw Error(p(92)); + if (Pe(i)) { + if (1 < i.length) throw Error(p(93)); + i = i[0]; + } + o = i; + } + (null == o && (o = ''), (i = o)); + } + s._wrapperState = { initialValue: Sa(i) }; + } + function ib(s, o) { + var i = Sa(o.value), + a = Sa(o.defaultValue); + (null != i && + ((i = '' + i) !== s.value && (s.value = i), + null == o.defaultValue && s.defaultValue !== i && (s.defaultValue = i)), + null != a && (s.defaultValue = '' + a)); + } + function jb(s) { + var o = s.textContent; + o === s._wrapperState.initialValue && '' !== o && null !== o && (s.value = o); + } + function kb(s) { + switch (s) { + case 'svg': + return 'http://www.w3.org/2000/svg'; + case 'math': + return 'http://www.w3.org/1998/Math/MathML'; + default: + return 'http://www.w3.org/1999/xhtml'; + } + } + function lb(s, o) { + return null == s || 'http://www.w3.org/1999/xhtml' === s + ? kb(o) + : 'http://www.w3.org/2000/svg' === s && 'foreignObject' === o + ? 'http://www.w3.org/1999/xhtml' + : s; + } + var Te, + Re, + $e = + ((Re = function (s, o) { + if ('http://www.w3.org/2000/svg' !== s.namespaceURI || 'innerHTML' in s) + s.innerHTML = o; + else { + for ( + (Te = Te || document.createElement('div')).innerHTML = + '' + o.valueOf().toString() + '', + o = Te.firstChild; + s.firstChild; + ) + s.removeChild(s.firstChild); + for (; o.firstChild; ) s.appendChild(o.firstChild); + } + }), + 'undefined' != typeof MSApp && MSApp.execUnsafeLocalFunction + ? function (s, o, i, a) { + MSApp.execUnsafeLocalFunction(function () { + return Re(s, o); + }); + } + : Re); + function ob(s, o) { + if (o) { + var i = s.firstChild; + if (i && i === s.lastChild && 3 === i.nodeType) return void (i.nodeValue = o); + } + s.textContent = o; + } + var qe = { + animationIterationCount: !0, + aspectRatio: !0, + borderImageOutset: !0, + borderImageSlice: !0, + borderImageWidth: !0, + boxFlex: !0, + boxFlexGroup: !0, + boxOrdinalGroup: !0, + columnCount: !0, + columns: !0, + flex: !0, + flexGrow: !0, + flexPositive: !0, + flexShrink: !0, + flexNegative: !0, + flexOrder: !0, + gridArea: !0, + gridRow: !0, + gridRowEnd: !0, + gridRowSpan: !0, + gridRowStart: !0, + gridColumn: !0, + gridColumnEnd: !0, + gridColumnSpan: !0, + gridColumnStart: !0, + fontWeight: !0, + lineClamp: !0, + lineHeight: !0, + opacity: !0, + order: !0, + orphans: !0, + tabSize: !0, + widows: !0, + zIndex: !0, + zoom: !0, + fillOpacity: !0, + floodOpacity: !0, + stopOpacity: !0, + strokeDasharray: !0, + strokeDashoffset: !0, + strokeMiterlimit: !0, + strokeOpacity: !0, + strokeWidth: !0 + }, + ze = ['Webkit', 'ms', 'Moz', 'O']; + function rb(s, o, i) { + return null == o || 'boolean' == typeof o || '' === o + ? '' + : i || 'number' != typeof o || 0 === o || (qe.hasOwnProperty(s) && qe[s]) + ? ('' + o).trim() + : o + 'px'; + } + function sb(s, o) { + for (var i in ((s = s.style), o)) + if (o.hasOwnProperty(i)) { + var a = 0 === i.indexOf('--'), + u = rb(i, o[i], a); + ('float' === i && (i = 'cssFloat'), a ? s.setProperty(i, u) : (s[i] = u)); + } + } + Object.keys(qe).forEach(function (s) { + ze.forEach(function (o) { + ((o = o + s.charAt(0).toUpperCase() + s.substring(1)), (qe[o] = qe[s])); + }); + }); + var We = we( + { menuitem: !0 }, + { + area: !0, + base: !0, + br: !0, + col: !0, + embed: !0, + hr: !0, + img: !0, + input: !0, + keygen: !0, + link: !0, + meta: !0, + param: !0, + source: !0, + track: !0, + wbr: !0 + } + ); + function ub(s, o) { + if (o) { + if (We[s] && (null != o.children || null != o.dangerouslySetInnerHTML)) + throw Error(p(137, s)); + if (null != o.dangerouslySetInnerHTML) { + if (null != o.children) throw Error(p(60)); + if ( + 'object' != typeof o.dangerouslySetInnerHTML || + !('__html' in o.dangerouslySetInnerHTML) + ) + throw Error(p(61)); + } + if (null != o.style && 'object' != typeof o.style) throw Error(p(62)); + } + } + function vb(s, o) { + if (-1 === s.indexOf('-')) return 'string' == typeof o.is; + switch (s) { + case 'annotation-xml': + case 'color-profile': + case 'font-face': + case 'font-face-src': + case 'font-face-uri': + case 'font-face-format': + case 'font-face-name': + case 'missing-glyph': + return !1; + default: + return !0; + } + } + var He = null; + function xb(s) { + return ( + (s = s.target || s.srcElement || window).correspondingUseElement && + (s = s.correspondingUseElement), + 3 === s.nodeType ? s.parentNode : s + ); + } + var Ye = null, + Xe = null, + Qe = null; + function Bb(s) { + if ((s = Cb(s))) { + if ('function' != typeof Ye) throw Error(p(280)); + var o = s.stateNode; + o && ((o = Db(o)), Ye(s.stateNode, s.type, o)); + } + } + function Eb(s) { + Xe ? (Qe ? Qe.push(s) : (Qe = [s])) : (Xe = s); + } + function Fb() { + if (Xe) { + var s = Xe, + o = Qe; + if (((Qe = Xe = null), Bb(s), o)) for (s = 0; s < o.length; s++) Bb(o[s]); + } + } + function Gb(s, o) { + return s(o); + } + function Hb() {} + var et = !1; + function Jb(s, o, i) { + if (et) return s(o, i); + et = !0; + try { + return Gb(s, o, i); + } finally { + ((et = !1), (null !== Xe || null !== Qe) && (Hb(), Fb())); + } + } + function Kb(s, o) { + var i = s.stateNode; + if (null === i) return null; + var a = Db(i); + if (null === a) return null; + i = a[o]; + e: switch (o) { + case 'onClick': + case 'onClickCapture': + case 'onDoubleClick': + case 'onDoubleClickCapture': + case 'onMouseDown': + case 'onMouseDownCapture': + case 'onMouseMove': + case 'onMouseMoveCapture': + case 'onMouseUp': + case 'onMouseUpCapture': + case 'onMouseEnter': + ((a = !a.disabled) || + (a = !( + 'button' === (s = s.type) || + 'input' === s || + 'select' === s || + 'textarea' === s + )), + (s = !a)); + break e; + default: + s = !1; + } + if (s) return null; + if (i && 'function' != typeof i) throw Error(p(231, o, typeof i)); + return i; + } + var tt = !1; + if (x) + try { + var rt = {}; + (Object.defineProperty(rt, 'passive', { + get: function () { + tt = !0; + } + }), + window.addEventListener('test', rt, rt), + window.removeEventListener('test', rt, rt)); + } catch (Re) { + tt = !1; + } + function Nb(s, o, i, a, u, _, w, x, C) { + var j = Array.prototype.slice.call(arguments, 3); + try { + o.apply(i, j); + } catch (s) { + this.onError(s); + } + } + var nt = !1, + st = null, + ot = !1, + it = null, + at = { + onError: function (s) { + ((nt = !0), (st = s)); + } + }; + function Tb(s, o, i, a, u, _, w, x, C) { + ((nt = !1), (st = null), Nb.apply(at, arguments)); + } + function Vb(s) { + var o = s, + i = s; + if (s.alternate) for (; o.return; ) o = o.return; + else { + s = o; + do { + (!!(4098 & (o = s).flags) && (i = o.return), (s = o.return)); + } while (s); + } + return 3 === o.tag ? i : null; + } + function Wb(s) { + if (13 === s.tag) { + var o = s.memoizedState; + if ((null === o && null !== (s = s.alternate) && (o = s.memoizedState), null !== o)) + return o.dehydrated; + } + return null; + } + function Xb(s) { + if (Vb(s) !== s) throw Error(p(188)); + } + function Zb(s) { + return null !== + (s = (function Yb(s) { + var o = s.alternate; + if (!o) { + if (null === (o = Vb(s))) throw Error(p(188)); + return o !== s ? null : s; + } + for (var i = s, a = o; ; ) { + var u = i.return; + if (null === u) break; + var _ = u.alternate; + if (null === _) { + if (null !== (a = u.return)) { + i = a; + continue; + } + break; + } + if (u.child === _.child) { + for (_ = u.child; _; ) { + if (_ === i) return (Xb(u), s); + if (_ === a) return (Xb(u), o); + _ = _.sibling; + } + throw Error(p(188)); + } + if (i.return !== a.return) ((i = u), (a = _)); + else { + for (var w = !1, x = u.child; x; ) { + if (x === i) { + ((w = !0), (i = u), (a = _)); + break; + } + if (x === a) { + ((w = !0), (a = u), (i = _)); + break; + } + x = x.sibling; + } + if (!w) { + for (x = _.child; x; ) { + if (x === i) { + ((w = !0), (i = _), (a = u)); + break; + } + if (x === a) { + ((w = !0), (a = _), (i = u)); + break; + } + x = x.sibling; + } + if (!w) throw Error(p(189)); + } + } + if (i.alternate !== a) throw Error(p(190)); + } + if (3 !== i.tag) throw Error(p(188)); + return i.stateNode.current === i ? s : o; + })(s)) + ? $b(s) + : null; + } + function $b(s) { + if (5 === s.tag || 6 === s.tag) return s; + for (s = s.child; null !== s; ) { + var o = $b(s); + if (null !== o) return o; + s = s.sibling; + } + return null; + } + var ct = u.unstable_scheduleCallback, + lt = u.unstable_cancelCallback, + ut = u.unstable_shouldYield, + pt = u.unstable_requestPaint, + ht = u.unstable_now, + dt = u.unstable_getCurrentPriorityLevel, + mt = u.unstable_ImmediatePriority, + gt = u.unstable_UserBlockingPriority, + yt = u.unstable_NormalPriority, + vt = u.unstable_LowPriority, + bt = u.unstable_IdlePriority, + St = null, + _t = null; + var Et = Math.clz32 + ? Math.clz32 + : function nc(s) { + return ((s >>>= 0), 0 === s ? 32 : (31 - ((wt(s) / xt) | 0)) | 0); + }, + wt = Math.log, + xt = Math.LN2; + var kt = 64, + Ot = 4194304; + function tc(s) { + switch (s & -s) { + case 1: + return 1; + case 2: + return 2; + case 4: + return 4; + case 8: + return 8; + case 16: + return 16; + case 32: + return 32; + case 64: + case 128: + case 256: + case 512: + case 1024: + case 2048: + case 4096: + case 8192: + case 16384: + case 32768: + case 65536: + case 131072: + case 262144: + case 524288: + case 1048576: + case 2097152: + return 4194240 & s; + case 4194304: + case 8388608: + case 16777216: + case 33554432: + case 67108864: + return 130023424 & s; + case 134217728: + return 134217728; + case 268435456: + return 268435456; + case 536870912: + return 536870912; + case 1073741824: + return 1073741824; + default: + return s; + } + } + function uc(s, o) { + var i = s.pendingLanes; + if (0 === i) return 0; + var a = 0, + u = s.suspendedLanes, + _ = s.pingedLanes, + w = 268435455 & i; + if (0 !== w) { + var x = w & ~u; + 0 !== x ? (a = tc(x)) : 0 !== (_ &= w) && (a = tc(_)); + } else 0 !== (w = i & ~u) ? (a = tc(w)) : 0 !== _ && (a = tc(_)); + if (0 === a) return 0; + if ( + 0 !== o && + o !== a && + !(o & u) && + ((u = a & -a) >= (_ = o & -o) || (16 === u && 4194240 & _)) + ) + return o; + if ((4 & a && (a |= 16 & i), 0 !== (o = s.entangledLanes))) + for (s = s.entanglements, o &= a; 0 < o; ) + ((u = 1 << (i = 31 - Et(o))), (a |= s[i]), (o &= ~u)); + return a; + } + function vc(s, o) { + switch (s) { + case 1: + case 2: + case 4: + return o + 250; + case 8: + case 16: + case 32: + case 64: + case 128: + case 256: + case 512: + case 1024: + case 2048: + case 4096: + case 8192: + case 16384: + case 32768: + case 65536: + case 131072: + case 262144: + case 524288: + case 1048576: + case 2097152: + return o + 5e3; + default: + return -1; + } + } + function xc(s) { + return 0 !== (s = -1073741825 & s.pendingLanes) ? s : 1073741824 & s ? 1073741824 : 0; + } + function yc() { + var s = kt; + return (!(4194240 & (kt <<= 1)) && (kt = 64), s); + } + function zc(s) { + for (var o = [], i = 0; 31 > i; i++) o.push(s); + return o; + } + function Ac(s, o, i) { + ((s.pendingLanes |= o), + 536870912 !== o && ((s.suspendedLanes = 0), (s.pingedLanes = 0)), + ((s = s.eventTimes)[(o = 31 - Et(o))] = i)); + } + function Cc(s, o) { + var i = (s.entangledLanes |= o); + for (s = s.entanglements; i; ) { + var a = 31 - Et(i), + u = 1 << a; + ((u & o) | (s[a] & o) && (s[a] |= o), (i &= ~u)); + } + } + var At = 0; + function Dc(s) { + return 1 < (s &= -s) ? (4 < s ? (268435455 & s ? 16 : 536870912) : 4) : 1; + } + var Ct, + jt, + Pt, + It, + Tt, + Nt = !1, + Mt = [], + Rt = null, + Dt = null, + Lt = null, + Ft = new Map(), + Bt = new Map(), + $t = [], + qt = + 'mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit'.split( + ' ' + ); + function Sc(s, o) { + switch (s) { + case 'focusin': + case 'focusout': + Rt = null; + break; + case 'dragenter': + case 'dragleave': + Dt = null; + break; + case 'mouseover': + case 'mouseout': + Lt = null; + break; + case 'pointerover': + case 'pointerout': + Ft.delete(o.pointerId); + break; + case 'gotpointercapture': + case 'lostpointercapture': + Bt.delete(o.pointerId); + } + } + function Tc(s, o, i, a, u, _) { + return null === s || s.nativeEvent !== _ + ? ((s = { + blockedOn: o, + domEventName: i, + eventSystemFlags: a, + nativeEvent: _, + targetContainers: [u] + }), + null !== o && null !== (o = Cb(o)) && jt(o), + s) + : ((s.eventSystemFlags |= a), + (o = s.targetContainers), + null !== u && -1 === o.indexOf(u) && o.push(u), + s); + } + function Vc(s) { + var o = Wc(s.target); + if (null !== o) { + var i = Vb(o); + if (null !== i) + if (13 === (o = i.tag)) { + if (null !== (o = Wb(i))) + return ( + (s.blockedOn = o), + void Tt(s.priority, function () { + Pt(i); + }) + ); + } else if (3 === o && i.stateNode.current.memoizedState.isDehydrated) + return void (s.blockedOn = 3 === i.tag ? i.stateNode.containerInfo : null); + } + s.blockedOn = null; + } + function Xc(s) { + if (null !== s.blockedOn) return !1; + for (var o = s.targetContainers; 0 < o.length; ) { + var i = Yc(s.domEventName, s.eventSystemFlags, o[0], s.nativeEvent); + if (null !== i) return (null !== (o = Cb(i)) && jt(o), (s.blockedOn = i), !1); + var a = new (i = s.nativeEvent).constructor(i.type, i); + ((He = a), i.target.dispatchEvent(a), (He = null), o.shift()); + } + return !0; + } + function Zc(s, o, i) { + Xc(s) && i.delete(o); + } + function $c() { + ((Nt = !1), + null !== Rt && Xc(Rt) && (Rt = null), + null !== Dt && Xc(Dt) && (Dt = null), + null !== Lt && Xc(Lt) && (Lt = null), + Ft.forEach(Zc), + Bt.forEach(Zc)); + } + function ad(s, o) { + s.blockedOn === o && + ((s.blockedOn = null), + Nt || ((Nt = !0), u.unstable_scheduleCallback(u.unstable_NormalPriority, $c))); + } + function bd(s) { + function b(o) { + return ad(o, s); + } + if (0 < Mt.length) { + ad(Mt[0], s); + for (var o = 1; o < Mt.length; o++) { + var i = Mt[o]; + i.blockedOn === s && (i.blockedOn = null); + } + } + for ( + null !== Rt && ad(Rt, s), + null !== Dt && ad(Dt, s), + null !== Lt && ad(Lt, s), + Ft.forEach(b), + Bt.forEach(b), + o = 0; + o < $t.length; + o++ + ) + (i = $t[o]).blockedOn === s && (i.blockedOn = null); + for (; 0 < $t.length && null === (o = $t[0]).blockedOn; ) + (Vc(o), null === o.blockedOn && $t.shift()); + } + var Ut = V.ReactCurrentBatchConfig, + Vt = !0; + function ed(s, o, i, a) { + var u = At, + _ = Ut.transition; + Ut.transition = null; + try { + ((At = 1), fd(s, o, i, a)); + } finally { + ((At = u), (Ut.transition = _)); + } + } + function gd(s, o, i, a) { + var u = At, + _ = Ut.transition; + Ut.transition = null; + try { + ((At = 4), fd(s, o, i, a)); + } finally { + ((At = u), (Ut.transition = _)); + } + } + function fd(s, o, i, a) { + if (Vt) { + var u = Yc(s, o, i, a); + if (null === u) (hd(s, o, a, zt, i), Sc(s, a)); + else if ( + (function Uc(s, o, i, a, u) { + switch (o) { + case 'focusin': + return ((Rt = Tc(Rt, s, o, i, a, u)), !0); + case 'dragenter': + return ((Dt = Tc(Dt, s, o, i, a, u)), !0); + case 'mouseover': + return ((Lt = Tc(Lt, s, o, i, a, u)), !0); + case 'pointerover': + var _ = u.pointerId; + return (Ft.set(_, Tc(Ft.get(_) || null, s, o, i, a, u)), !0); + case 'gotpointercapture': + return ( + (_ = u.pointerId), + Bt.set(_, Tc(Bt.get(_) || null, s, o, i, a, u)), + !0 + ); + } + return !1; + })(u, s, o, i, a) + ) + a.stopPropagation(); + else if ((Sc(s, a), 4 & o && -1 < qt.indexOf(s))) { + for (; null !== u; ) { + var _ = Cb(u); + if ( + (null !== _ && Ct(_), + null === (_ = Yc(s, o, i, a)) && hd(s, o, a, zt, i), + _ === u) + ) + break; + u = _; + } + null !== u && a.stopPropagation(); + } else hd(s, o, a, null, i); + } + } + var zt = null; + function Yc(s, o, i, a) { + if (((zt = null), null !== (s = Wc((s = xb(a)))))) + if (null === (o = Vb(s))) s = null; + else if (13 === (i = o.tag)) { + if (null !== (s = Wb(o))) return s; + s = null; + } else if (3 === i) { + if (o.stateNode.current.memoizedState.isDehydrated) + return 3 === o.tag ? o.stateNode.containerInfo : null; + s = null; + } else o !== s && (s = null); + return ((zt = s), null); + } + function jd(s) { + switch (s) { + case 'cancel': + case 'click': + case 'close': + case 'contextmenu': + case 'copy': + case 'cut': + case 'auxclick': + case 'dblclick': + case 'dragend': + case 'dragstart': + case 'drop': + case 'focusin': + case 'focusout': + case 'input': + case 'invalid': + case 'keydown': + case 'keypress': + case 'keyup': + case 'mousedown': + case 'mouseup': + case 'paste': + case 'pause': + case 'play': + case 'pointercancel': + case 'pointerdown': + case 'pointerup': + case 'ratechange': + case 'reset': + case 'resize': + case 'seeked': + case 'submit': + case 'touchcancel': + case 'touchend': + case 'touchstart': + case 'volumechange': + case 'change': + case 'selectionchange': + case 'textInput': + case 'compositionstart': + case 'compositionend': + case 'compositionupdate': + case 'beforeblur': + case 'afterblur': + case 'beforeinput': + case 'blur': + case 'fullscreenchange': + case 'focus': + case 'hashchange': + case 'popstate': + case 'select': + case 'selectstart': + return 1; + case 'drag': + case 'dragenter': + case 'dragexit': + case 'dragleave': + case 'dragover': + case 'mousemove': + case 'mouseout': + case 'mouseover': + case 'pointermove': + case 'pointerout': + case 'pointerover': + case 'scroll': + case 'toggle': + case 'touchmove': + case 'wheel': + case 'mouseenter': + case 'mouseleave': + case 'pointerenter': + case 'pointerleave': + return 4; + case 'message': + switch (dt()) { + case mt: + return 1; + case gt: + return 4; + case yt: + case vt: + return 16; + case bt: + return 536870912; + default: + return 16; + } + default: + return 16; + } + } + var Wt = null, + Jt = null, + Ht = null; + function nd() { + if (Ht) return Ht; + var s, + o, + i = Jt, + a = i.length, + u = 'value' in Wt ? Wt.value : Wt.textContent, + _ = u.length; + for (s = 0; s < a && i[s] === u[s]; s++); + var w = a - s; + for (o = 1; o <= w && i[a - o] === u[_ - o]; o++); + return (Ht = u.slice(s, 1 < o ? 1 - o : void 0)); + } + function od(s) { + var o = s.keyCode; + return ( + 'charCode' in s ? 0 === (s = s.charCode) && 13 === o && (s = 13) : (s = o), + 10 === s && (s = 13), + 32 <= s || 13 === s ? s : 0 + ); + } + function pd() { + return !0; + } + function qd() { + return !1; + } + function rd(s) { + function b(o, i, a, u, _) { + for (var w in ((this._reactName = o), + (this._targetInst = a), + (this.type = i), + (this.nativeEvent = u), + (this.target = _), + (this.currentTarget = null), + s)) + s.hasOwnProperty(w) && ((o = s[w]), (this[w] = o ? o(u) : u[w])); + return ( + (this.isDefaultPrevented = ( + null != u.defaultPrevented ? u.defaultPrevented : !1 === u.returnValue + ) + ? pd + : qd), + (this.isPropagationStopped = qd), + this + ); + } + return ( + we(b.prototype, { + preventDefault: function () { + this.defaultPrevented = !0; + var s = this.nativeEvent; + s && + (s.preventDefault + ? s.preventDefault() + : 'unknown' != typeof s.returnValue && (s.returnValue = !1), + (this.isDefaultPrevented = pd)); + }, + stopPropagation: function () { + var s = this.nativeEvent; + s && + (s.stopPropagation + ? s.stopPropagation() + : 'unknown' != typeof s.cancelBubble && (s.cancelBubble = !0), + (this.isPropagationStopped = pd)); + }, + persist: function () {}, + isPersistent: pd + }), + b + ); + } + var Kt, + Gt, + Yt, + Xt = { + eventPhase: 0, + bubbles: 0, + cancelable: 0, + timeStamp: function (s) { + return s.timeStamp || Date.now(); + }, + defaultPrevented: 0, + isTrusted: 0 + }, + Qt = rd(Xt), + Zt = we({}, Xt, { view: 0, detail: 0 }), + er = rd(Zt), + tr = we({}, Zt, { + screenX: 0, + screenY: 0, + clientX: 0, + clientY: 0, + pageX: 0, + pageY: 0, + ctrlKey: 0, + shiftKey: 0, + altKey: 0, + metaKey: 0, + getModifierState: zd, + button: 0, + buttons: 0, + relatedTarget: function (s) { + return void 0 === s.relatedTarget + ? s.fromElement === s.srcElement + ? s.toElement + : s.fromElement + : s.relatedTarget; + }, + movementX: function (s) { + return 'movementX' in s + ? s.movementX + : (s !== Yt && + (Yt && 'mousemove' === s.type + ? ((Kt = s.screenX - Yt.screenX), (Gt = s.screenY - Yt.screenY)) + : (Gt = Kt = 0), + (Yt = s)), + Kt); + }, + movementY: function (s) { + return 'movementY' in s ? s.movementY : Gt; + } + }), + rr = rd(tr), + nr = rd(we({}, tr, { dataTransfer: 0 })), + sr = rd(we({}, Zt, { relatedTarget: 0 })), + ir = rd(we({}, Xt, { animationName: 0, elapsedTime: 0, pseudoElement: 0 })), + ar = we({}, Xt, { + clipboardData: function (s) { + return 'clipboardData' in s ? s.clipboardData : window.clipboardData; + } + }), + cr = rd(ar), + lr = rd(we({}, Xt, { data: 0 })), + ur = { + Esc: 'Escape', + Spacebar: ' ', + Left: 'ArrowLeft', + Up: 'ArrowUp', + Right: 'ArrowRight', + Down: 'ArrowDown', + Del: 'Delete', + Win: 'OS', + Menu: 'ContextMenu', + Apps: 'ContextMenu', + Scroll: 'ScrollLock', + MozPrintableKey: 'Unidentified' + }, + pr = { + 8: 'Backspace', + 9: 'Tab', + 12: 'Clear', + 13: 'Enter', + 16: 'Shift', + 17: 'Control', + 18: 'Alt', + 19: 'Pause', + 20: 'CapsLock', + 27: 'Escape', + 32: ' ', + 33: 'PageUp', + 34: 'PageDown', + 35: 'End', + 36: 'Home', + 37: 'ArrowLeft', + 38: 'ArrowUp', + 39: 'ArrowRight', + 40: 'ArrowDown', + 45: 'Insert', + 46: 'Delete', + 112: 'F1', + 113: 'F2', + 114: 'F3', + 115: 'F4', + 116: 'F5', + 117: 'F6', + 118: 'F7', + 119: 'F8', + 120: 'F9', + 121: 'F10', + 122: 'F11', + 123: 'F12', + 144: 'NumLock', + 145: 'ScrollLock', + 224: 'Meta' + }, + dr = { Alt: 'altKey', Control: 'ctrlKey', Meta: 'metaKey', Shift: 'shiftKey' }; + function Pd(s) { + var o = this.nativeEvent; + return o.getModifierState ? o.getModifierState(s) : !!(s = dr[s]) && !!o[s]; + } + function zd() { + return Pd; + } + var fr = we({}, Zt, { + key: function (s) { + if (s.key) { + var o = ur[s.key] || s.key; + if ('Unidentified' !== o) return o; + } + return 'keypress' === s.type + ? 13 === (s = od(s)) + ? 'Enter' + : String.fromCharCode(s) + : 'keydown' === s.type || 'keyup' === s.type + ? pr[s.keyCode] || 'Unidentified' + : ''; + }, + code: 0, + location: 0, + ctrlKey: 0, + shiftKey: 0, + altKey: 0, + metaKey: 0, + repeat: 0, + locale: 0, + getModifierState: zd, + charCode: function (s) { + return 'keypress' === s.type ? od(s) : 0; + }, + keyCode: function (s) { + return 'keydown' === s.type || 'keyup' === s.type ? s.keyCode : 0; + }, + which: function (s) { + return 'keypress' === s.type + ? od(s) + : 'keydown' === s.type || 'keyup' === s.type + ? s.keyCode + : 0; + } + }), + mr = rd(fr), + gr = rd( + we({}, tr, { + pointerId: 0, + width: 0, + height: 0, + pressure: 0, + tangentialPressure: 0, + tiltX: 0, + tiltY: 0, + twist: 0, + pointerType: 0, + isPrimary: 0 + }) + ), + yr = rd( + we({}, Zt, { + touches: 0, + targetTouches: 0, + changedTouches: 0, + altKey: 0, + metaKey: 0, + ctrlKey: 0, + shiftKey: 0, + getModifierState: zd + }) + ), + vr = rd(we({}, Xt, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 })), + br = we({}, tr, { + deltaX: function (s) { + return 'deltaX' in s ? s.deltaX : 'wheelDeltaX' in s ? -s.wheelDeltaX : 0; + }, + deltaY: function (s) { + return 'deltaY' in s + ? s.deltaY + : 'wheelDeltaY' in s + ? -s.wheelDeltaY + : 'wheelDelta' in s + ? -s.wheelDelta + : 0; + }, + deltaZ: 0, + deltaMode: 0 + }), + Sr = rd(br), + _r = [9, 13, 27, 32], + Er = x && 'CompositionEvent' in window, + wr = null; + x && 'documentMode' in document && (wr = document.documentMode); + var xr = x && 'TextEvent' in window && !wr, + kr = x && (!Er || (wr && 8 < wr && 11 >= wr)), + Or = String.fromCharCode(32), + Ar = !1; + function ge(s, o) { + switch (s) { + case 'keyup': + return -1 !== _r.indexOf(o.keyCode); + case 'keydown': + return 229 !== o.keyCode; + case 'keypress': + case 'mousedown': + case 'focusout': + return !0; + default: + return !1; + } + } + function he(s) { + return 'object' == typeof (s = s.detail) && 'data' in s ? s.data : null; + } + var Cr = !1; + var jr = { + color: !0, + date: !0, + datetime: !0, + 'datetime-local': !0, + email: !0, + month: !0, + number: !0, + password: !0, + range: !0, + search: !0, + tel: !0, + text: !0, + time: !0, + url: !0, + week: !0 + }; + function me(s) { + var o = s && s.nodeName && s.nodeName.toLowerCase(); + return 'input' === o ? !!jr[s.type] : 'textarea' === o; + } + function ne(s, o, i, a) { + (Eb(a), + 0 < (o = oe(o, 'onChange')).length && + ((i = new Qt('onChange', 'change', null, i, a)), + s.push({ event: i, listeners: o }))); + } + var Pr = null, + Ir = null; + function re(s) { + se(s, 0); + } + function te(s) { + if (Wa(ue(s))) return s; + } + function ve(s, o) { + if ('change' === s) return o; + } + var Tr = !1; + if (x) { + var Nr; + if (x) { + var Mr = 'oninput' in document; + if (!Mr) { + var Rr = document.createElement('div'); + (Rr.setAttribute('oninput', 'return;'), (Mr = 'function' == typeof Rr.oninput)); + } + Nr = Mr; + } else Nr = !1; + Tr = Nr && (!document.documentMode || 9 < document.documentMode); + } + function Ae() { + Pr && (Pr.detachEvent('onpropertychange', Be), (Ir = Pr = null)); + } + function Be(s) { + if ('value' === s.propertyName && te(Ir)) { + var o = []; + (ne(o, Ir, s, xb(s)), Jb(re, o)); + } + } + function Ce(s, o, i) { + 'focusin' === s + ? (Ae(), (Ir = i), (Pr = o).attachEvent('onpropertychange', Be)) + : 'focusout' === s && Ae(); + } + function De(s) { + if ('selectionchange' === s || 'keyup' === s || 'keydown' === s) return te(Ir); + } + function Ee(s, o) { + if ('click' === s) return te(o); + } + function Fe(s, o) { + if ('input' === s || 'change' === s) return te(o); + } + var Dr = + 'function' == typeof Object.is + ? Object.is + : function Ge(s, o) { + return (s === o && (0 !== s || 1 / s == 1 / o)) || (s != s && o != o); + }; + function Ie(s, o) { + if (Dr(s, o)) return !0; + if ('object' != typeof s || null === s || 'object' != typeof o || null === o) return !1; + var i = Object.keys(s), + a = Object.keys(o); + if (i.length !== a.length) return !1; + for (a = 0; a < i.length; a++) { + var u = i[a]; + if (!C.call(o, u) || !Dr(s[u], o[u])) return !1; + } + return !0; + } + function Je(s) { + for (; s && s.firstChild; ) s = s.firstChild; + return s; + } + function Ke(s, o) { + var i, + a = Je(s); + for (s = 0; a; ) { + if (3 === a.nodeType) { + if (((i = s + a.textContent.length), s <= o && i >= o)) + return { node: a, offset: o - s }; + s = i; + } + e: { + for (; a; ) { + if (a.nextSibling) { + a = a.nextSibling; + break e; + } + a = a.parentNode; + } + a = void 0; + } + a = Je(a); + } + } + function Le(s, o) { + return ( + !(!s || !o) && + (s === o || + ((!s || 3 !== s.nodeType) && + (o && 3 === o.nodeType + ? Le(s, o.parentNode) + : 'contains' in s + ? s.contains(o) + : !!s.compareDocumentPosition && !!(16 & s.compareDocumentPosition(o))))) + ); + } + function Me() { + for (var s = window, o = Xa(); o instanceof s.HTMLIFrameElement; ) { + try { + var i = 'string' == typeof o.contentWindow.location.href; + } catch (s) { + i = !1; + } + if (!i) break; + o = Xa((s = o.contentWindow).document); + } + return o; + } + function Ne(s) { + var o = s && s.nodeName && s.nodeName.toLowerCase(); + return ( + o && + (('input' === o && + ('text' === s.type || + 'search' === s.type || + 'tel' === s.type || + 'url' === s.type || + 'password' === s.type)) || + 'textarea' === o || + 'true' === s.contentEditable) + ); + } + function Oe(s) { + var o = Me(), + i = s.focusedElem, + a = s.selectionRange; + if (o !== i && i && i.ownerDocument && Le(i.ownerDocument.documentElement, i)) { + if (null !== a && Ne(i)) + if (((o = a.start), void 0 === (s = a.end) && (s = o), 'selectionStart' in i)) + ((i.selectionStart = o), (i.selectionEnd = Math.min(s, i.value.length))); + else if ( + (s = ((o = i.ownerDocument || document) && o.defaultView) || window).getSelection + ) { + s = s.getSelection(); + var u = i.textContent.length, + _ = Math.min(a.start, u); + ((a = void 0 === a.end ? _ : Math.min(a.end, u)), + !s.extend && _ > a && ((u = a), (a = _), (_ = u)), + (u = Ke(i, _))); + var w = Ke(i, a); + u && + w && + (1 !== s.rangeCount || + s.anchorNode !== u.node || + s.anchorOffset !== u.offset || + s.focusNode !== w.node || + s.focusOffset !== w.offset) && + ((o = o.createRange()).setStart(u.node, u.offset), + s.removeAllRanges(), + _ > a + ? (s.addRange(o), s.extend(w.node, w.offset)) + : (o.setEnd(w.node, w.offset), s.addRange(o))); + } + for (o = [], s = i; (s = s.parentNode); ) + 1 === s.nodeType && o.push({ element: s, left: s.scrollLeft, top: s.scrollTop }); + for ('function' == typeof i.focus && i.focus(), i = 0; i < o.length; i++) + (((s = o[i]).element.scrollLeft = s.left), (s.element.scrollTop = s.top)); + } + } + var Lr = x && 'documentMode' in document && 11 >= document.documentMode, + Fr = null, + Br = null, + $r = null, + qr = !1; + function Ue(s, o, i) { + var a = i.window === i ? i.document : 9 === i.nodeType ? i : i.ownerDocument; + qr || + null == Fr || + Fr !== Xa(a) || + ('selectionStart' in (a = Fr) && Ne(a) + ? (a = { start: a.selectionStart, end: a.selectionEnd }) + : (a = { + anchorNode: (a = ( + (a.ownerDocument && a.ownerDocument.defaultView) || + window + ).getSelection()).anchorNode, + anchorOffset: a.anchorOffset, + focusNode: a.focusNode, + focusOffset: a.focusOffset + }), + ($r && Ie($r, a)) || + (($r = a), + 0 < (a = oe(Br, 'onSelect')).length && + ((o = new Qt('onSelect', 'select', null, o, i)), + s.push({ event: o, listeners: a }), + (o.target = Fr)))); + } + function Ve(s, o) { + var i = {}; + return ( + (i[s.toLowerCase()] = o.toLowerCase()), + (i['Webkit' + s] = 'webkit' + o), + (i['Moz' + s] = 'moz' + o), + i + ); + } + var Ur = { + animationend: Ve('Animation', 'AnimationEnd'), + animationiteration: Ve('Animation', 'AnimationIteration'), + animationstart: Ve('Animation', 'AnimationStart'), + transitionend: Ve('Transition', 'TransitionEnd') + }, + Vr = {}, + zr = {}; + function Ze(s) { + if (Vr[s]) return Vr[s]; + if (!Ur[s]) return s; + var o, + i = Ur[s]; + for (o in i) if (i.hasOwnProperty(o) && o in zr) return (Vr[s] = i[o]); + return s; + } + x && + ((zr = document.createElement('div').style), + 'AnimationEvent' in window || + (delete Ur.animationend.animation, + delete Ur.animationiteration.animation, + delete Ur.animationstart.animation), + 'TransitionEvent' in window || delete Ur.transitionend.transition); + var Wr = Ze('animationend'), + Jr = Ze('animationiteration'), + Hr = Ze('animationstart'), + Kr = Ze('transitionend'), + Gr = new Map(), + Yr = + 'abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel'.split( + ' ' + ); + function ff(s, o) { + (Gr.set(s, o), fa(o, [s])); + } + for (var Xr = 0; Xr < Yr.length; Xr++) { + var Qr = Yr[Xr]; + ff(Qr.toLowerCase(), 'on' + (Qr[0].toUpperCase() + Qr.slice(1))); + } + (ff(Wr, 'onAnimationEnd'), + ff(Jr, 'onAnimationIteration'), + ff(Hr, 'onAnimationStart'), + ff('dblclick', 'onDoubleClick'), + ff('focusin', 'onFocus'), + ff('focusout', 'onBlur'), + ff(Kr, 'onTransitionEnd'), + ha('onMouseEnter', ['mouseout', 'mouseover']), + ha('onMouseLeave', ['mouseout', 'mouseover']), + ha('onPointerEnter', ['pointerout', 'pointerover']), + ha('onPointerLeave', ['pointerout', 'pointerover']), + fa( + 'onChange', + 'change click focusin focusout input keydown keyup selectionchange'.split(' ') + ), + fa( + 'onSelect', + 'focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange'.split( + ' ' + ) + ), + fa('onBeforeInput', ['compositionend', 'keypress', 'textInput', 'paste']), + fa( + 'onCompositionEnd', + 'compositionend focusout keydown keypress keyup mousedown'.split(' ') + ), + fa( + 'onCompositionStart', + 'compositionstart focusout keydown keypress keyup mousedown'.split(' ') + ), + fa( + 'onCompositionUpdate', + 'compositionupdate focusout keydown keypress keyup mousedown'.split(' ') + )); + var Zr = + 'abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting'.split( + ' ' + ), + en = new Set('cancel close invalid load scroll toggle'.split(' ').concat(Zr)); + function nf(s, o, i) { + var a = s.type || 'unknown-event'; + ((s.currentTarget = i), + (function Ub(s, o, i, a, u, _, w, x, C) { + if ((Tb.apply(this, arguments), nt)) { + if (!nt) throw Error(p(198)); + var j = st; + ((nt = !1), (st = null), ot || ((ot = !0), (it = j))); + } + })(a, o, void 0, s), + (s.currentTarget = null)); + } + function se(s, o) { + o = !!(4 & o); + for (var i = 0; i < s.length; i++) { + var a = s[i], + u = a.event; + a = a.listeners; + e: { + var _ = void 0; + if (o) + for (var w = a.length - 1; 0 <= w; w--) { + var x = a[w], + C = x.instance, + j = x.currentTarget; + if (((x = x.listener), C !== _ && u.isPropagationStopped())) break e; + (nf(u, x, j), (_ = C)); + } + else + for (w = 0; w < a.length; w++) { + if ( + ((C = (x = a[w]).instance), + (j = x.currentTarget), + (x = x.listener), + C !== _ && u.isPropagationStopped()) + ) + break e; + (nf(u, x, j), (_ = C)); + } + } + } + if (ot) throw ((s = it), (ot = !1), (it = null), s); + } + function D(s, o) { + var i = o[mn]; + void 0 === i && (i = o[mn] = new Set()); + var a = s + '__bubble'; + i.has(a) || (pf(o, s, 2, !1), i.add(a)); + } + function qf(s, o, i) { + var a = 0; + (o && (a |= 4), pf(i, s, a, o)); + } + var tn = '_reactListening' + Math.random().toString(36).slice(2); + function sf(s) { + if (!s[tn]) { + ((s[tn] = !0), + _.forEach(function (o) { + 'selectionchange' !== o && (en.has(o) || qf(o, !1, s), qf(o, !0, s)); + })); + var o = 9 === s.nodeType ? s : s.ownerDocument; + null === o || o[tn] || ((o[tn] = !0), qf('selectionchange', !1, o)); + } + } + function pf(s, o, i, a) { + switch (jd(o)) { + case 1: + var u = ed; + break; + case 4: + u = gd; + break; + default: + u = fd; + } + ((i = u.bind(null, o, i, s)), + (u = void 0), + !tt || ('touchstart' !== o && 'touchmove' !== o && 'wheel' !== o) || (u = !0), + a + ? void 0 !== u + ? s.addEventListener(o, i, { capture: !0, passive: u }) + : s.addEventListener(o, i, !0) + : void 0 !== u + ? s.addEventListener(o, i, { passive: u }) + : s.addEventListener(o, i, !1)); + } + function hd(s, o, i, a, u) { + var _ = a; + if (!(1 & o || 2 & o || null === a)) + e: for (;;) { + if (null === a) return; + var w = a.tag; + if (3 === w || 4 === w) { + var x = a.stateNode.containerInfo; + if (x === u || (8 === x.nodeType && x.parentNode === u)) break; + if (4 === w) + for (w = a.return; null !== w; ) { + var C = w.tag; + if ( + (3 === C || 4 === C) && + ((C = w.stateNode.containerInfo) === u || + (8 === C.nodeType && C.parentNode === u)) + ) + return; + w = w.return; + } + for (; null !== x; ) { + if (null === (w = Wc(x))) return; + if (5 === (C = w.tag) || 6 === C) { + a = _ = w; + continue e; + } + x = x.parentNode; + } + } + a = a.return; + } + Jb(function () { + var a = _, + u = xb(i), + w = []; + e: { + var x = Gr.get(s); + if (void 0 !== x) { + var C = Qt, + j = s; + switch (s) { + case 'keypress': + if (0 === od(i)) break e; + case 'keydown': + case 'keyup': + C = mr; + break; + case 'focusin': + ((j = 'focus'), (C = sr)); + break; + case 'focusout': + ((j = 'blur'), (C = sr)); + break; + case 'beforeblur': + case 'afterblur': + C = sr; + break; + case 'click': + if (2 === i.button) break e; + case 'auxclick': + case 'dblclick': + case 'mousedown': + case 'mousemove': + case 'mouseup': + case 'mouseout': + case 'mouseover': + case 'contextmenu': + C = rr; + break; + case 'drag': + case 'dragend': + case 'dragenter': + case 'dragexit': + case 'dragleave': + case 'dragover': + case 'dragstart': + case 'drop': + C = nr; + break; + case 'touchcancel': + case 'touchend': + case 'touchmove': + case 'touchstart': + C = yr; + break; + case Wr: + case Jr: + case Hr: + C = ir; + break; + case Kr: + C = vr; + break; + case 'scroll': + C = er; + break; + case 'wheel': + C = Sr; + break; + case 'copy': + case 'cut': + case 'paste': + C = cr; + break; + case 'gotpointercapture': + case 'lostpointercapture': + case 'pointercancel': + case 'pointerdown': + case 'pointermove': + case 'pointerout': + case 'pointerover': + case 'pointerup': + C = gr; + } + var L = !!(4 & o), + B = !L && 'scroll' === s, + $ = L ? (null !== x ? x + 'Capture' : null) : x; + L = []; + for (var U, V = a; null !== V; ) { + var z = (U = V).stateNode; + if ( + (5 === U.tag && + null !== z && + ((U = z), null !== $ && null != (z = Kb(V, $)) && L.push(tf(V, z, U))), + B) + ) + break; + V = V.return; + } + 0 < L.length && + ((x = new C(x, j, null, i, u)), w.push({ event: x, listeners: L })); + } + } + if (!(7 & o)) { + if ( + ((C = 'mouseout' === s || 'pointerout' === s), + (!(x = 'mouseover' === s || 'pointerover' === s) || + i === He || + !(j = i.relatedTarget || i.fromElement) || + (!Wc(j) && !j[fn])) && + (C || x) && + ((x = + u.window === u + ? u + : (x = u.ownerDocument) + ? x.defaultView || x.parentWindow + : window), + C + ? ((C = a), + null !== (j = (j = i.relatedTarget || i.toElement) ? Wc(j) : null) && + (j !== (B = Vb(j)) || (5 !== j.tag && 6 !== j.tag)) && + (j = null)) + : ((C = null), (j = a)), + C !== j)) + ) { + if ( + ((L = rr), + (z = 'onMouseLeave'), + ($ = 'onMouseEnter'), + (V = 'mouse'), + ('pointerout' !== s && 'pointerover' !== s) || + ((L = gr), (z = 'onPointerLeave'), ($ = 'onPointerEnter'), (V = 'pointer')), + (B = null == C ? x : ue(C)), + (U = null == j ? x : ue(j)), + ((x = new L(z, V + 'leave', C, i, u)).target = B), + (x.relatedTarget = U), + (z = null), + Wc(u) === a && + (((L = new L($, V + 'enter', j, i, u)).target = U), + (L.relatedTarget = B), + (z = L)), + (B = z), + C && j) + ) + e: { + for ($ = j, V = 0, U = L = C; U; U = vf(U)) V++; + for (U = 0, z = $; z; z = vf(z)) U++; + for (; 0 < V - U; ) ((L = vf(L)), V--); + for (; 0 < U - V; ) (($ = vf($)), U--); + for (; V--; ) { + if (L === $ || (null !== $ && L === $.alternate)) break e; + ((L = vf(L)), ($ = vf($))); + } + L = null; + } + else L = null; + (null !== C && wf(w, x, C, L, !1), + null !== j && null !== B && wf(w, B, j, L, !0)); + } + if ( + 'select' === + (C = (x = a ? ue(a) : window).nodeName && x.nodeName.toLowerCase()) || + ('input' === C && 'file' === x.type) + ) + var Y = ve; + else if (me(x)) + if (Tr) Y = Fe; + else { + Y = De; + var Z = Ce; + } + else + (C = x.nodeName) && + 'input' === C.toLowerCase() && + ('checkbox' === x.type || 'radio' === x.type) && + (Y = Ee); + switch ( + (Y && (Y = Y(s, a)) + ? ne(w, Y, i, u) + : (Z && Z(s, x, a), + 'focusout' === s && + (Z = x._wrapperState) && + Z.controlled && + 'number' === x.type && + cb(x, 'number', x.value)), + (Z = a ? ue(a) : window), + s) + ) { + case 'focusin': + (me(Z) || 'true' === Z.contentEditable) && ((Fr = Z), (Br = a), ($r = null)); + break; + case 'focusout': + $r = Br = Fr = null; + break; + case 'mousedown': + qr = !0; + break; + case 'contextmenu': + case 'mouseup': + case 'dragend': + ((qr = !1), Ue(w, i, u)); + break; + case 'selectionchange': + if (Lr) break; + case 'keydown': + case 'keyup': + Ue(w, i, u); + } + var ee; + if (Er) + e: { + switch (s) { + case 'compositionstart': + var ie = 'onCompositionStart'; + break e; + case 'compositionend': + ie = 'onCompositionEnd'; + break e; + case 'compositionupdate': + ie = 'onCompositionUpdate'; + break e; + } + ie = void 0; + } + else + Cr + ? ge(s, i) && (ie = 'onCompositionEnd') + : 'keydown' === s && 229 === i.keyCode && (ie = 'onCompositionStart'); + (ie && + (kr && + 'ko' !== i.locale && + (Cr || 'onCompositionStart' !== ie + ? 'onCompositionEnd' === ie && Cr && (ee = nd()) + : ((Jt = 'value' in (Wt = u) ? Wt.value : Wt.textContent), (Cr = !0))), + 0 < (Z = oe(a, ie)).length && + ((ie = new lr(ie, s, null, i, u)), + w.push({ event: ie, listeners: Z }), + ee ? (ie.data = ee) : null !== (ee = he(i)) && (ie.data = ee))), + (ee = xr + ? (function je(s, o) { + switch (s) { + case 'compositionend': + return he(o); + case 'keypress': + return 32 !== o.which ? null : ((Ar = !0), Or); + case 'textInput': + return (s = o.data) === Or && Ar ? null : s; + default: + return null; + } + })(s, i) + : (function ke(s, o) { + if (Cr) + return 'compositionend' === s || (!Er && ge(s, o)) + ? ((s = nd()), (Ht = Jt = Wt = null), (Cr = !1), s) + : null; + switch (s) { + case 'paste': + default: + return null; + case 'keypress': + if (!(o.ctrlKey || o.altKey || o.metaKey) || (o.ctrlKey && o.altKey)) { + if (o.char && 1 < o.char.length) return o.char; + if (o.which) return String.fromCharCode(o.which); + } + return null; + case 'compositionend': + return kr && 'ko' !== o.locale ? null : o.data; + } + })(s, i)) && + 0 < (a = oe(a, 'onBeforeInput')).length && + ((u = new lr('onBeforeInput', 'beforeinput', null, i, u)), + w.push({ event: u, listeners: a }), + (u.data = ee))); + } + se(w, o); + }); + } + function tf(s, o, i) { + return { instance: s, listener: o, currentTarget: i }; + } + function oe(s, o) { + for (var i = o + 'Capture', a = []; null !== s; ) { + var u = s, + _ = u.stateNode; + (5 === u.tag && + null !== _ && + ((u = _), + null != (_ = Kb(s, i)) && a.unshift(tf(s, _, u)), + null != (_ = Kb(s, o)) && a.push(tf(s, _, u))), + (s = s.return)); + } + return a; + } + function vf(s) { + if (null === s) return null; + do { + s = s.return; + } while (s && 5 !== s.tag); + return s || null; + } + function wf(s, o, i, a, u) { + for (var _ = o._reactName, w = []; null !== i && i !== a; ) { + var x = i, + C = x.alternate, + j = x.stateNode; + if (null !== C && C === a) break; + (5 === x.tag && + null !== j && + ((x = j), + u + ? null != (C = Kb(i, _)) && w.unshift(tf(i, C, x)) + : u || (null != (C = Kb(i, _)) && w.push(tf(i, C, x)))), + (i = i.return)); + } + 0 !== w.length && s.push({ event: o, listeners: w }); + } + var rn = /\r\n?/g, + nn = /\u0000|\uFFFD/g; + function zf(s) { + return ('string' == typeof s ? s : '' + s).replace(rn, '\n').replace(nn, ''); + } + function Af(s, o, i) { + if (((o = zf(o)), zf(s) !== o && i)) throw Error(p(425)); + } + function Bf() {} + var sn = null, + on = null; + function Ef(s, o) { + return ( + 'textarea' === s || + 'noscript' === s || + 'string' == typeof o.children || + 'number' == typeof o.children || + ('object' == typeof o.dangerouslySetInnerHTML && + null !== o.dangerouslySetInnerHTML && + null != o.dangerouslySetInnerHTML.__html) + ); + } + var an = 'function' == typeof setTimeout ? setTimeout : void 0, + cn = 'function' == typeof clearTimeout ? clearTimeout : void 0, + ln = 'function' == typeof Promise ? Promise : void 0, + un = + 'function' == typeof queueMicrotask + ? queueMicrotask + : void 0 !== ln + ? function (s) { + return ln.resolve(null).then(s).catch(If); + } + : an; + function If(s) { + setTimeout(function () { + throw s; + }); + } + function Kf(s, o) { + var i = o, + a = 0; + do { + var u = i.nextSibling; + if ((s.removeChild(i), u && 8 === u.nodeType)) + if ('/$' === (i = u.data)) { + if (0 === a) return (s.removeChild(u), void bd(o)); + a--; + } else ('$' !== i && '$?' !== i && '$!' !== i) || a++; + i = u; + } while (i); + bd(o); + } + function Lf(s) { + for (; null != s; s = s.nextSibling) { + var o = s.nodeType; + if (1 === o || 3 === o) break; + if (8 === o) { + if ('$' === (o = s.data) || '$!' === o || '$?' === o) break; + if ('/$' === o) return null; + } + } + return s; + } + function Mf(s) { + s = s.previousSibling; + for (var o = 0; s; ) { + if (8 === s.nodeType) { + var i = s.data; + if ('$' === i || '$!' === i || '$?' === i) { + if (0 === o) return s; + o--; + } else '/$' === i && o++; + } + s = s.previousSibling; + } + return null; + } + var pn = Math.random().toString(36).slice(2), + hn = '__reactFiber$' + pn, + dn = '__reactProps$' + pn, + fn = '__reactContainer$' + pn, + mn = '__reactEvents$' + pn, + gn = '__reactListeners$' + pn, + yn = '__reactHandles$' + pn; + function Wc(s) { + var o = s[hn]; + if (o) return o; + for (var i = s.parentNode; i; ) { + if ((o = i[fn] || i[hn])) { + if (((i = o.alternate), null !== o.child || (null !== i && null !== i.child))) + for (s = Mf(s); null !== s; ) { + if ((i = s[hn])) return i; + s = Mf(s); + } + return o; + } + i = (s = i).parentNode; + } + return null; + } + function Cb(s) { + return !(s = s[hn] || s[fn]) || + (5 !== s.tag && 6 !== s.tag && 13 !== s.tag && 3 !== s.tag) + ? null + : s; + } + function ue(s) { + if (5 === s.tag || 6 === s.tag) return s.stateNode; + throw Error(p(33)); + } + function Db(s) { + return s[dn] || null; + } + var vn = [], + bn = -1; + function Uf(s) { + return { current: s }; + } + function E(s) { + 0 > bn || ((s.current = vn[bn]), (vn[bn] = null), bn--); + } + function G(s, o) { + (bn++, (vn[bn] = s.current), (s.current = o)); + } + var Sn = {}, + _n = Uf(Sn), + En = Uf(!1), + wn = Sn; + function Yf(s, o) { + var i = s.type.contextTypes; + if (!i) return Sn; + var a = s.stateNode; + if (a && a.__reactInternalMemoizedUnmaskedChildContext === o) + return a.__reactInternalMemoizedMaskedChildContext; + var u, + _ = {}; + for (u in i) _[u] = o[u]; + return ( + a && + (((s = s.stateNode).__reactInternalMemoizedUnmaskedChildContext = o), + (s.__reactInternalMemoizedMaskedChildContext = _)), + _ + ); + } + function Zf(s) { + return null != (s = s.childContextTypes); + } + function $f() { + (E(En), E(_n)); + } + function ag(s, o, i) { + if (_n.current !== Sn) throw Error(p(168)); + (G(_n, o), G(En, i)); + } + function bg(s, o, i) { + var a = s.stateNode; + if (((o = o.childContextTypes), 'function' != typeof a.getChildContext)) return i; + for (var u in (a = a.getChildContext())) + if (!(u in o)) throw Error(p(108, Ra(s) || 'Unknown', u)); + return we({}, i, a); + } + function cg(s) { + return ( + (s = ((s = s.stateNode) && s.__reactInternalMemoizedMergedChildContext) || Sn), + (wn = _n.current), + G(_n, s), + G(En, En.current), + !0 + ); + } + function dg(s, o, i) { + var a = s.stateNode; + if (!a) throw Error(p(169)); + (i + ? ((s = bg(s, o, wn)), + (a.__reactInternalMemoizedMergedChildContext = s), + E(En), + E(_n), + G(_n, s)) + : E(En), + G(En, i)); + } + var xn = null, + kn = !1, + On = !1; + function hg(s) { + null === xn ? (xn = [s]) : xn.push(s); + } + function jg() { + if (!On && null !== xn) { + On = !0; + var s = 0, + o = At; + try { + var i = xn; + for (At = 1; s < i.length; s++) { + var a = i[s]; + do { + a = a(!0); + } while (null !== a); + } + ((xn = null), (kn = !1)); + } catch (o) { + throw (null !== xn && (xn = xn.slice(s + 1)), ct(mt, jg), o); + } finally { + ((At = o), (On = !1)); + } + } + return null; + } + var An = [], + Cn = 0, + jn = null, + Pn = 0, + In = [], + Tn = 0, + Nn = null, + Mn = 1, + Rn = ''; + function tg(s, o) { + ((An[Cn++] = Pn), (An[Cn++] = jn), (jn = s), (Pn = o)); + } + function ug(s, o, i) { + ((In[Tn++] = Mn), (In[Tn++] = Rn), (In[Tn++] = Nn), (Nn = s)); + var a = Mn; + s = Rn; + var u = 32 - Et(a) - 1; + ((a &= ~(1 << u)), (i += 1)); + var _ = 32 - Et(o) + u; + if (30 < _) { + var w = u - (u % 5); + ((_ = (a & ((1 << w) - 1)).toString(32)), + (a >>= w), + (u -= w), + (Mn = (1 << (32 - Et(o) + u)) | (i << u) | a), + (Rn = _ + s)); + } else ((Mn = (1 << _) | (i << u) | a), (Rn = s)); + } + function vg(s) { + null !== s.return && (tg(s, 1), ug(s, 1, 0)); + } + function wg(s) { + for (; s === jn; ) ((jn = An[--Cn]), (An[Cn] = null), (Pn = An[--Cn]), (An[Cn] = null)); + for (; s === Nn; ) + ((Nn = In[--Tn]), + (In[Tn] = null), + (Rn = In[--Tn]), + (In[Tn] = null), + (Mn = In[--Tn]), + (In[Tn] = null)); + } + var Dn = null, + Ln = null, + Fn = !1, + Bn = null; + function Ag(s, o) { + var i = Bg(5, null, null, 0); + ((i.elementType = 'DELETED'), + (i.stateNode = o), + (i.return = s), + null === (o = s.deletions) ? ((s.deletions = [i]), (s.flags |= 16)) : o.push(i)); + } + function Cg(s, o) { + switch (s.tag) { + case 5: + var i = s.type; + return ( + null !== + (o = + 1 !== o.nodeType || i.toLowerCase() !== o.nodeName.toLowerCase() + ? null + : o) && ((s.stateNode = o), (Dn = s), (Ln = Lf(o.firstChild)), !0) + ); + case 6: + return ( + null !== (o = '' === s.pendingProps || 3 !== o.nodeType ? null : o) && + ((s.stateNode = o), (Dn = s), (Ln = null), !0) + ); + case 13: + return ( + null !== (o = 8 !== o.nodeType ? null : o) && + ((i = null !== Nn ? { id: Mn, overflow: Rn } : null), + (s.memoizedState = { dehydrated: o, treeContext: i, retryLane: 1073741824 }), + ((i = Bg(18, null, null, 0)).stateNode = o), + (i.return = s), + (s.child = i), + (Dn = s), + (Ln = null), + !0) + ); + default: + return !1; + } + } + function Dg(s) { + return !(!(1 & s.mode) || 128 & s.flags); + } + function Eg(s) { + if (Fn) { + var o = Ln; + if (o) { + var i = o; + if (!Cg(s, o)) { + if (Dg(s)) throw Error(p(418)); + o = Lf(i.nextSibling); + var a = Dn; + o && Cg(s, o) + ? Ag(a, i) + : ((s.flags = (-4097 & s.flags) | 2), (Fn = !1), (Dn = s)); + } + } else { + if (Dg(s)) throw Error(p(418)); + ((s.flags = (-4097 & s.flags) | 2), (Fn = !1), (Dn = s)); + } + } + } + function Fg(s) { + for (s = s.return; null !== s && 5 !== s.tag && 3 !== s.tag && 13 !== s.tag; ) + s = s.return; + Dn = s; + } + function Gg(s) { + if (s !== Dn) return !1; + if (!Fn) return (Fg(s), (Fn = !0), !1); + var o; + if ( + ((o = 3 !== s.tag) && + !(o = 5 !== s.tag) && + (o = 'head' !== (o = s.type) && 'body' !== o && !Ef(s.type, s.memoizedProps)), + o && (o = Ln)) + ) { + if (Dg(s)) throw (Hg(), Error(p(418))); + for (; o; ) (Ag(s, o), (o = Lf(o.nextSibling))); + } + if ((Fg(s), 13 === s.tag)) { + if (!(s = null !== (s = s.memoizedState) ? s.dehydrated : null)) throw Error(p(317)); + e: { + for (s = s.nextSibling, o = 0; s; ) { + if (8 === s.nodeType) { + var i = s.data; + if ('/$' === i) { + if (0 === o) { + Ln = Lf(s.nextSibling); + break e; + } + o--; + } else ('$' !== i && '$!' !== i && '$?' !== i) || o++; + } + s = s.nextSibling; + } + Ln = null; + } + } else Ln = Dn ? Lf(s.stateNode.nextSibling) : null; + return !0; + } + function Hg() { + for (var s = Ln; s; ) s = Lf(s.nextSibling); + } + function Ig() { + ((Ln = Dn = null), (Fn = !1)); + } + function Jg(s) { + null === Bn ? (Bn = [s]) : Bn.push(s); + } + var $n = V.ReactCurrentBatchConfig; + function Lg(s, o, i) { + if (null !== (s = i.ref) && 'function' != typeof s && 'object' != typeof s) { + if (i._owner) { + if ((i = i._owner)) { + if (1 !== i.tag) throw Error(p(309)); + var a = i.stateNode; + } + if (!a) throw Error(p(147, s)); + var u = a, + _ = '' + s; + return null !== o && + null !== o.ref && + 'function' == typeof o.ref && + o.ref._stringRef === _ + ? o.ref + : ((o = function (s) { + var o = u.refs; + null === s ? delete o[_] : (o[_] = s); + }), + (o._stringRef = _), + o); + } + if ('string' != typeof s) throw Error(p(284)); + if (!i._owner) throw Error(p(290, s)); + } + return s; + } + function Mg(s, o) { + throw ( + (s = Object.prototype.toString.call(o)), + Error( + p( + 31, + '[object Object]' === s + ? 'object with keys {' + Object.keys(o).join(', ') + '}' + : s + ) + ) + ); + } + function Ng(s) { + return (0, s._init)(s._payload); + } + function Og(s) { + function b(o, i) { + if (s) { + var a = o.deletions; + null === a ? ((o.deletions = [i]), (o.flags |= 16)) : a.push(i); + } + } + function c(o, i) { + if (!s) return null; + for (; null !== i; ) (b(o, i), (i = i.sibling)); + return null; + } + function d(s, o) { + for (s = new Map(); null !== o; ) + (null !== o.key ? s.set(o.key, o) : s.set(o.index, o), (o = o.sibling)); + return s; + } + function e(s, o) { + return (((s = Pg(s, o)).index = 0), (s.sibling = null), s); + } + function f(o, i, a) { + return ( + (o.index = a), + s + ? null !== (a = o.alternate) + ? (a = a.index) < i + ? ((o.flags |= 2), i) + : a + : ((o.flags |= 2), i) + : ((o.flags |= 1048576), i) + ); + } + function g(o) { + return (s && null === o.alternate && (o.flags |= 2), o); + } + function h(s, o, i, a) { + return null === o || 6 !== o.tag + ? (((o = Qg(i, s.mode, a)).return = s), o) + : (((o = e(o, i)).return = s), o); + } + function k(s, o, i, a) { + var u = i.type; + return u === Z + ? m(s, o, i.props.children, a, i.key) + : null !== o && + (o.elementType === u || + ('object' == typeof u && null !== u && u.$$typeof === ye && Ng(u) === o.type)) + ? (((a = e(o, i.props)).ref = Lg(s, o, i)), (a.return = s), a) + : (((a = Rg(i.type, i.key, i.props, null, s.mode, a)).ref = Lg(s, o, i)), + (a.return = s), + a); + } + function l(s, o, i, a) { + return null === o || + 4 !== o.tag || + o.stateNode.containerInfo !== i.containerInfo || + o.stateNode.implementation !== i.implementation + ? (((o = Sg(i, s.mode, a)).return = s), o) + : (((o = e(o, i.children || [])).return = s), o); + } + function m(s, o, i, a, u) { + return null === o || 7 !== o.tag + ? (((o = Tg(i, s.mode, a, u)).return = s), o) + : (((o = e(o, i)).return = s), o); + } + function q(s, o, i) { + if (('string' == typeof o && '' !== o) || 'number' == typeof o) + return (((o = Qg('' + o, s.mode, i)).return = s), o); + if ('object' == typeof o && null !== o) { + switch (o.$$typeof) { + case z: + return ( + ((i = Rg(o.type, o.key, o.props, null, s.mode, i)).ref = Lg(s, null, o)), + (i.return = s), + i + ); + case Y: + return (((o = Sg(o, s.mode, i)).return = s), o); + case ye: + return q(s, (0, o._init)(o._payload), i); + } + if (Pe(o) || Ka(o)) return (((o = Tg(o, s.mode, i, null)).return = s), o); + Mg(s, o); + } + return null; + } + function r(s, o, i, a) { + var u = null !== o ? o.key : null; + if (('string' == typeof i && '' !== i) || 'number' == typeof i) + return null !== u ? null : h(s, o, '' + i, a); + if ('object' == typeof i && null !== i) { + switch (i.$$typeof) { + case z: + return i.key === u ? k(s, o, i, a) : null; + case Y: + return i.key === u ? l(s, o, i, a) : null; + case ye: + return r(s, o, (u = i._init)(i._payload), a); + } + if (Pe(i) || Ka(i)) return null !== u ? null : m(s, o, i, a, null); + Mg(s, i); + } + return null; + } + function y(s, o, i, a, u) { + if (('string' == typeof a && '' !== a) || 'number' == typeof a) + return h(o, (s = s.get(i) || null), '' + a, u); + if ('object' == typeof a && null !== a) { + switch (a.$$typeof) { + case z: + return k(o, (s = s.get(null === a.key ? i : a.key) || null), a, u); + case Y: + return l(o, (s = s.get(null === a.key ? i : a.key) || null), a, u); + case ye: + return y(s, o, i, (0, a._init)(a._payload), u); + } + if (Pe(a) || Ka(a)) return m(o, (s = s.get(i) || null), a, u, null); + Mg(o, a); + } + return null; + } + function n(o, i, a, u) { + for ( + var _ = null, w = null, x = i, C = (i = 0), j = null; + null !== x && C < a.length; + C++ + ) { + x.index > C ? ((j = x), (x = null)) : (j = x.sibling); + var L = r(o, x, a[C], u); + if (null === L) { + null === x && (x = j); + break; + } + (s && x && null === L.alternate && b(o, x), + (i = f(L, i, C)), + null === w ? (_ = L) : (w.sibling = L), + (w = L), + (x = j)); + } + if (C === a.length) return (c(o, x), Fn && tg(o, C), _); + if (null === x) { + for (; C < a.length; C++) + null !== (x = q(o, a[C], u)) && + ((i = f(x, i, C)), null === w ? (_ = x) : (w.sibling = x), (w = x)); + return (Fn && tg(o, C), _); + } + for (x = d(o, x); C < a.length; C++) + null !== (j = y(x, o, C, a[C], u)) && + (s && null !== j.alternate && x.delete(null === j.key ? C : j.key), + (i = f(j, i, C)), + null === w ? (_ = j) : (w.sibling = j), + (w = j)); + return ( + s && + x.forEach(function (s) { + return b(o, s); + }), + Fn && tg(o, C), + _ + ); + } + function t(o, i, a, u) { + var _ = Ka(a); + if ('function' != typeof _) throw Error(p(150)); + if (null == (a = _.call(a))) throw Error(p(151)); + for ( + var w = (_ = null), x = i, C = (i = 0), j = null, L = a.next(); + null !== x && !L.done; + C++, L = a.next() + ) { + x.index > C ? ((j = x), (x = null)) : (j = x.sibling); + var B = r(o, x, L.value, u); + if (null === B) { + null === x && (x = j); + break; + } + (s && x && null === B.alternate && b(o, x), + (i = f(B, i, C)), + null === w ? (_ = B) : (w.sibling = B), + (w = B), + (x = j)); + } + if (L.done) return (c(o, x), Fn && tg(o, C), _); + if (null === x) { + for (; !L.done; C++, L = a.next()) + null !== (L = q(o, L.value, u)) && + ((i = f(L, i, C)), null === w ? (_ = L) : (w.sibling = L), (w = L)); + return (Fn && tg(o, C), _); + } + for (x = d(o, x); !L.done; C++, L = a.next()) + null !== (L = y(x, o, C, L.value, u)) && + (s && null !== L.alternate && x.delete(null === L.key ? C : L.key), + (i = f(L, i, C)), + null === w ? (_ = L) : (w.sibling = L), + (w = L)); + return ( + s && + x.forEach(function (s) { + return b(o, s); + }), + Fn && tg(o, C), + _ + ); + } + return function J(s, o, i, a) { + if ( + ('object' == typeof i && + null !== i && + i.type === Z && + null === i.key && + (i = i.props.children), + 'object' == typeof i && null !== i) + ) { + switch (i.$$typeof) { + case z: + e: { + for (var u = i.key, _ = o; null !== _; ) { + if (_.key === u) { + if ((u = i.type) === Z) { + if (7 === _.tag) { + (c(s, _.sibling), ((o = e(_, i.props.children)).return = s), (s = o)); + break e; + } + } else if ( + _.elementType === u || + ('object' == typeof u && + null !== u && + u.$$typeof === ye && + Ng(u) === _.type) + ) { + (c(s, _.sibling), + ((o = e(_, i.props)).ref = Lg(s, _, i)), + (o.return = s), + (s = o)); + break e; + } + c(s, _); + break; + } + (b(s, _), (_ = _.sibling)); + } + i.type === Z + ? (((o = Tg(i.props.children, s.mode, a, i.key)).return = s), (s = o)) + : (((a = Rg(i.type, i.key, i.props, null, s.mode, a)).ref = Lg(s, o, i)), + (a.return = s), + (s = a)); + } + return g(s); + case Y: + e: { + for (_ = i.key; null !== o; ) { + if (o.key === _) { + if ( + 4 === o.tag && + o.stateNode.containerInfo === i.containerInfo && + o.stateNode.implementation === i.implementation + ) { + (c(s, o.sibling), ((o = e(o, i.children || [])).return = s), (s = o)); + break e; + } + c(s, o); + break; + } + (b(s, o), (o = o.sibling)); + } + (((o = Sg(i, s.mode, a)).return = s), (s = o)); + } + return g(s); + case ye: + return J(s, o, (_ = i._init)(i._payload), a); + } + if (Pe(i)) return n(s, o, i, a); + if (Ka(i)) return t(s, o, i, a); + Mg(s, i); + } + return ('string' == typeof i && '' !== i) || 'number' == typeof i + ? ((i = '' + i), + null !== o && 6 === o.tag + ? (c(s, o.sibling), ((o = e(o, i)).return = s), (s = o)) + : (c(s, o), ((o = Qg(i, s.mode, a)).return = s), (s = o)), + g(s)) + : c(s, o); + }; + } + var qn = Og(!0), + Un = Og(!1), + Vn = Uf(null), + zn = null, + Wn = null, + Jn = null; + function $g() { + Jn = Wn = zn = null; + } + function ah(s) { + var o = Vn.current; + (E(Vn), (s._currentValue = o)); + } + function bh(s, o, i) { + for (; null !== s; ) { + var a = s.alternate; + if ( + ((s.childLanes & o) !== o + ? ((s.childLanes |= o), null !== a && (a.childLanes |= o)) + : null !== a && (a.childLanes & o) !== o && (a.childLanes |= o), + s === i) + ) + break; + s = s.return; + } + } + function ch(s, o) { + ((zn = s), + (Jn = Wn = null), + null !== (s = s.dependencies) && + null !== s.firstContext && + (!!(s.lanes & o) && (bs = !0), (s.firstContext = null))); + } + function eh(s) { + var o = s._currentValue; + if (Jn !== s) + if (((s = { context: s, memoizedValue: o, next: null }), null === Wn)) { + if (null === zn) throw Error(p(308)); + ((Wn = s), (zn.dependencies = { lanes: 0, firstContext: s })); + } else Wn = Wn.next = s; + return o; + } + var Hn = null; + function gh(s) { + null === Hn ? (Hn = [s]) : Hn.push(s); + } + function hh(s, o, i, a) { + var u = o.interleaved; + return ( + null === u ? ((i.next = i), gh(o)) : ((i.next = u.next), (u.next = i)), + (o.interleaved = i), + ih(s, a) + ); + } + function ih(s, o) { + s.lanes |= o; + var i = s.alternate; + for (null !== i && (i.lanes |= o), i = s, s = s.return; null !== s; ) + ((s.childLanes |= o), + null !== (i = s.alternate) && (i.childLanes |= o), + (i = s), + (s = s.return)); + return 3 === i.tag ? i.stateNode : null; + } + var Kn = !1; + function kh(s) { + s.updateQueue = { + baseState: s.memoizedState, + firstBaseUpdate: null, + lastBaseUpdate: null, + shared: { pending: null, interleaved: null, lanes: 0 }, + effects: null + }; + } + function lh(s, o) { + ((s = s.updateQueue), + o.updateQueue === s && + (o.updateQueue = { + baseState: s.baseState, + firstBaseUpdate: s.firstBaseUpdate, + lastBaseUpdate: s.lastBaseUpdate, + shared: s.shared, + effects: s.effects + })); + } + function mh(s, o) { + return { eventTime: s, lane: o, tag: 0, payload: null, callback: null, next: null }; + } + function nh(s, o, i) { + var a = s.updateQueue; + if (null === a) return null; + if (((a = a.shared), 2 & Ds)) { + var u = a.pending; + return ( + null === u ? (o.next = o) : ((o.next = u.next), (u.next = o)), + (a.pending = o), + ih(s, i) + ); + } + return ( + null === (u = a.interleaved) + ? ((o.next = o), gh(a)) + : ((o.next = u.next), (u.next = o)), + (a.interleaved = o), + ih(s, i) + ); + } + function oh(s, o, i) { + if (null !== (o = o.updateQueue) && ((o = o.shared), 4194240 & i)) { + var a = o.lanes; + ((i |= a &= s.pendingLanes), (o.lanes = i), Cc(s, i)); + } + } + function ph(s, o) { + var i = s.updateQueue, + a = s.alternate; + if (null !== a && i === (a = a.updateQueue)) { + var u = null, + _ = null; + if (null !== (i = i.firstBaseUpdate)) { + do { + var w = { + eventTime: i.eventTime, + lane: i.lane, + tag: i.tag, + payload: i.payload, + callback: i.callback, + next: null + }; + (null === _ ? (u = _ = w) : (_ = _.next = w), (i = i.next)); + } while (null !== i); + null === _ ? (u = _ = o) : (_ = _.next = o); + } else u = _ = o; + return ( + (i = { + baseState: a.baseState, + firstBaseUpdate: u, + lastBaseUpdate: _, + shared: a.shared, + effects: a.effects + }), + void (s.updateQueue = i) + ); + } + (null === (s = i.lastBaseUpdate) ? (i.firstBaseUpdate = o) : (s.next = o), + (i.lastBaseUpdate = o)); + } + function qh(s, o, i, a) { + var u = s.updateQueue; + Kn = !1; + var _ = u.firstBaseUpdate, + w = u.lastBaseUpdate, + x = u.shared.pending; + if (null !== x) { + u.shared.pending = null; + var C = x, + j = C.next; + ((C.next = null), null === w ? (_ = j) : (w.next = j), (w = C)); + var L = s.alternate; + null !== L && + (x = (L = L.updateQueue).lastBaseUpdate) !== w && + (null === x ? (L.firstBaseUpdate = j) : (x.next = j), (L.lastBaseUpdate = C)); + } + if (null !== _) { + var B = u.baseState; + for (w = 0, L = j = C = null, x = _; ; ) { + var $ = x.lane, + U = x.eventTime; + if ((a & $) === $) { + null !== L && + (L = L.next = + { + eventTime: U, + lane: 0, + tag: x.tag, + payload: x.payload, + callback: x.callback, + next: null + }); + e: { + var V = s, + z = x; + switch ((($ = o), (U = i), z.tag)) { + case 1: + if ('function' == typeof (V = z.payload)) { + B = V.call(U, B, $); + break e; + } + B = V; + break e; + case 3: + V.flags = (-65537 & V.flags) | 128; + case 0: + if ( + null == ($ = 'function' == typeof (V = z.payload) ? V.call(U, B, $) : V) + ) + break e; + B = we({}, B, $); + break e; + case 2: + Kn = !0; + } + } + null !== x.callback && + 0 !== x.lane && + ((s.flags |= 64), null === ($ = u.effects) ? (u.effects = [x]) : $.push(x)); + } else + ((U = { + eventTime: U, + lane: $, + tag: x.tag, + payload: x.payload, + callback: x.callback, + next: null + }), + null === L ? ((j = L = U), (C = B)) : (L = L.next = U), + (w |= $)); + if (null === (x = x.next)) { + if (null === (x = u.shared.pending)) break; + ((x = ($ = x).next), + ($.next = null), + (u.lastBaseUpdate = $), + (u.shared.pending = null)); + } + } + if ( + (null === L && (C = B), + (u.baseState = C), + (u.firstBaseUpdate = j), + (u.lastBaseUpdate = L), + null !== (o = u.shared.interleaved)) + ) { + u = o; + do { + ((w |= u.lane), (u = u.next)); + } while (u !== o); + } else null === _ && (u.shared.lanes = 0); + ((zs |= w), (s.lanes = w), (s.memoizedState = B)); + } + } + function sh(s, o, i) { + if (((s = o.effects), (o.effects = null), null !== s)) + for (o = 0; o < s.length; o++) { + var a = s[o], + u = a.callback; + if (null !== u) { + if (((a.callback = null), (a = i), 'function' != typeof u)) + throw Error(p(191, u)); + u.call(a); + } + } + } + var Gn = {}, + Yn = Uf(Gn), + Xn = Uf(Gn), + Qn = Uf(Gn); + function xh(s) { + if (s === Gn) throw Error(p(174)); + return s; + } + function yh(s, o) { + switch ((G(Qn, o), G(Xn, s), G(Yn, Gn), (s = o.nodeType))) { + case 9: + case 11: + o = (o = o.documentElement) ? o.namespaceURI : lb(null, ''); + break; + default: + o = lb( + (o = (s = 8 === s ? o.parentNode : o).namespaceURI || null), + (s = s.tagName) + ); + } + (E(Yn), G(Yn, o)); + } + function zh() { + (E(Yn), E(Xn), E(Qn)); + } + function Ah(s) { + xh(Qn.current); + var o = xh(Yn.current), + i = lb(o, s.type); + o !== i && (G(Xn, s), G(Yn, i)); + } + function Bh(s) { + Xn.current === s && (E(Yn), E(Xn)); + } + var Zn = Uf(0); + function Ch(s) { + for (var o = s; null !== o; ) { + if (13 === o.tag) { + var i = o.memoizedState; + if ( + null !== i && + (null === (i = i.dehydrated) || '$?' === i.data || '$!' === i.data) + ) + return o; + } else if (19 === o.tag && void 0 !== o.memoizedProps.revealOrder) { + if (128 & o.flags) return o; + } else if (null !== o.child) { + ((o.child.return = o), (o = o.child)); + continue; + } + if (o === s) break; + for (; null === o.sibling; ) { + if (null === o.return || o.return === s) return null; + o = o.return; + } + ((o.sibling.return = o.return), (o = o.sibling)); + } + return null; + } + var es = []; + function Eh() { + for (var s = 0; s < es.length; s++) es[s]._workInProgressVersionPrimary = null; + es.length = 0; + } + var ts = V.ReactCurrentDispatcher, + rs = V.ReactCurrentBatchConfig, + ns = 0, + ss = null, + os = null, + as = null, + cs = !1, + ls = !1, + us = 0, + ps = 0; + function P() { + throw Error(p(321)); + } + function Mh(s, o) { + if (null === o) return !1; + for (var i = 0; i < o.length && i < s.length; i++) if (!Dr(s[i], o[i])) return !1; + return !0; + } + function Nh(s, o, i, a, u, _) { + if ( + ((ns = _), + (ss = o), + (o.memoizedState = null), + (o.updateQueue = null), + (o.lanes = 0), + (ts.current = null === s || null === s.memoizedState ? ds : fs), + (s = i(a, u)), + ls) + ) { + _ = 0; + do { + if (((ls = !1), (us = 0), 25 <= _)) throw Error(p(301)); + ((_ += 1), + (as = os = null), + (o.updateQueue = null), + (ts.current = ms), + (s = i(a, u))); + } while (ls); + } + if ( + ((ts.current = hs), + (o = null !== os && null !== os.next), + (ns = 0), + (as = os = ss = null), + (cs = !1), + o) + ) + throw Error(p(300)); + return s; + } + function Sh() { + var s = 0 !== us; + return ((us = 0), s); + } + function Th() { + var s = { + memoizedState: null, + baseState: null, + baseQueue: null, + queue: null, + next: null + }; + return (null === as ? (ss.memoizedState = as = s) : (as = as.next = s), as); + } + function Uh() { + if (null === os) { + var s = ss.alternate; + s = null !== s ? s.memoizedState : null; + } else s = os.next; + var o = null === as ? ss.memoizedState : as.next; + if (null !== o) ((as = o), (os = s)); + else { + if (null === s) throw Error(p(310)); + ((s = { + memoizedState: (os = s).memoizedState, + baseState: os.baseState, + baseQueue: os.baseQueue, + queue: os.queue, + next: null + }), + null === as ? (ss.memoizedState = as = s) : (as = as.next = s)); + } + return as; + } + function Vh(s, o) { + return 'function' == typeof o ? o(s) : o; + } + function Wh(s) { + var o = Uh(), + i = o.queue; + if (null === i) throw Error(p(311)); + i.lastRenderedReducer = s; + var a = os, + u = a.baseQueue, + _ = i.pending; + if (null !== _) { + if (null !== u) { + var w = u.next; + ((u.next = _.next), (_.next = w)); + } + ((a.baseQueue = u = _), (i.pending = null)); + } + if (null !== u) { + ((_ = u.next), (a = a.baseState)); + var x = (w = null), + C = null, + j = _; + do { + var L = j.lane; + if ((ns & L) === L) + (null !== C && + (C = C.next = + { + lane: 0, + action: j.action, + hasEagerState: j.hasEagerState, + eagerState: j.eagerState, + next: null + }), + (a = j.hasEagerState ? j.eagerState : s(a, j.action))); + else { + var B = { + lane: L, + action: j.action, + hasEagerState: j.hasEagerState, + eagerState: j.eagerState, + next: null + }; + (null === C ? ((x = C = B), (w = a)) : (C = C.next = B), + (ss.lanes |= L), + (zs |= L)); + } + j = j.next; + } while (null !== j && j !== _); + (null === C ? (w = a) : (C.next = x), + Dr(a, o.memoizedState) || (bs = !0), + (o.memoizedState = a), + (o.baseState = w), + (o.baseQueue = C), + (i.lastRenderedState = a)); + } + if (null !== (s = i.interleaved)) { + u = s; + do { + ((_ = u.lane), (ss.lanes |= _), (zs |= _), (u = u.next)); + } while (u !== s); + } else null === u && (i.lanes = 0); + return [o.memoizedState, i.dispatch]; + } + function Xh(s) { + var o = Uh(), + i = o.queue; + if (null === i) throw Error(p(311)); + i.lastRenderedReducer = s; + var a = i.dispatch, + u = i.pending, + _ = o.memoizedState; + if (null !== u) { + i.pending = null; + var w = (u = u.next); + do { + ((_ = s(_, w.action)), (w = w.next)); + } while (w !== u); + (Dr(_, o.memoizedState) || (bs = !0), + (o.memoizedState = _), + null === o.baseQueue && (o.baseState = _), + (i.lastRenderedState = _)); + } + return [_, a]; + } + function Yh() {} + function Zh(s, o) { + var i = ss, + a = Uh(), + u = o(), + _ = !Dr(a.memoizedState, u); + if ( + (_ && ((a.memoizedState = u), (bs = !0)), + (a = a.queue), + $h(ai.bind(null, i, a, s), [s]), + a.getSnapshot !== o || _ || (null !== as && 1 & as.memoizedState.tag)) + ) { + if (((i.flags |= 2048), bi(9, ci.bind(null, i, a, u, o), void 0, null), null === Ls)) + throw Error(p(349)); + 30 & ns || di(i, o, u); + } + return u; + } + function di(s, o, i) { + ((s.flags |= 16384), + (s = { getSnapshot: o, value: i }), + null === (o = ss.updateQueue) + ? ((o = { lastEffect: null, stores: null }), (ss.updateQueue = o), (o.stores = [s])) + : null === (i = o.stores) + ? (o.stores = [s]) + : i.push(s)); + } + function ci(s, o, i, a) { + ((o.value = i), (o.getSnapshot = a), ei(o) && fi(s)); + } + function ai(s, o, i) { + return i(function () { + ei(o) && fi(s); + }); + } + function ei(s) { + var o = s.getSnapshot; + s = s.value; + try { + var i = o(); + return !Dr(s, i); + } catch (s) { + return !0; + } + } + function fi(s) { + var o = ih(s, 1); + null !== o && gi(o, s, 1, -1); + } + function hi(s) { + var o = Th(); + return ( + 'function' == typeof s && (s = s()), + (o.memoizedState = o.baseState = s), + (s = { + pending: null, + interleaved: null, + lanes: 0, + dispatch: null, + lastRenderedReducer: Vh, + lastRenderedState: s + }), + (o.queue = s), + (s = s.dispatch = ii.bind(null, ss, s)), + [o.memoizedState, s] + ); + } + function bi(s, o, i, a) { + return ( + (s = { tag: s, create: o, destroy: i, deps: a, next: null }), + null === (o = ss.updateQueue) + ? ((o = { lastEffect: null, stores: null }), + (ss.updateQueue = o), + (o.lastEffect = s.next = s)) + : null === (i = o.lastEffect) + ? (o.lastEffect = s.next = s) + : ((a = i.next), (i.next = s), (s.next = a), (o.lastEffect = s)), + s + ); + } + function ji() { + return Uh().memoizedState; + } + function ki(s, o, i, a) { + var u = Th(); + ((ss.flags |= s), (u.memoizedState = bi(1 | o, i, void 0, void 0 === a ? null : a))); + } + function li(s, o, i, a) { + var u = Uh(); + a = void 0 === a ? null : a; + var _ = void 0; + if (null !== os) { + var w = os.memoizedState; + if (((_ = w.destroy), null !== a && Mh(a, w.deps))) + return void (u.memoizedState = bi(o, i, _, a)); + } + ((ss.flags |= s), (u.memoizedState = bi(1 | o, i, _, a))); + } + function mi(s, o) { + return ki(8390656, 8, s, o); + } + function $h(s, o) { + return li(2048, 8, s, o); + } + function ni(s, o) { + return li(4, 2, s, o); + } + function oi(s, o) { + return li(4, 4, s, o); + } + function pi(s, o) { + return 'function' == typeof o + ? ((s = s()), + o(s), + function () { + o(null); + }) + : null != o + ? ((s = s()), + (o.current = s), + function () { + o.current = null; + }) + : void 0; + } + function qi(s, o, i) { + return ((i = null != i ? i.concat([s]) : null), li(4, 4, pi.bind(null, o, s), i)); + } + function ri() {} + function si(s, o) { + var i = Uh(); + o = void 0 === o ? null : o; + var a = i.memoizedState; + return null !== a && null !== o && Mh(o, a[1]) ? a[0] : ((i.memoizedState = [s, o]), s); + } + function ti(s, o) { + var i = Uh(); + o = void 0 === o ? null : o; + var a = i.memoizedState; + return null !== a && null !== o && Mh(o, a[1]) + ? a[0] + : ((s = s()), (i.memoizedState = [s, o]), s); + } + function ui(s, o, i) { + return 21 & ns + ? (Dr(i, o) || ((i = yc()), (ss.lanes |= i), (zs |= i), (s.baseState = !0)), o) + : (s.baseState && ((s.baseState = !1), (bs = !0)), (s.memoizedState = i)); + } + function vi(s, o) { + var i = At; + ((At = 0 !== i && 4 > i ? i : 4), s(!0)); + var a = rs.transition; + rs.transition = {}; + try { + (s(!1), o()); + } finally { + ((At = i), (rs.transition = a)); + } + } + function wi() { + return Uh().memoizedState; + } + function xi(s, o, i) { + var a = yi(s); + if ( + ((i = { lane: a, action: i, hasEagerState: !1, eagerState: null, next: null }), zi(s)) + ) + Ai(o, i); + else if (null !== (i = hh(s, o, i, a))) { + (gi(i, s, a, R()), Bi(i, o, a)); + } + } + function ii(s, o, i) { + var a = yi(s), + u = { lane: a, action: i, hasEagerState: !1, eagerState: null, next: null }; + if (zi(s)) Ai(o, u); + else { + var _ = s.alternate; + if ( + 0 === s.lanes && + (null === _ || 0 === _.lanes) && + null !== (_ = o.lastRenderedReducer) + ) + try { + var w = o.lastRenderedState, + x = _(w, i); + if (((u.hasEagerState = !0), (u.eagerState = x), Dr(x, w))) { + var C = o.interleaved; + return ( + null === C ? ((u.next = u), gh(o)) : ((u.next = C.next), (C.next = u)), + void (o.interleaved = u) + ); + } + } catch (s) {} + null !== (i = hh(s, o, u, a)) && (gi(i, s, a, (u = R())), Bi(i, o, a)); + } + } + function zi(s) { + var o = s.alternate; + return s === ss || (null !== o && o === ss); + } + function Ai(s, o) { + ls = cs = !0; + var i = s.pending; + (null === i ? (o.next = o) : ((o.next = i.next), (i.next = o)), (s.pending = o)); + } + function Bi(s, o, i) { + if (4194240 & i) { + var a = o.lanes; + ((i |= a &= s.pendingLanes), (o.lanes = i), Cc(s, i)); + } + } + var hs = { + readContext: eh, + useCallback: P, + useContext: P, + useEffect: P, + useImperativeHandle: P, + useInsertionEffect: P, + useLayoutEffect: P, + useMemo: P, + useReducer: P, + useRef: P, + useState: P, + useDebugValue: P, + useDeferredValue: P, + useTransition: P, + useMutableSource: P, + useSyncExternalStore: P, + useId: P, + unstable_isNewReconciler: !1 + }, + ds = { + readContext: eh, + useCallback: function (s, o) { + return ((Th().memoizedState = [s, void 0 === o ? null : o]), s); + }, + useContext: eh, + useEffect: mi, + useImperativeHandle: function (s, o, i) { + return ( + (i = null != i ? i.concat([s]) : null), + ki(4194308, 4, pi.bind(null, o, s), i) + ); + }, + useLayoutEffect: function (s, o) { + return ki(4194308, 4, s, o); + }, + useInsertionEffect: function (s, o) { + return ki(4, 2, s, o); + }, + useMemo: function (s, o) { + var i = Th(); + return ((o = void 0 === o ? null : o), (s = s()), (i.memoizedState = [s, o]), s); + }, + useReducer: function (s, o, i) { + var a = Th(); + return ( + (o = void 0 !== i ? i(o) : o), + (a.memoizedState = a.baseState = o), + (s = { + pending: null, + interleaved: null, + lanes: 0, + dispatch: null, + lastRenderedReducer: s, + lastRenderedState: o + }), + (a.queue = s), + (s = s.dispatch = xi.bind(null, ss, s)), + [a.memoizedState, s] + ); + }, + useRef: function (s) { + return ((s = { current: s }), (Th().memoizedState = s)); + }, + useState: hi, + useDebugValue: ri, + useDeferredValue: function (s) { + return (Th().memoizedState = s); + }, + useTransition: function () { + var s = hi(!1), + o = s[0]; + return ((s = vi.bind(null, s[1])), (Th().memoizedState = s), [o, s]); + }, + useMutableSource: function () {}, + useSyncExternalStore: function (s, o, i) { + var a = ss, + u = Th(); + if (Fn) { + if (void 0 === i) throw Error(p(407)); + i = i(); + } else { + if (((i = o()), null === Ls)) throw Error(p(349)); + 30 & ns || di(a, o, i); + } + u.memoizedState = i; + var _ = { value: i, getSnapshot: o }; + return ( + (u.queue = _), + mi(ai.bind(null, a, _, s), [s]), + (a.flags |= 2048), + bi(9, ci.bind(null, a, _, i, o), void 0, null), + i + ); + }, + useId: function () { + var s = Th(), + o = Ls.identifierPrefix; + if (Fn) { + var i = Rn; + ((o = ':' + o + 'R' + (i = (Mn & ~(1 << (32 - Et(Mn) - 1))).toString(32) + i)), + 0 < (i = us++) && (o += 'H' + i.toString(32)), + (o += ':')); + } else o = ':' + o + 'r' + (i = ps++).toString(32) + ':'; + return (s.memoizedState = o); + }, + unstable_isNewReconciler: !1 + }, + fs = { + readContext: eh, + useCallback: si, + useContext: eh, + useEffect: $h, + useImperativeHandle: qi, + useInsertionEffect: ni, + useLayoutEffect: oi, + useMemo: ti, + useReducer: Wh, + useRef: ji, + useState: function () { + return Wh(Vh); + }, + useDebugValue: ri, + useDeferredValue: function (s) { + return ui(Uh(), os.memoizedState, s); + }, + useTransition: function () { + return [Wh(Vh)[0], Uh().memoizedState]; + }, + useMutableSource: Yh, + useSyncExternalStore: Zh, + useId: wi, + unstable_isNewReconciler: !1 + }, + ms = { + readContext: eh, + useCallback: si, + useContext: eh, + useEffect: $h, + useImperativeHandle: qi, + useInsertionEffect: ni, + useLayoutEffect: oi, + useMemo: ti, + useReducer: Xh, + useRef: ji, + useState: function () { + return Xh(Vh); + }, + useDebugValue: ri, + useDeferredValue: function (s) { + var o = Uh(); + return null === os ? (o.memoizedState = s) : ui(o, os.memoizedState, s); + }, + useTransition: function () { + return [Xh(Vh)[0], Uh().memoizedState]; + }, + useMutableSource: Yh, + useSyncExternalStore: Zh, + useId: wi, + unstable_isNewReconciler: !1 + }; + function Ci(s, o) { + if (s && s.defaultProps) { + for (var i in ((o = we({}, o)), (s = s.defaultProps))) + void 0 === o[i] && (o[i] = s[i]); + return o; + } + return o; + } + function Di(s, o, i, a) { + ((i = null == (i = i(a, (o = s.memoizedState))) ? o : we({}, o, i)), + (s.memoizedState = i), + 0 === s.lanes && (s.updateQueue.baseState = i)); + } + var gs = { + isMounted: function (s) { + return !!(s = s._reactInternals) && Vb(s) === s; + }, + enqueueSetState: function (s, o, i) { + s = s._reactInternals; + var a = R(), + u = yi(s), + _ = mh(a, u); + ((_.payload = o), + null != i && (_.callback = i), + null !== (o = nh(s, _, u)) && (gi(o, s, u, a), oh(o, s, u))); + }, + enqueueReplaceState: function (s, o, i) { + s = s._reactInternals; + var a = R(), + u = yi(s), + _ = mh(a, u); + ((_.tag = 1), + (_.payload = o), + null != i && (_.callback = i), + null !== (o = nh(s, _, u)) && (gi(o, s, u, a), oh(o, s, u))); + }, + enqueueForceUpdate: function (s, o) { + s = s._reactInternals; + var i = R(), + a = yi(s), + u = mh(i, a); + ((u.tag = 2), + null != o && (u.callback = o), + null !== (o = nh(s, u, a)) && (gi(o, s, a, i), oh(o, s, a))); + } + }; + function Fi(s, o, i, a, u, _, w) { + return 'function' == typeof (s = s.stateNode).shouldComponentUpdate + ? s.shouldComponentUpdate(a, _, w) + : !o.prototype || !o.prototype.isPureReactComponent || !Ie(i, a) || !Ie(u, _); + } + function Gi(s, o, i) { + var a = !1, + u = Sn, + _ = o.contextType; + return ( + 'object' == typeof _ && null !== _ + ? (_ = eh(_)) + : ((u = Zf(o) ? wn : _n.current), + (_ = (a = null != (a = o.contextTypes)) ? Yf(s, u) : Sn)), + (o = new o(i, _)), + (s.memoizedState = null !== o.state && void 0 !== o.state ? o.state : null), + (o.updater = gs), + (s.stateNode = o), + (o._reactInternals = s), + a && + (((s = s.stateNode).__reactInternalMemoizedUnmaskedChildContext = u), + (s.__reactInternalMemoizedMaskedChildContext = _)), + o + ); + } + function Hi(s, o, i, a) { + ((s = o.state), + 'function' == typeof o.componentWillReceiveProps && o.componentWillReceiveProps(i, a), + 'function' == typeof o.UNSAFE_componentWillReceiveProps && + o.UNSAFE_componentWillReceiveProps(i, a), + o.state !== s && gs.enqueueReplaceState(o, o.state, null)); + } + function Ii(s, o, i, a) { + var u = s.stateNode; + ((u.props = i), (u.state = s.memoizedState), (u.refs = {}), kh(s)); + var _ = o.contextType; + ('object' == typeof _ && null !== _ + ? (u.context = eh(_)) + : ((_ = Zf(o) ? wn : _n.current), (u.context = Yf(s, _))), + (u.state = s.memoizedState), + 'function' == typeof (_ = o.getDerivedStateFromProps) && + (Di(s, o, _, i), (u.state = s.memoizedState)), + 'function' == typeof o.getDerivedStateFromProps || + 'function' == typeof u.getSnapshotBeforeUpdate || + ('function' != typeof u.UNSAFE_componentWillMount && + 'function' != typeof u.componentWillMount) || + ((o = u.state), + 'function' == typeof u.componentWillMount && u.componentWillMount(), + 'function' == typeof u.UNSAFE_componentWillMount && u.UNSAFE_componentWillMount(), + o !== u.state && gs.enqueueReplaceState(u, u.state, null), + qh(s, i, u, a), + (u.state = s.memoizedState)), + 'function' == typeof u.componentDidMount && (s.flags |= 4194308)); + } + function Ji(s, o) { + try { + var i = '', + a = o; + do { + ((i += Pa(a)), (a = a.return)); + } while (a); + var u = i; + } catch (s) { + u = '\nError generating stack: ' + s.message + '\n' + s.stack; + } + return { value: s, source: o, stack: u, digest: null }; + } + function Ki(s, o, i) { + return { + value: s, + source: null, + stack: null != i ? i : null, + digest: null != o ? o : null + }; + } + function Li(s, o) { + try { + console.error(o.value); + } catch (s) { + setTimeout(function () { + throw s; + }); + } + } + var ys = 'function' == typeof WeakMap ? WeakMap : Map; + function Ni(s, o, i) { + (((i = mh(-1, i)).tag = 3), (i.payload = { element: null })); + var a = o.value; + return ( + (i.callback = function () { + (Qs || ((Qs = !0), (Zs = a)), Li(0, o)); + }), + i + ); + } + function Qi(s, o, i) { + (i = mh(-1, i)).tag = 3; + var a = s.type.getDerivedStateFromError; + if ('function' == typeof a) { + var u = o.value; + ((i.payload = function () { + return a(u); + }), + (i.callback = function () { + Li(0, o); + })); + } + var _ = s.stateNode; + return ( + null !== _ && + 'function' == typeof _.componentDidCatch && + (i.callback = function () { + (Li(0, o), + 'function' != typeof a && + (null === eo ? (eo = new Set([this])) : eo.add(this))); + var s = o.stack; + this.componentDidCatch(o.value, { componentStack: null !== s ? s : '' }); + }), + i + ); + } + function Si(s, o, i) { + var a = s.pingCache; + if (null === a) { + a = s.pingCache = new ys(); + var u = new Set(); + a.set(o, u); + } else void 0 === (u = a.get(o)) && ((u = new Set()), a.set(o, u)); + u.has(i) || (u.add(i), (s = Ti.bind(null, s, o, i)), o.then(s, s)); + } + function Ui(s) { + do { + var o; + if ( + ((o = 13 === s.tag) && + (o = null === (o = s.memoizedState) || null !== o.dehydrated), + o) + ) + return s; + s = s.return; + } while (null !== s); + return null; + } + function Vi(s, o, i, a, u) { + return 1 & s.mode + ? ((s.flags |= 65536), (s.lanes = u), s) + : (s === o + ? (s.flags |= 65536) + : ((s.flags |= 128), + (i.flags |= 131072), + (i.flags &= -52805), + 1 === i.tag && + (null === i.alternate + ? (i.tag = 17) + : (((o = mh(-1, 1)).tag = 2), nh(i, o, 1))), + (i.lanes |= 1)), + s); + } + var vs = V.ReactCurrentOwner, + bs = !1; + function Xi(s, o, i, a) { + o.child = null === s ? Un(o, null, i, a) : qn(o, s.child, i, a); + } + function Yi(s, o, i, a, u) { + i = i.render; + var _ = o.ref; + return ( + ch(o, u), + (a = Nh(s, o, i, a, _, u)), + (i = Sh()), + null === s || bs + ? (Fn && i && vg(o), (o.flags |= 1), Xi(s, o, a, u), o.child) + : ((o.updateQueue = s.updateQueue), + (o.flags &= -2053), + (s.lanes &= ~u), + Zi(s, o, u)) + ); + } + function $i(s, o, i, a, u) { + if (null === s) { + var _ = i.type; + return 'function' != typeof _ || + aj(_) || + void 0 !== _.defaultProps || + null !== i.compare || + void 0 !== i.defaultProps + ? (((s = Rg(i.type, null, a, o, o.mode, u)).ref = o.ref), + (s.return = o), + (o.child = s)) + : ((o.tag = 15), (o.type = _), bj(s, o, _, a, u)); + } + if (((_ = s.child), !(s.lanes & u))) { + var w = _.memoizedProps; + if ((i = null !== (i = i.compare) ? i : Ie)(w, a) && s.ref === o.ref) + return Zi(s, o, u); + } + return ((o.flags |= 1), ((s = Pg(_, a)).ref = o.ref), (s.return = o), (o.child = s)); + } + function bj(s, o, i, a, u) { + if (null !== s) { + var _ = s.memoizedProps; + if (Ie(_, a) && s.ref === o.ref) { + if (((bs = !1), (o.pendingProps = a = _), !(s.lanes & u))) + return ((o.lanes = s.lanes), Zi(s, o, u)); + 131072 & s.flags && (bs = !0); + } + } + return cj(s, o, i, a, u); + } + function dj(s, o, i) { + var a = o.pendingProps, + u = a.children, + _ = null !== s ? s.memoizedState : null; + if ('hidden' === a.mode) + if (1 & o.mode) { + if (!(1073741824 & i)) + return ( + (s = null !== _ ? _.baseLanes | i : i), + (o.lanes = o.childLanes = 1073741824), + (o.memoizedState = { baseLanes: s, cachePool: null, transitions: null }), + (o.updateQueue = null), + G(qs, $s), + ($s |= s), + null + ); + ((o.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }), + (a = null !== _ ? _.baseLanes : i), + G(qs, $s), + ($s |= a)); + } else + ((o.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }), + G(qs, $s), + ($s |= i)); + else + (null !== _ ? ((a = _.baseLanes | i), (o.memoizedState = null)) : (a = i), + G(qs, $s), + ($s |= a)); + return (Xi(s, o, u, i), o.child); + } + function gj(s, o) { + var i = o.ref; + ((null === s && null !== i) || (null !== s && s.ref !== i)) && + ((o.flags |= 512), (o.flags |= 2097152)); + } + function cj(s, o, i, a, u) { + var _ = Zf(i) ? wn : _n.current; + return ( + (_ = Yf(o, _)), + ch(o, u), + (i = Nh(s, o, i, a, _, u)), + (a = Sh()), + null === s || bs + ? (Fn && a && vg(o), (o.flags |= 1), Xi(s, o, i, u), o.child) + : ((o.updateQueue = s.updateQueue), + (o.flags &= -2053), + (s.lanes &= ~u), + Zi(s, o, u)) + ); + } + function hj(s, o, i, a, u) { + if (Zf(i)) { + var _ = !0; + cg(o); + } else _ = !1; + if ((ch(o, u), null === o.stateNode)) (ij(s, o), Gi(o, i, a), Ii(o, i, a, u), (a = !0)); + else if (null === s) { + var w = o.stateNode, + x = o.memoizedProps; + w.props = x; + var C = w.context, + j = i.contextType; + 'object' == typeof j && null !== j + ? (j = eh(j)) + : (j = Yf(o, (j = Zf(i) ? wn : _n.current))); + var L = i.getDerivedStateFromProps, + B = 'function' == typeof L || 'function' == typeof w.getSnapshotBeforeUpdate; + (B || + ('function' != typeof w.UNSAFE_componentWillReceiveProps && + 'function' != typeof w.componentWillReceiveProps) || + ((x !== a || C !== j) && Hi(o, w, a, j)), + (Kn = !1)); + var $ = o.memoizedState; + ((w.state = $), + qh(o, a, w, u), + (C = o.memoizedState), + x !== a || $ !== C || En.current || Kn + ? ('function' == typeof L && (Di(o, i, L, a), (C = o.memoizedState)), + (x = Kn || Fi(o, i, x, a, $, C, j)) + ? (B || + ('function' != typeof w.UNSAFE_componentWillMount && + 'function' != typeof w.componentWillMount) || + ('function' == typeof w.componentWillMount && w.componentWillMount(), + 'function' == typeof w.UNSAFE_componentWillMount && + w.UNSAFE_componentWillMount()), + 'function' == typeof w.componentDidMount && (o.flags |= 4194308)) + : ('function' == typeof w.componentDidMount && (o.flags |= 4194308), + (o.memoizedProps = a), + (o.memoizedState = C)), + (w.props = a), + (w.state = C), + (w.context = j), + (a = x)) + : ('function' == typeof w.componentDidMount && (o.flags |= 4194308), (a = !1))); + } else { + ((w = o.stateNode), + lh(s, o), + (x = o.memoizedProps), + (j = o.type === o.elementType ? x : Ci(o.type, x)), + (w.props = j), + (B = o.pendingProps), + ($ = w.context), + 'object' == typeof (C = i.contextType) && null !== C + ? (C = eh(C)) + : (C = Yf(o, (C = Zf(i) ? wn : _n.current)))); + var U = i.getDerivedStateFromProps; + ((L = 'function' == typeof U || 'function' == typeof w.getSnapshotBeforeUpdate) || + ('function' != typeof w.UNSAFE_componentWillReceiveProps && + 'function' != typeof w.componentWillReceiveProps) || + ((x !== B || $ !== C) && Hi(o, w, a, C)), + (Kn = !1), + ($ = o.memoizedState), + (w.state = $), + qh(o, a, w, u)); + var V = o.memoizedState; + x !== B || $ !== V || En.current || Kn + ? ('function' == typeof U && (Di(o, i, U, a), (V = o.memoizedState)), + (j = Kn || Fi(o, i, j, a, $, V, C) || !1) + ? (L || + ('function' != typeof w.UNSAFE_componentWillUpdate && + 'function' != typeof w.componentWillUpdate) || + ('function' == typeof w.componentWillUpdate && + w.componentWillUpdate(a, V, C), + 'function' == typeof w.UNSAFE_componentWillUpdate && + w.UNSAFE_componentWillUpdate(a, V, C)), + 'function' == typeof w.componentDidUpdate && (o.flags |= 4), + 'function' == typeof w.getSnapshotBeforeUpdate && (o.flags |= 1024)) + : ('function' != typeof w.componentDidUpdate || + (x === s.memoizedProps && $ === s.memoizedState) || + (o.flags |= 4), + 'function' != typeof w.getSnapshotBeforeUpdate || + (x === s.memoizedProps && $ === s.memoizedState) || + (o.flags |= 1024), + (o.memoizedProps = a), + (o.memoizedState = V)), + (w.props = a), + (w.state = V), + (w.context = C), + (a = j)) + : ('function' != typeof w.componentDidUpdate || + (x === s.memoizedProps && $ === s.memoizedState) || + (o.flags |= 4), + 'function' != typeof w.getSnapshotBeforeUpdate || + (x === s.memoizedProps && $ === s.memoizedState) || + (o.flags |= 1024), + (a = !1)); + } + return jj(s, o, i, a, _, u); + } + function jj(s, o, i, a, u, _) { + gj(s, o); + var w = !!(128 & o.flags); + if (!a && !w) return (u && dg(o, i, !1), Zi(s, o, _)); + ((a = o.stateNode), (vs.current = o)); + var x = w && 'function' != typeof i.getDerivedStateFromError ? null : a.render(); + return ( + (o.flags |= 1), + null !== s && w + ? ((o.child = qn(o, s.child, null, _)), (o.child = qn(o, null, x, _))) + : Xi(s, o, x, _), + (o.memoizedState = a.state), + u && dg(o, i, !0), + o.child + ); + } + function kj(s) { + var o = s.stateNode; + (o.pendingContext + ? ag(0, o.pendingContext, o.pendingContext !== o.context) + : o.context && ag(0, o.context, !1), + yh(s, o.containerInfo)); + } + function lj(s, o, i, a, u) { + return (Ig(), Jg(u), (o.flags |= 256), Xi(s, o, i, a), o.child); + } + var Ss, + _s, + Es, + ws = { dehydrated: null, treeContext: null, retryLane: 0 }; + function nj(s) { + return { baseLanes: s, cachePool: null, transitions: null }; + } + function oj(s, o, i) { + var a, + u = o.pendingProps, + _ = Zn.current, + w = !1, + x = !!(128 & o.flags); + if ( + ((a = x) || (a = (null === s || null !== s.memoizedState) && !!(2 & _)), + a + ? ((w = !0), (o.flags &= -129)) + : (null !== s && null === s.memoizedState) || (_ |= 1), + G(Zn, 1 & _), + null === s) + ) + return ( + Eg(o), + null !== (s = o.memoizedState) && null !== (s = s.dehydrated) + ? (1 & o.mode + ? '$!' === s.data + ? (o.lanes = 8) + : (o.lanes = 1073741824) + : (o.lanes = 1), + null) + : ((x = u.children), + (s = u.fallback), + w + ? ((u = o.mode), + (w = o.child), + (x = { mode: 'hidden', children: x }), + 1 & u || null === w + ? (w = pj(x, u, 0, null)) + : ((w.childLanes = 0), (w.pendingProps = x)), + (s = Tg(s, u, i, null)), + (w.return = o), + (s.return = o), + (w.sibling = s), + (o.child = w), + (o.child.memoizedState = nj(i)), + (o.memoizedState = ws), + s) + : qj(o, x)) + ); + if (null !== (_ = s.memoizedState) && null !== (a = _.dehydrated)) + return (function rj(s, o, i, a, u, _, w) { + if (i) + return 256 & o.flags + ? ((o.flags &= -257), sj(s, o, w, (a = Ki(Error(p(422)))))) + : null !== o.memoizedState + ? ((o.child = s.child), (o.flags |= 128), null) + : ((_ = a.fallback), + (u = o.mode), + (a = pj({ mode: 'visible', children: a.children }, u, 0, null)), + ((_ = Tg(_, u, w, null)).flags |= 2), + (a.return = o), + (_.return = o), + (a.sibling = _), + (o.child = a), + 1 & o.mode && qn(o, s.child, null, w), + (o.child.memoizedState = nj(w)), + (o.memoizedState = ws), + _); + if (!(1 & o.mode)) return sj(s, o, w, null); + if ('$!' === u.data) { + if ((a = u.nextSibling && u.nextSibling.dataset)) var x = a.dgst; + return ((a = x), sj(s, o, w, (a = Ki((_ = Error(p(419))), a, void 0)))); + } + if (((x = !!(w & s.childLanes)), bs || x)) { + if (null !== (a = Ls)) { + switch (w & -w) { + case 4: + u = 2; + break; + case 16: + u = 8; + break; + case 64: + case 128: + case 256: + case 512: + case 1024: + case 2048: + case 4096: + case 8192: + case 16384: + case 32768: + case 65536: + case 131072: + case 262144: + case 524288: + case 1048576: + case 2097152: + case 4194304: + case 8388608: + case 16777216: + case 33554432: + case 67108864: + u = 32; + break; + case 536870912: + u = 268435456; + break; + default: + u = 0; + } + 0 !== (u = u & (a.suspendedLanes | w) ? 0 : u) && + u !== _.retryLane && + ((_.retryLane = u), ih(s, u), gi(a, s, u, -1)); + } + return (tj(), sj(s, o, w, (a = Ki(Error(p(421)))))); + } + return '$?' === u.data + ? ((o.flags |= 128), + (o.child = s.child), + (o = uj.bind(null, s)), + (u._reactRetry = o), + null) + : ((s = _.treeContext), + (Ln = Lf(u.nextSibling)), + (Dn = o), + (Fn = !0), + (Bn = null), + null !== s && + ((In[Tn++] = Mn), + (In[Tn++] = Rn), + (In[Tn++] = Nn), + (Mn = s.id), + (Rn = s.overflow), + (Nn = o)), + (o = qj(o, a.children)), + (o.flags |= 4096), + o); + })(s, o, x, u, a, _, i); + if (w) { + ((w = u.fallback), (x = o.mode), (a = (_ = s.child).sibling)); + var C = { mode: 'hidden', children: u.children }; + return ( + 1 & x || o.child === _ + ? ((u = Pg(_, C)).subtreeFlags = 14680064 & _.subtreeFlags) + : (((u = o.child).childLanes = 0), (u.pendingProps = C), (o.deletions = null)), + null !== a ? (w = Pg(a, w)) : ((w = Tg(w, x, i, null)).flags |= 2), + (w.return = o), + (u.return = o), + (u.sibling = w), + (o.child = u), + (u = w), + (w = o.child), + (x = + null === (x = s.child.memoizedState) + ? nj(i) + : { baseLanes: x.baseLanes | i, cachePool: null, transitions: x.transitions }), + (w.memoizedState = x), + (w.childLanes = s.childLanes & ~i), + (o.memoizedState = ws), + u + ); + } + return ( + (s = (w = s.child).sibling), + (u = Pg(w, { mode: 'visible', children: u.children })), + !(1 & o.mode) && (u.lanes = i), + (u.return = o), + (u.sibling = null), + null !== s && + (null === (i = o.deletions) ? ((o.deletions = [s]), (o.flags |= 16)) : i.push(s)), + (o.child = u), + (o.memoizedState = null), + u + ); + } + function qj(s, o) { + return ( + ((o = pj({ mode: 'visible', children: o }, s.mode, 0, null)).return = s), + (s.child = o) + ); + } + function sj(s, o, i, a) { + return ( + null !== a && Jg(a), + qn(o, s.child, null, i), + ((s = qj(o, o.pendingProps.children)).flags |= 2), + (o.memoizedState = null), + s + ); + } + function vj(s, o, i) { + s.lanes |= o; + var a = s.alternate; + (null !== a && (a.lanes |= o), bh(s.return, o, i)); + } + function wj(s, o, i, a, u) { + var _ = s.memoizedState; + null === _ + ? (s.memoizedState = { + isBackwards: o, + rendering: null, + renderingStartTime: 0, + last: a, + tail: i, + tailMode: u + }) + : ((_.isBackwards = o), + (_.rendering = null), + (_.renderingStartTime = 0), + (_.last = a), + (_.tail = i), + (_.tailMode = u)); + } + function xj(s, o, i) { + var a = o.pendingProps, + u = a.revealOrder, + _ = a.tail; + if ((Xi(s, o, a.children, i), 2 & (a = Zn.current))) + ((a = (1 & a) | 2), (o.flags |= 128)); + else { + if (null !== s && 128 & s.flags) + e: for (s = o.child; null !== s; ) { + if (13 === s.tag) null !== s.memoizedState && vj(s, i, o); + else if (19 === s.tag) vj(s, i, o); + else if (null !== s.child) { + ((s.child.return = s), (s = s.child)); + continue; + } + if (s === o) break e; + for (; null === s.sibling; ) { + if (null === s.return || s.return === o) break e; + s = s.return; + } + ((s.sibling.return = s.return), (s = s.sibling)); + } + a &= 1; + } + if ((G(Zn, a), 1 & o.mode)) + switch (u) { + case 'forwards': + for (i = o.child, u = null; null !== i; ) + (null !== (s = i.alternate) && null === Ch(s) && (u = i), (i = i.sibling)); + (null === (i = u) + ? ((u = o.child), (o.child = null)) + : ((u = i.sibling), (i.sibling = null)), + wj(o, !1, u, i, _)); + break; + case 'backwards': + for (i = null, u = o.child, o.child = null; null !== u; ) { + if (null !== (s = u.alternate) && null === Ch(s)) { + o.child = u; + break; + } + ((s = u.sibling), (u.sibling = i), (i = u), (u = s)); + } + wj(o, !0, i, null, _); + break; + case 'together': + wj(o, !1, null, null, void 0); + break; + default: + o.memoizedState = null; + } + else o.memoizedState = null; + return o.child; + } + function ij(s, o) { + !(1 & o.mode) && + null !== s && + ((s.alternate = null), (o.alternate = null), (o.flags |= 2)); + } + function Zi(s, o, i) { + if ( + (null !== s && (o.dependencies = s.dependencies), + (zs |= o.lanes), + !(i & o.childLanes)) + ) + return null; + if (null !== s && o.child !== s.child) throw Error(p(153)); + if (null !== o.child) { + for ( + i = Pg((s = o.child), s.pendingProps), o.child = i, i.return = o; + null !== s.sibling; + ) + ((s = s.sibling), ((i = i.sibling = Pg(s, s.pendingProps)).return = o)); + i.sibling = null; + } + return o.child; + } + function Dj(s, o) { + if (!Fn) + switch (s.tailMode) { + case 'hidden': + o = s.tail; + for (var i = null; null !== o; ) + (null !== o.alternate && (i = o), (o = o.sibling)); + null === i ? (s.tail = null) : (i.sibling = null); + break; + case 'collapsed': + i = s.tail; + for (var a = null; null !== i; ) + (null !== i.alternate && (a = i), (i = i.sibling)); + null === a + ? o || null === s.tail + ? (s.tail = null) + : (s.tail.sibling = null) + : (a.sibling = null); + } + } + function S(s) { + var o = null !== s.alternate && s.alternate.child === s.child, + i = 0, + a = 0; + if (o) + for (var u = s.child; null !== u; ) + ((i |= u.lanes | u.childLanes), + (a |= 14680064 & u.subtreeFlags), + (a |= 14680064 & u.flags), + (u.return = s), + (u = u.sibling)); + else + for (u = s.child; null !== u; ) + ((i |= u.lanes | u.childLanes), + (a |= u.subtreeFlags), + (a |= u.flags), + (u.return = s), + (u = u.sibling)); + return ((s.subtreeFlags |= a), (s.childLanes = i), o); + } + function Ej(s, o, i) { + var a = o.pendingProps; + switch ((wg(o), o.tag)) { + case 2: + case 16: + case 15: + case 0: + case 11: + case 7: + case 8: + case 12: + case 9: + case 14: + return (S(o), null); + case 1: + case 17: + return (Zf(o.type) && $f(), S(o), null); + case 3: + return ( + (a = o.stateNode), + zh(), + E(En), + E(_n), + Eh(), + a.pendingContext && ((a.context = a.pendingContext), (a.pendingContext = null)), + (null !== s && null !== s.child) || + (Gg(o) + ? (o.flags |= 4) + : null === s || + (s.memoizedState.isDehydrated && !(256 & o.flags)) || + ((o.flags |= 1024), null !== Bn && (Fj(Bn), (Bn = null)))), + S(o), + null + ); + case 5: + Bh(o); + var u = xh(Qn.current); + if (((i = o.type), null !== s && null != o.stateNode)) + (_s(s, o, i, a), s.ref !== o.ref && ((o.flags |= 512), (o.flags |= 2097152))); + else { + if (!a) { + if (null === o.stateNode) throw Error(p(166)); + return (S(o), null); + } + if (((s = xh(Yn.current)), Gg(o))) { + ((a = o.stateNode), (i = o.type)); + var _ = o.memoizedProps; + switch (((a[hn] = o), (a[dn] = _), (s = !!(1 & o.mode)), i)) { + case 'dialog': + (D('cancel', a), D('close', a)); + break; + case 'iframe': + case 'object': + case 'embed': + D('load', a); + break; + case 'video': + case 'audio': + for (u = 0; u < Zr.length; u++) D(Zr[u], a); + break; + case 'source': + D('error', a); + break; + case 'img': + case 'image': + case 'link': + (D('error', a), D('load', a)); + break; + case 'details': + D('toggle', a); + break; + case 'input': + (Za(a, _), D('invalid', a)); + break; + case 'select': + ((a._wrapperState = { wasMultiple: !!_.multiple }), D('invalid', a)); + break; + case 'textarea': + (hb(a, _), D('invalid', a)); + } + for (var x in (ub(i, _), (u = null), _)) + if (_.hasOwnProperty(x)) { + var C = _[x]; + 'children' === x + ? 'string' == typeof C + ? a.textContent !== C && + (!0 !== _.suppressHydrationWarning && Af(a.textContent, C, s), + (u = ['children', C])) + : 'number' == typeof C && + a.textContent !== '' + C && + (!0 !== _.suppressHydrationWarning && Af(a.textContent, C, s), + (u = ['children', '' + C])) + : w.hasOwnProperty(x) && null != C && 'onScroll' === x && D('scroll', a); + } + switch (i) { + case 'input': + (Va(a), db(a, _, !0)); + break; + case 'textarea': + (Va(a), jb(a)); + break; + case 'select': + case 'option': + break; + default: + 'function' == typeof _.onClick && (a.onclick = Bf); + } + ((a = u), (o.updateQueue = a), null !== a && (o.flags |= 4)); + } else { + ((x = 9 === u.nodeType ? u : u.ownerDocument), + 'http://www.w3.org/1999/xhtml' === s && (s = kb(i)), + 'http://www.w3.org/1999/xhtml' === s + ? 'script' === i + ? (((s = x.createElement('div')).innerHTML = ' @@ -790,6 +795,25 @@ /> + + +
+
+ + {$i18n.t('File Extensions')} + +
+ +
{/if} diff --git a/src/lib/components/admin/Settings/Models.svelte b/src/lib/components/admin/Settings/Models.svelte index 42828b6c53..cacb5b5e73 100644 --- a/src/lib/components/admin/Settings/Models.svelte +++ b/src/lib/components/admin/Settings/Models.svelte @@ -350,12 +350,12 @@ window.addEventListener('keydown', onKeyDown); window.addEventListener('keyup', onKeyUp); - window.addEventListener('blur-sm', onBlur); + window.addEventListener('blur', onBlur); return () => { window.removeEventListener('keydown', onKeyDown); window.removeEventListener('keyup', onKeyUp); - window.removeEventListener('blur-sm', onBlur); + window.removeEventListener('blur', onBlur); }; }); diff --git a/src/lib/components/admin/Settings/Models/ModelSettingsModal.svelte b/src/lib/components/admin/Settings/Models/ModelSettingsModal.svelte index 14b6e6d34c..1b6b0a3f31 100644 --- a/src/lib/components/admin/Settings/Models/ModelSettingsModal.svelte +++ b/src/lib/components/admin/Settings/Models/ModelSettingsModal.svelte @@ -234,7 +234,7 @@ tooltip={$i18n.t( 'Set the default models that are automatically selected for all users when a new chat is created.' )} - models={$models} + models={$models.filter((model) => !(model?.info?.meta?.hidden ?? false))} bind:modelIds={defaultModelIds} /> @@ -245,7 +245,7 @@ tooltip={$i18n.t( 'Set the models that are automatically pinned to the sidebar for all users.' )} - models={$models} + models={$models.filter((model) => !(model?.info?.meta?.hidden ?? false))} bind:modelIds={defaultPinnedModelIds} /> @@ -366,7 +366,7 @@ {#if showDefaultParams}
- +
{/if} diff --git a/src/lib/components/admin/Settings/WebSearch.svelte b/src/lib/components/admin/Settings/WebSearch.svelte index cac70fc55a..4f9929dc60 100644 --- a/src/lib/components/admin/Settings/WebSearch.svelte +++ b/src/lib/components/admin/Settings/WebSearch.svelte @@ -39,7 +39,8 @@ 'firecrawl', 'external', 'yandex', - 'youcom' + 'youcom', + 'linkup' ]; let webLoaderEngines = ['playwright', 'firecrawl', 'tavily', 'external']; @@ -78,8 +79,15 @@ webConfig.PLAYWRIGHT_TIMEOUT = webConfig.PLAYWRIGHT_TIMEOUT.toString(); } + // Convert Linkup params JSON string to object before sending + const linkupParams = + typeof webConfig.LINKUP_SEARCH_PARAMS === 'string' && + webConfig.LINKUP_SEARCH_PARAMS.trim() !== '' + ? JSON.parse(webConfig.LINKUP_SEARCH_PARAMS) + : (webConfig.LINKUP_SEARCH_PARAMS ?? {}); + const res = await updateRAGConfig(localStorage.token, { - web: webConfig + web: { ...webConfig, LINKUP_SEARCH_PARAMS: linkupParams } }); // Convert arrays back to strings for display @@ -123,6 +131,12 @@ webConfig.PLAYWRIGHT_TIMEOUT = parsed; } } + + // Convert Linkup params object to JSON string for textarea display + webConfig.LINKUP_SEARCH_PARAMS = + typeof webConfig.LINKUP_SEARCH_PARAMS === 'object' + ? JSON.stringify(webConfig.LINKUP_SEARCH_PARAMS ?? {}, null, 2) + : (webConfig.LINKUP_SEARCH_PARAMS ?? ''); } }); @@ -834,6 +848,30 @@ /> + {:else if webConfig.WEB_SEARCH_ENGINE === 'linkup'} +
+
+
+ {$i18n.t('Linkup API Key')} +
+ + +
+ +
+
+ {$i18n.t('Parameters')} +
+ +