diff --git a/README.md b/README.md index b14632e793baa90f6c362da5b72908346ea79c00..863e4f33e0b66fc5efbaf25955188f579545d2eb 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ --- -title: MiniCPM5-2B WebGPU Pi +title: MiniCPM5-2B Pi HTTP experiment emoji: 🥧 colorFrom: green colorTo: blue @@ -7,86 +7,37 @@ sdk: static app_file: index.html pinned: false license: apache-2.0 -short_description: A coding agent running entirely in your browser -thumbnail: https://huggingface.co/spaces/townbox/MiniCPM5-2B-WebGPU-Pi/resolve/main/social-thumbnail-v3.png +short_description: Browser coding agent with HTTP requests (experimental) models: - openbmb/MiniCPM5-2B - Mike0021/MiniCPM5-2B-ONNX tags: - transformers.js - - onnx - webgpu - - text-generation - agents - pi - just-bash --- -# Pi browser workspace · MiniCPM5-2B +# Pi browser HTTP experiment -Run **Pi's real agent core**, **just-bash**, and **MiniCPM5-2B** entirely in your browser. Chat with Pi, inspect and edit files, and execute shell commands in a persistent virtual workspace. A browser worker runs the agent loop, local WebGPU inference, and every tool. No inference API, API key, or shell server is involved. +An independent duplicate of [victor/MiniCPM5-2B-WebGPU-Pi](https://huggingface.co/spaces/victor/MiniCPM5-2B-WebGPU-Pi) at revision `959e272adeb7931e32d3eb2177dc1d5e96c3e967`. The original Space is unchanged. -Send your first message. If the complete verified model is already cached in this browser, Pi restores it and sends your message automatically, without a confirmation dialog. Otherwise, a **Load model & send** dialog explains the download. Confirming closes the dialog and shows progress in the top bar, then sends your message automatically. Cancel or Stop keeps your unsent draft; loading errors offer a retry. If the cache is incomplete or has changed, downloading missing files requires confirmation. You can also click **Load model** ahead of time. The first download is about **1.84 GB**; files are SHA-256 verified and cached in OPFS. The loader uses bounded byte ranges, retries, cancellation, and separate download / GPU setup / warm-up phases. Chat and virtual files are saved in IndexedDB on this site. Cached weights can be reused after reloading. The entire workspace uses a dark theme. +MiniCPM5-2B inference and just-bash run in a browser worker. This copy adds real `curl`/`wget` requests through browser `fetch`, with no backend or proxy. The first model download is about 1.84 GB, verified and cached locally. WebGPU with shader-f16 is required for inference; the Shell can run HTTP commands without loading the model. -If your browser blocks storage inside Hugging Face's embedded view, use the app's **Open workspace in a new tab** button or [open the app directly](https://townbox-minicpm5-2b-webgpu-pi.static.hf.space/). This keeps inference and files in your browser and does not require changing browser privacy settings. +Try in Shell: -Requires WebGPU with FP16 (`shader-f16`) in a browser worker, OPFS, and sufficient storage and device memory. There is an 8,192-token prompt-plus-output budget, up to 2,048 generated tokens per model call, and a 12-turn limit per request. Desktop and narrow-screen layouts are included. Physical Android/iOS devices have not been tested. +```bash +curl -fsS https://jsonplaceholder.typicode.com/todos/1 -o todo.json +jq '{id, title, completed}' todo.json +``` -Try: **What's our total sales revenue?** +Or ask Pi: **Fetch https://jsonplaceholder.typicode.com/todos/1, save it as todo.json, and tell me its title and whether it is completed.** -Pi has `bash`, `read`, `write`, and `edit` tools. just-bash supports shell scripts, pipes, redirects, `awk`, `jq`, `sed`, `grep`, and other text commands. Node.js, Python, npm, native binaries, SQLite, and network commands are unavailable. The left column uses xterm.js with Pi's actual terminal renderer, editor, and message components. MiniCPM and the tools run in the browser worker. This reuses Pi's TUI; the full Node CLI and its extensions are not included. Files are virtual and remain on your device. Export work you want to keep. +Allowed HTTPS hosts: `api.github.com`, `raw.githubusercontent.com`, `huggingface.co`, `jsonplaceholder.typicode.com`, and `httpbin.org`. GET, HEAD, and POST are enabled, with an 8-second deadline and 1 MiB response limit. Use `set -o pipefail` before pipelines to retain download failures. -The top bar shows the model, its load status, and a live token-speed sparkline labeled **WebGPU** for inference or **JavaScript** for tool execution. Speed is measured from generated tokens, including thinking; prompt processing and tool execution have their own statuses. The chart clears when generation stops. Successful file reads open the corresponding workspace file while preserving unsaved edits. Common file types have Seti icons. The shell includes live Bash syntax coloring, multiline commands, session history, colored errors/exit states, and a resizable output area. Panels use background shading and rounded corners sized to their nested spacing throughout the dark workspace. +Browser CORS applies. Redirects require the final URL directly: browsers hide redirect destinations, so this copy reports an error instead of silently returning empty output or following unchecked hosts. Cookies are omitted. Explicit request URLs, headers, and bodies are sent to the destination; inference and workspace storage remain local. Node.js, Python, npm, and native programs remain unavailable. -The terminal uses Pi's dark palette and native message/editor padding. Recent checks cover seven viewport sizes, Unicode alignment, long tool output, a simulated 60-turn transcript, twelve keyboard interactions, five actual-model workflows, and a ten-turn conversation with twelve tool results. Mobile sizes were simulated on desktop Chromium. +Source is under `app/`. Rebuild with `cd app && npm ci && npm test && npm run build`, then `python3 scripts/stage.py`. The HTTP implementation is in `app/src/browser-http.mjs`; it uses just-bash's existing curl/wget commands and custom transport hook. Tests and results are in `validation/`. -## Our conversion - -The included `q4f16` model was converted directly from the official [OpenBMB MiniCPM5-2B BF16 checkpoint](https://huggingface.co/openbmb/MiniCPM5-2B/tree/abe115e887989b14f05e64a3b260648329324c3f), not from community-converted weights. - -- Source revision: `abe115e887989b14f05e64a3b260648329324c3f`. -- Official weight SHA-256, verified before conversion: `14fb8e7f0a18d53d1f239773758bf581cee7e456a4523a54622c3a245b64402c`. -- ONNX Runtime GenAI 0.15.2; symmetric int4, block size 32; FP16 activations and KV cache. -- Fused QKV, GQA, RoPE, and normalization operations. -- Last-position logits selected before the output projection. -- Lossless splitting of the 510 MiB embedding allocation into four 127.5 MiB tensors. -- Seven external-data shards; corrected tool-history serialization and Jinja compatibility. - -The [package manifest](https://huggingface.co/Mike0021/MiniCPM5-2B-ONNX/blob/04a6c49fcba3a65a0351c92644c3a7e9d4343059/manifest.json) contains file sizes and SHA-256 hashes. The weights are hosted in the companion [model repository](https://huggingface.co/Mike0021/MiniCPM5-2B-ONNX). The app pins model revision `04a6c49fcba3a65a0351c92644c3a7e9d4343059`; the Space hosts the app and browser runtime. - -## Validation - -Six prompts with prefill and cached decoding give 41 tested prediction positions. These are scoped conversion checks, not a broad quality evaluation. - -| Comparison | Top-token agreement | Mean KL divergence | -|---|---:|---:| -| FP16 ONNX vs FP16 PyTorch | 41/41 | 0.00000815 | -| Int4 ONNX vs official BF16 PyTorch | 36/41 | 0.125916 | -| Packaged int4 vs our original int4 export | 41/41; all logits bit-identical | 0 | -| Browser WebGPU vs native packaged ONNX | 41/41 | 0.002517 | - -Local Chromium tests on an AMD Radeon 8060S covered streaming, stopping, thinking mode, XML tool-call generation, and one retrieval fixture at 3,888 prompt tokens. Inference also passed with the GPU device capped at a 128 MiB storage binding limit and 256 MiB buffer limit. This desktop allocation test does not emulate a phone's memory pressure or thermals. - -Warm local benchmark medians were about 35–42 decode tokens/s. At 1,890 prompt tokens, first-token latency improved about 9.5% against our own identical-weight control with all-position logits and unsplit embeddings. Timings depend on device, browser, prompt, and thermal state. - -Four-bit quantization has measurable quality loss. A multi-turn audit reproduced ineffective HTML/CDN edits and long, inconclusive reasoning with this export, while the original BF16 model completed the reference workflow. The base model also makes mistakes: one Chinese arithmetic prompt produced an incorrect answer in both the official BF16 model and the conversion. Pi translates validated XML tool calls into actions in the virtual filesystem. Integration tests do not establish broad coding-agent reliability. - -The agent now uses the 2B model's supported thinking mode and actual nucleus sampling (temperature 1, top-p .95, no top-k/min-p filter, repetition penalty 1). Completed thinking is retained separately in history and collapsed in the UI. The audit documents the earlier configuration mistakes, exact-prompt comparisons, parser/sampling corrections, and unresolved quality limits. It does not claim the 4-bit model matches BF16 or that multi-turn inference is fully optimized. - -## Browser-agent verification - -The production browser bundle passed five real-model agent workflows with networking disabled: reading an unseen random file value, computing CSV revenue and writing a report, creating and executing a shell script, editing that script, and recovering from a missing-file error. It made zero network requests during these tasks. Tests also cover generation cancellation, editor/import/shell controls, persisted files and chat, and cached reloads with zero weight requests. Eight unit tests cover XML/CDATA, tool-shaped code examples, context/history conversion, filesystem restoration, and inert Markdown. - -The same workflows passed with an actual desktop GPU capped at 128 MiB storage bindings and 256 MiB buffers. This is not mobile hardware emulation. Public-Hub download cancellation/retry was tested locally; cached reloads took about 1.8–1.9 seconds on the tested desktop. - -The deployed browser agent also passed all five workflows from the public Space URL, with zero requests during offline tasks and zero weight downloads on reload. The actual Hugging Face embedded page successfully loaded the model and used Pi's bash and file tools to produce and verify the $144 report. - -The xterm.js terminal build also passed all 12 terminal interaction checks from the public app URL, including keyboard editing, search, history, Unicode/large clipboard paste, shell execution, and a 390px layout. In the actual Hugging Face embed, it loaded MiniCPM from cache in 3.644 seconds on the tested desktop and created a fresh, verified $144 sales report through Pi's tools. - -## Runtime - -Browser runtime versions: Pi Agent / Pi AI **0.85.1**, just-bash **3.4.2**, Transformers.js **4.2.0**, and ONNX Runtime Web **1.26.0-dev.20260416-b7804b056c**. JavaScript/WASM assets are hosted in this Space. Model caching is keyed to the pinned model revision and per-file verification receipts. - -## Attribution - -Base model: **OpenBMB**, Apache-2.0. Agent: **Pi / earendil-works**. Shell: **just-bash / Vercel**. Inference: **Hugging Face Transformers.js** and **Microsoft ONNX Runtime**. Bundled license texts and notices are in [licenses](licenses). This Space contains an independently converted and quantized derivative; no weights were retrained. +The small 4-bit model can make mistakes. Shell transport checks and actual-model trials are reported separately; they do not establish general agent reliability or physical-phone performance. diff --git a/app/README.md b/app/README.md new file mode 100644 index 0000000000000000000000000000000000000000..df52fbe45c06e76809ab8f72712ad66ba9422fbd --- /dev/null +++ b/app/README.md @@ -0,0 +1,137 @@ +# Pi in the browser + +A static web app running **Pi’s actual terminal UI in xterm.js**, **the real Pi Agent**, **just-bash**, and **our verified MiniCPM5-2B q4f16 conversion** in the browser. A dedicated worker owns the agent loop, WebGPU inference, and virtual shell. No inference API, API key, shell server, or Pi RPC server is involved. + +```sh +cd app +npm ci +npm run build +npm run preview +``` + +Open the printed localhost URL and send your first message. If the complete verified model is already cached, Pi restores it and sends your message automatically without a confirmation dialog. Otherwise, a **Load model & send** dialog explains the download and closes immediately on confirmation. Progress appears in the top bar while your message stays visible as queued; it sends automatically once the model is ready. Closing the dialog or pressing Stop returns the unsent message to the editor. Loading errors reopen the dialog for retry. Automatic restoration never downloads missing model files: an incomplete or changed cache requires confirmation. You can also load ahead of time with **Load model**. The default downloads our pinned model from Hugging Face. The app needs a secure context (HTTPS or localhost), WebGPU with `shader-f16` in a worker, and OPFS storage. Allow about 2 GB of free browser storage plus device memory for inference. Actual memory availability matters on phones. + +For development, use `npm run dev`. To use the already converted weights on this computer instead of downloading them, run `python scripts/serve.py` from the repository root in another terminal, then open `http://127.0.0.1:5173/?source=local`. The development and preview servers forward `/models` to that static file server. The local source option is accepted only on localhost/127.0.0.1. + +## Features + +- Pi’s upstream fullscreen renderer, multiline editor, user/assistant message components, Markdown, prompt history, and autocomplete. xterm.js renders their ANSI output. +- `/load`, `/help`, `/new`, and `!command` browser commands. Enter sends, Shift+Enter inserts a newline, Escape/Ctrl+C stops, Ctrl+O expands tools. Ctrl+P/N recalls prompts; Ctrl+Shift+F searches the transcript. The Send and Newline buttons also support touch input. +- Streaming conversation with genuine `@earendil-works/pi-agent-core` tool execution and automatic follow-up turns. +- `bash`, `read`, `write`, and exact-match `edit` tools connected to the same just-bash filesystem. +- File editor with Prism syntax colors for HTML/XML/SVG, CSS, JavaScript/TypeScript (including JSX/TSX), Python, Bash, JSON, Markdown, YAML, TOML, SQL, CSV, C/C++, C#, Java, Go, Rust, Dockerfiles, and diffs. Highlighting runs in a separate, lazily started worker and is debounced while typing. Native textarea editing, selection, undo, and scrolling are preserved. Unknown formats, files above 200,000 characters or 5,000 lines, excessive token output, and grammar work exceeding 1.5 seconds fall back to plain text. Text-file import, workspace export, and an interactive command entry are also included. +- The starter workspace pairs `sales.csv` (products and units sold) with `products.json` (product prices). Both are needed for total sales revenue. The cat suggests “What's our total sales revenue?” without naming files or tools; the workspace README contains no calculation instructions. Only an untouched earlier pair is upgraded together; custom data and prior deletions are preserved. +- Successful `read` tool calls open and highlight the resolved file in the workspace, including relative paths and symlinks. Following waits for newly created files, preserves unsaved edits, and keeps the conversation’s focus and page scroll position. Common file types use a local subset of 18 Seti icons from VS Code’s built-in theme, totaling about 12 KB of SVGs. +- The shell highlights Bash as you type, accepts multiline commands (Shift+Enter), recalls session history (↑/↓), and separates command/output blocks with colored exit states and errors. Clear or Ctrl+L clears the output. Its output area can be resized vertically. +- Model name, loading progress, and loaded status live in a rounded, inset top bar aligned with the workspace width. New chat sits at the bottom left of the terminal, opposite the send controls. Panels use background shading and rounded corners instead of separator borders. +- The top bar’s activity indicator labels model inference **WebGPU** and tool execution **JavaScript**. It shows loading, prompt processing, tool execution, and live generation speed. Its sparkline uses actual generated-token counts, including thinking, over a rolling second; prompt-processing time is excluded. Rates refresh four times per second and clear when generation stops. The capsule fits its current contents with a 220ms width transition, disabled when reduced motion is preferred. Nested corner radii account for their insets: the header uses a 16px radius around 8px-radius controls with 8px padding. +- The first-message dialog explains that the model, inference, and shell run entirely in the browser. Pi’s input receives focus when the workspace starts; cancelling setup returns focus and the unsent draft to Pi. +- The download dialog has a matching peeking cat with transparent paws over its top edge. The sprite preloads and decodes on page startup, stays decorative for keyboard/screen-reader users, and shrinks on short screens to keep the download note and actions visible. Subtle paw prints appear around the overlay whenever the dialog is open, including before confirmation and on retry. They do not intercept clicks, pause in hidden tabs, and stay still with reduced motion. +- After 7 seconds of inactivity, a faint paw trail occasionally crosses Pi’s transcript, with 45–60 seconds between trails. Typing, clicking, or scrolling clears it immediately; pointer movement neither resets the delay nor stops the trail. It stays above the input, never takes focus, and pauses during model activity, open dialogs, hidden or unfocused tabs, and reduced motion. +- An empty chat has a small blocky cat with a clickable starter prompt. The bubble and cat appear together once the image is decoded. The suggestion fills Pi’s editor without sending, adapts to the workspace files, and disappears after the first user message. The 104px mascot makes one gentle hop shortly after appearing, then occasionally blinks; clicking or tapping the cat replays the hop and a short meow. Both cats are decorative and never take keyboard focus. Motion pauses while hidden and is disabled for reduced-motion preferences. Its paws align with the input divider, with room reserved beside it for the status text. Its position follows the terminal’s available blank rows, keeping the input and transcript unobstructed; short viewports omit it when there is no room. +- IndexedDB persistence for chat, file bytes, executable modes, directories, and symbolic links. New chat keeps the workspace. +- Verified model downloading: six concurrent files, 32 MiB byte ranges, three attempts per chunk, cancellation, incremental SHA-256 checks, and atomic OPFS writes. Completed files survive an interrupted load; an incomplete file restarts on retry. +- Cached reloads use file size, modification time, and the stored verification receipt. Model files are hashed during download; they are not rehashed on every reload. +- Visible download / WebGPU setup / shader warm-up phases. No image requests from model-generated Markdown. +- MiniCPM5-2B's supported thinking mode, with completed reasoning retained separately in conversation history. Thoughts are collapsed in the terminal; click to expand. Tool-shaped text inside reasoning is never executed. +- Temperature 1, actual top-p 0.95 sampling, no top-k/min-p filtering, and repetition penalty 1. A tested adapter applies nucleus filtering because Transformers.js 4.2.0 does not implement its exposed `top_p` option in generation. +- An 8,192-token combined prompt/output budget, up to 2,048 generated tokens (reasoning plus answer/tool XML) per model call, and a 12-turn limit per user request. Older complete user turns can be omitted from inference context; the full saved conversation is retained. An oversized current turn produces an explicit error. +- The terminal footer shows used/total context tokens and remaining capacity for the latest model call. It includes the formatted prompt (instructions, tool definitions, and retained history) plus generated tokens, updates during streaming, survives reloads, and resets with New chat. Unsent draft text is counted when submitted; saved turns excluded from the model context are not counted. On narrow screens the counter gets its own line. + +## Model quality + +The [September 14 multi-turn audit](../research/multiturn-audit/REPORT.md) found that the previous no-thinking/greedy profile was not faithful to the model's documented configuration. The corrected adapter handles reasoning and sampling, but the current 4-bit conversion still fails some HTML/CDN follow-ups that the original BF16 model completed. It can produce ineffective edits or exhaust its reasoning budget. Numerical conversion checks and basic tool tests do not establish general coding reliability. Cross-call KV reuse and physical-phone validation remain outstanding. +- Responsive desktop and mobile layouts. The file workspace follows the chat on narrow screens. +- A consistent dark theme across the terminal, header, model controls, file editor, shell, and setup dialog, including native form controls and scrollbars. + +## Runtime boundaries + +This uses Pi's actual TUI and agent core with browser host adapters. The npm `pi-tui` package supplies the renderer, editor, input parser, layout, Markdown, search, and keybindings. Unmodified CLI presentation components are in [vendor/pi-coding-agent](vendor/pi-coding-agent/README.md), with provenance checksums and the upstream dark palette. Secondary text colors are lifted for legibility at small sizes. [The build adapter](scripts/pi-browser.mjs) replaces terminal host services; [the terminal adapter](src/pi/xterm-terminal.mjs) connects xterm input/output/resize to Pi. Browser command dispatch and just-bash tool cards are app code. + +Message padding follows Pi 0.85.1 defaults: one column of output padding, one inner row above/below user and tool boxes, one separator row between turns, and zero editor column padding. The browser panel adds an 8px outer inset, with no right padding on desktop. Pi owns transcript scrolling, so xterm's unused native scrollbar gutter is disabled. The pinned `@xterm/addon-unicode-graphemes@0.4.0` addon matches Pi's grapheme widths for CJK, emoji sequences and combining accents. It uses xterm's proposed Unicode API and is covered by rendering assertions. + +The full Node CLI, host filesystem, OAuth providers, extensions, package installation, and RPC server are not included. xterm.js is the terminal emulator; it does not add Node.js or a native shell. Model inference and tool execution remain in the browser worker. Terminal control sequences from model/file output are stripped before rendering, and Markdown images do not trigger downloads. + +just-bash is a simulated shell, not a Linux VM. Shell scripts, pipes, redirects, `awk`, `jq`, `sed`, `grep`, `find`, and other supported text commands execute in JavaScript. Node.js, Python, npm, native executables, and SQLite are unavailable. This HTTP experiment enables curl/wget for selected HTTPS APIs through a browser fetch adapter; see public/http-help.html for hosts, examples, and limits. The installed browser bundle also excludes working gzip/zlib commands. Shell cwd and variables reset between commands; filesystem changes persist. Commands have a 10-second deadline, 3,000-command cap, 16 MiB filesystem budget, and 256 KiB output budget. Tool output passed to the model is capped at 6,000 characters. + +Local model and filesystem tool calls can run with the browser network disabled after loading. HTTP commands require a connection and CORS permission from the destination. Reopening the app itself still requires its static HTML/JS/WASM assets; there is no offline service worker. Browser storage belongs to this site's origin and may be evicted by the browser. Export important work. + +The small 4-bit model can make mistakes. These tests establish working integration on the tested device, not broad coding-agent reliability or support for every mobile browser. No physical phone has been tested. + +## Verification + +```sh +npm test +npm run build +# Start npm run preview, then run the terminal checks (no model needed): +node tests/terminal.mjs +# Deterministic presentation fixtures, including narrow and short viewports: +npm run test:render +# Ten consecutive actual-model turns (local model server required): +npm run test:conversation +# First message, modal cancellation/retry, and actual model auto-send: +npm run test:first-message +# Download confirmation, top-bar progress, queued messages and cancellation (controlled worker fixtures): +npm run test:load-flow +# Cached auto-start, invalidated cache, Stop and GPU failure recovery: +npm run test:cached-start +# Live token speed, generation/tool/idle phases and eight header layouts: +npm run test:runtime-meter +# Automatic read following, unsaved edits, file icons and mobile layout: +npm run test:follow-read +# File highlighting, native editing, saving, scrolling and large-file fallback: +npm run test:editor +# Companion product data and preserving existing workspaces during its addition: +npm run test:starter-products +# Opt-in real WebGPU model evaluation; requires the dedicated cached test profile: +npm run test:sales-demo +# Syntax-colored command input, actual shell execution, history and layouts: +npm run test:shell +# Actual token usage, streaming, cancellation, reload and input focus: +npm run test:context +# Start npm run preview -- --port 4173 and the root static model server first: +npm run test:browser +``` + +The terminal suite checks real keyboard events, multiline editing, autocomplete, history, Unicode and large clipboard pastes, shell execution, and live resize. The browser suite uses real Chromium, the actual model, and the production bundle; prompts are submitted through xterm and Pi’s editor. It disables networking while Pi reads a random value from an unseen file, calculates CSV revenue, writes and verifies a report, creates and executes a shell script, edits it, and recovers from a missing-file tool error. It also checks stopping generation, file import/edit/save, manual shell execution, workspace persistence, cached reloads, and a 390 px layout. + +To exercise the public Hugging Face download in a separate browser profile: + +```sh +APP_URL=http://127.0.0.1:4173/ \ +BROWSER_PROFILE=../validation/agent-browser-profile/remote \ +TEST_LABEL=agent-browser-hub TEST_CANCEL_LOAD=1 npm run test:browser +``` + +To exercise smaller GPU buffer allocations on the desktop GPU: + +```sh +APP_URL='http://127.0.0.1:4173/?source=local&limit128' \ +TEST_LABEL=agent-browser-limit128 npm run test:browser +``` + +`limit128` sets the actual WebGPU device to 128 MiB storage bindings and 256 MiB buffers. It is an allocation compatibility test; viewport resizing and GPU limits do not emulate mobile hardware performance. + +Results and screenshots are in the repository's `validation/agent-browser*` files. Test logs include complete model tool calls and results. The browser profile and downloaded weights are ignored by Git. + +## Static hosting + +Upload **the contents of `app/dist`** to an HTTPS static host. It contains the app and local ONNX Runtime assets; weights are fetched from the pinned public Hugging Face repository and cached in OPFS. No build or inference server is needed after deployment. + +The public deployment is [townbox/MiniCPM5-2B-WebGPU-Pi](https://huggingface.co/spaces/townbox/MiniCPM5-2B-WebGPU-Pi). From the repository root, `python scripts/prepare_space.py` stages the built app, source, licenses, and selected validation files in `.space-agent/` for upload. + +Browsers that deny storage in third-party embeds get an **Open workspace in a new tab** link. The top-level Space app can then use its own storage without changing browser privacy settings. Embedded-page tests restore normal Chromium storage partitioning because Playwright 1.58 disables it by default; the restricted-storage path is tested separately. + +## Pinned components + +| Component | Version / revision | +|---|---| +| Pi agent core and Pi AI types/event stream | `@earendil-works/*` 0.85.1 | +| Pi TUI / CLI presentation components | 0.85.1 | +| xterm.js / fit addon | 6.0.0 / 0.11.0 | +| just-bash | 3.4.2, explicit `just-bash/browser` import | +| Transformers.js | 4.2.0 | +| Model | `Mike0021/MiniCPM5-2B-ONNX` at `04a6c49fcba3a65a0351c92644c3a7e9d4343059` | +| Model provenance | official OpenBMB weights; see root README and package manifest | + +Architecture decisions and primary-source research are in [the investigation](../research/browser-agent/REPORT.md). diff --git a/app/index.html b/app/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a91b5619c76cf1bd96c0311d2861420e56936031 --- /dev/null +++ b/app/index.html @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + Pi · Coding agent in your browser + + +
+
+
+ WebGPU + + + Idle +
+ +
+
+
MiniCPM5-2B4-bit
+

One download, about 1.84 GB. Cached in this browser for next time.

+ +
+
+
+
+
+
+
+ + +
Files and chat are saved on this device.
+
Pi TUI · xterm.js Model and tools run in your browser
+
+
+ + +
+ + + +
+

Download model weights

+ +
+
+

The model and shell run in your browser. HTTP commands can send requests and data to external services.

+
+
Model
MiniCPM5-2B
+
Inference
On your GPU
+
Shell
Bash in the browser
+
+
About 1.84 GB on the first downloadSaved in this browser for faster starts next time.
+

Your message

+ + +

Powered by + Transformers.js + ONNX Runtime + Pi + just-bash +

+
+
+
+ + + diff --git a/app/package-lock.json b/app/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..b50d6cab6fa6617b715d5c5368f295d8d87d29ba --- /dev/null +++ b/app/package-lock.json @@ -0,0 +1,4599 @@ +{ + "name": "minicpm5-pi-browser", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "minicpm5-pi-browser", + "version": "0.1.0", + "dependencies": { + "@earendil-works/pi-agent-core": "0.85.1", + "@earendil-works/pi-ai": "0.85.1", + "@earendil-works/pi-tui": "0.85.1", + "@huggingface/transformers": "4.2.0", + "@xmldom/xmldom": "0.9.12", + "@xterm/addon-fit": "0.11.0", + "@xterm/addon-unicode-graphemes": "0.4.0", + "@xterm/xterm": "6.0.0", + "buffer": "6.0.3", + "events": "3.3.0", + "hash-wasm": "4.12.0", + "just-bash": "3.4.2", + "markdown-it": "15.0.2", + "prismjs": "1.30.0" + }, + "devDependencies": { + "playwright": "1.58.2", + "vite": "8.3.0" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.123.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.123.0.tgz", + "integrity": "sha512-Y9oX9mPNGZClHQOFqrWRk43Srcu/UHuPq3rfxxOq7JgW0gi+lJA2MAOK4Ul3k/+AUrwRWFJvd0tK3oC0Pw25dw==", + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@aws-crypto/sha256-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", + "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha256-js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", + "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/supports-web-crypto": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", + "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", + "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/client-bedrock-runtime": { + "version": "3.1048.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1048.0.tgz", + "integrity": "sha512-u+NT61JZEkRFtpL0CAw1N1dwxnaLgwVXQl/zjJxTGgLyS/jTIdg2SdoEoCTHxgDyCnqa1HEi9QOoE9/pYRNpOQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/credential-provider-node": "^3.972.42", + "@aws-sdk/eventstream-handler-node": "^3.972.16", + "@aws-sdk/middleware-eventstream": "^3.972.12", + "@aws-sdk/middleware-websocket": "^3.972.19", + "@aws-sdk/token-providers": "3.1048.0", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/fetch-http-handler": "^5.4.2", + "@smithy/node-http-handler": "^4.7.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.978.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.0.tgz", + "integrity": "sha512-2yX9LUmxPklVjSGTb8dfnWRJSiFQ3TeH2nn7G1mdKHTfnabzF0+gfrS8rYfLWmZrQ8A3mEcxMJjRc51dL5KWaA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.974.5", + "@aws-sdk/xml-builder": "^3.972.40", + "@aws/lambda-invoke-store": "^0.3.0", + "@smithy/core": "^3.33.3", + "@smithy/signature-v4": "^5.6.12", + "@smithy/types": "^4.17.2", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.972.71", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.71.tgz", + "integrity": "sha512-JN+JHruYZw3GUZB8YGAlDk4wTDPOEAEEdEzj5nS0xodWR4smzHsN7PnK2j6IeOsDIj2aqua5DSbhXl9Gtf90FQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.972.73", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.73.tgz", + "integrity": "sha512-uyYYnJOnlis8uQzaYGPd7N1JoioCoNpXgnkXYixsWJXHXgXyYi8WXJSDfofxJeWfQIGWLe2Nwyq60Uc7MZdVOg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/fetch-http-handler": "^5.7.2", + "@smithy/node-http-handler": "^4.11.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/node-http-handler": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz", + "integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.18.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.973.16", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.16.tgz", + "integrity": "sha512-i++ly+0Uxa+u3ebSSyr0S/3CFhFJDxCXT3+Zj+mW2bXenEx5bKGCdTIKFu39SgXBNhWDjex/8cXUx9MUTMCrTw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/credential-provider-env": "^3.972.71", + "@aws-sdk/credential-provider-http": "^3.972.73", + "@aws-sdk/credential-provider-login": "^3.972.78", + "@aws-sdk/credential-provider-process": "^3.972.71", + "@aws-sdk/credential-provider-sso": "^3.973.15", + "@aws-sdk/credential-provider-web-identity": "^3.972.77", + "@aws-sdk/nested-clients": "^3.997.45", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/credential-provider-imds": "^4.4.16", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-login": { + "version": "3.972.78", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.78.tgz", + "integrity": "sha512-eUtswnXu0+Ii9ieRK+0L7aPFV3Z/dnW2VntJzjBP9xs8s+8p5nBNuymIXtXwZ+5r5+XJP3e32nMkuZ/r0HozEA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/nested-clients": "^3.997.45", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.972.83", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.83.tgz", + "integrity": "sha512-jdso7ejzfRnatxMUZK4S/U6KbaDPCvfIV4XL+IQAPFDBt5rj5Fq595euqlK8Le4lNCMFR9oUpt+1l0aMgaayOQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "^3.972.71", + "@aws-sdk/credential-provider-http": "^3.972.73", + "@aws-sdk/credential-provider-ini": "^3.973.16", + "@aws-sdk/credential-provider-process": "^3.972.71", + "@aws-sdk/credential-provider-sso": "^3.973.15", + "@aws-sdk/credential-provider-web-identity": "^3.972.77", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/credential-provider-imds": "^4.4.16", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.972.71", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.71.tgz", + "integrity": "sha512-lYmXJa4gvq4xN1lrT5NiP5vIYYKcGWAdj8y+8o6dlcateB5eF3Dn8DtmjjHKfMBrTPAMr2pebIiX/UOj8c1/UA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.973.15", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.15.tgz", + "integrity": "sha512-6Jhcf4v0pSFdjk1EW2kvzuEBKD+UZ2uNcHUIglKKLndD20YhvkL2kdmDOV5/j4mYuWWwe/a1FQ1aomU86/Cg5Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/nested-clients": "^3.997.45", + "@aws-sdk/token-providers": "3.1129.0", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": { + "version": "3.1129.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1129.0.tgz", + "integrity": "sha512-Sbl3rpzQdsG4ZK2zh0JWUYyZPKKorJlVOddA2T0DVbKJFrsW8J6wgnslxxUH04+WaBMr4A1HzJZvZX0xUvkniA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/nested-clients": "^3.997.45", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.972.77", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.77.tgz", + "integrity": "sha512-uylIQSUWpfLuH2LovxEEfwzJGM/SabLOfLMg6YXu/E8jJEKUdpdILCVCQCdFvHyu/7dLJOHPMfrSwduxO56NkQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/nested-clients": "^3.997.45", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/eventstream-handler-node": { + "version": "3.972.34", + "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.34.tgz", + "integrity": "sha512-cTeVzpu1xEAkryTZBYhGwnQ6gOGyp8ZYZvmn0Sg/nI/ABmy/CRHHxPDJDUi9PxwxUtGGaatvfRUB3FCgT/rSWw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/middleware-eventstream": { + "version": "3.972.29", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.29.tgz", + "integrity": "sha512-dlRzHCgyB8W6hLuDC5pcT5q+ziPt00n4QGgGBE17ucLVU4zMa6lsbuUdQ2Pm75Z5VA8GF+R/+SgrRcaTdIzSIQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/middleware-websocket": { + "version": "3.972.53", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.53.tgz", + "integrity": "sha512-bIrDaMENQmYRBHntOiOheqkiw5+fhKW4Lqb+mS1uqF0VwvdWI22fW2HFgWrng66CmYd+4k8ePlpj38sEfTuMLQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/fetch-http-handler": "^5.7.2", + "@smithy/signature-v4": "^5.6.12", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.997.45", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.45.tgz", + "integrity": "sha512-mooq9Q+jLa18VoM7HouczmslZU60iiB0aKc/Ztnq/luIL1ud0z4DnYprLR/ZO1gp331S9tJctM1HZr7u6YKBXQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.0", + "@aws-sdk/signature-v4-multi-region": "^3.996.46", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/fetch-http-handler": "^5.7.2", + "@smithy/node-http-handler": "^4.11.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients/node_modules/@smithy/node-http-handler": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz", + "integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.18.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.996.46", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.46.tgz", + "integrity": "sha512-L+2xZTye/2T96f3lwCws0Zw6GG2JHZW9e8FpVgGBeeExSKyeoZ6CWRpBml/7DNiK/O26jrgPM9F+Ay8VkgzUWQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.974.5", + "@smithy/signature-v4": "^5.6.12", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.1048.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1048.0.tgz", + "integrity": "sha512-k0y/GcuesuSfWyUM0WamrGyeZmltRYaPbHO82UDA6mZ/doB+FOHKutikPAtSXMn/hDz970cF+iRuuiYO9VEbAA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/nested-clients": "^3.997.9", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.974.5", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.5.tgz", + "integrity": "sha512-LkwLL2BLbC6wNNm4JaH9mbEqBMdOZCct6VAYqhdN4U1xrWM+fUJQEfbHwQgDypapOWTRtlk25akb5afM0P8CIQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/util-locate-window": { + "version": "3.965.10", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.965.10.tgz", + "integrity": "sha512-ycwH6Zd2GhuSqdXX9ihbCjeGTB6xOJs+O3+Jb8/zDG9978XU80qs75dfkPJRMNKe5MvBZPuNeFpd4JZKPoUF4g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.972.40", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.40.tgz", + "integrity": "sha512-wlFmCIGUlwF4zx/kncw+bmxTQh1HeSJq4mYV/V5cZUSJadDP3kXvGW8Rn21cimj/7y9ju+47oYWXi97vF7czaA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz", + "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", + "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@borewit/text-codec": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.2.tgz", + "integrity": "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@earendil-works/chord": { + "version": "0.85.1", + "resolved": "https://registry.npmjs.org/@earendil-works/chord/-/chord-0.85.1.tgz", + "integrity": "sha512-VDlkEC3dhCzQ5fcyH1OhG19dq+6jCn+rqc/iXFivwDYGR5anwo2RCiXij9PpHhqNR5GuhhE+Er69Zi1Sn4eY6w==", + "license": "MIT", + "dependencies": { + "esbuild": "0.28.1" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-agent-core": { + "version": "0.85.1", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-0.85.1.tgz", + "integrity": "sha512-hIXIP3eAWueAYiAl8aMvWCvvZ8Q5gT3Dip5bE5uJyIGh4+YlWRjtMLI4BaeoXoSs93zndjue61u1B/vhefLnuA==", + "license": "MIT", + "dependencies": { + "@earendil-works/chord": "^0.85.1", + "@earendil-works/pi-ai": "^0.85.1", + "@earendil-works/pi-telemetry": "^0.85.1", + "diff": "8.0.4", + "ignore": "7.0.5", + "typebox": "1.3.7", + "yaml": "2.9.0" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-ai": { + "version": "0.85.1", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-0.85.1.tgz", + "integrity": "sha512-+VgVIJDkDO2efYJKEEqvPTH4zmnIaXdAppGbO+vKFA9qy5PdhFiAenuFAkU+oiCSfOC4dMHDyrjdQeL4ZoC5CQ==", + "license": "MIT", + "dependencies": { + "@anthropic-ai/sdk": "0.123.0", + "@aws-sdk/client-bedrock-runtime": "3.1048.0", + "@earendil-works/pi-telemetry": "^0.85.1", + "@google/genai": "1.52.0", + "@smithy/node-http-handler": "4.7.3", + "http-proxy-agent": "7.0.2", + "https-proxy-agent": "7.0.6", + "openai": "6.40.0", + "partial-json": "0.1.7", + "typebox": "1.3.7" + }, + "bin": { + "pi-ai": "dist/cli.js" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-telemetry": { + "version": "0.85.1", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-0.85.1.tgz", + "integrity": "sha512-Bg/YN6kA7Swja/NQxka8xFdecb4E/auIEGF2G5A25EaQXhRnPj300/7/KpgsDDMYUzHTDAv4RyUxaQPJKW81Rw==", + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-tui": { + "version": "0.85.1", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-tui/-/pi-tui-0.85.1.tgz", + "integrity": "sha512-OIzw9efInmO4WOBnD4TxcTdBjmzvYJpzslkgoUro946nEGoYWg5rwv1p4fDt3/JvMx9QybryUCUwlm7j8Dreig==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "1.6.0", + "marked": "18.0.5" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@google/genai": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/@google/genai/-/genai-1.52.0.tgz", + "integrity": "sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "google-auth-library": "^10.3.0", + "p-retry": "^4.6.2", + "protobufjs": "^7.5.4", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.25.2" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + } + }, + "node_modules/@huggingface/jinja": { + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.5.10.tgz", + "integrity": "sha512-SgS1D1bglQ94ceD4ZCL6eayUDy9uV1xuyk61OjgSxU5GJh7upqZCKII0JoTYMc6wWsg3JUgaPRX0ElQzXPk3Cw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/tokenizers": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.1.3.tgz", + "integrity": "sha512-8rF/RRT10u+kn7YuUbUg0OF30K8rjTc78aHpxT+qJ1uWSqxT1MHi8+9ltwYfkFYJzT/oS+qw3JVfHtNMGAdqyA==", + "license": "Apache-2.0" + }, + "node_modules/@huggingface/transformers": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-4.2.0.tgz", + "integrity": "sha512-8BRCoBMH0XsWaEIamuR0LrJGAfftgHAfb2Vrffy0VKlSAE/MnUJ5/h/zTfEP3fDIft+nk7TqB8xXEyABGitBjQ==", + "license": "Apache-2.0", + "dependencies": { + "@huggingface/jinja": "^0.5.6", + "@huggingface/tokenizers": "^0.1.3", + "onnxruntime-node": "1.24.3", + "onnxruntime-web": "1.26.0-dev.20260416-b7804b056c", + "sharp": "^0.34.5" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jitl/quickjs-ffi-types": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-ffi-types/-/quickjs-ffi-types-0.32.0.tgz", + "integrity": "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg==", + "license": "MIT" + }, + "node_modules/@jitl/quickjs-wasmfile-debug-asyncify": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-wasmfile-debug-asyncify/-/quickjs-wasmfile-debug-asyncify-0.32.0.tgz", + "integrity": "sha512-EX8zbXwGqCgAE764M+qvkHtyXDi/FUoMBea0JnES7vCM3P7a2+EOZOjGv85wtZ2sJhI1oJ+nekmqpOODFDY+hw==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, + "node_modules/@jitl/quickjs-wasmfile-debug-sync": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-wasmfile-debug-sync/-/quickjs-wasmfile-debug-sync-0.32.0.tgz", + "integrity": "sha512-LeYWrPGC1uNCTBWvibo3ZLJj0CSVNYUXvJpXMCmuQ5Sap2cCACc3uvGvYV4homHHBAzfw5akoTqMMS4YFRtw+Q==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, + "node_modules/@jitl/quickjs-wasmfile-release-asyncify": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-wasmfile-release-asyncify/-/quickjs-wasmfile-release-asyncify-0.32.0.tgz", + "integrity": "sha512-3oSwPfja12ICz4aIblB58cuY8JlEq5Txt8Cut4VLo+LH47QN+mzCnSgnbB03hWzg1LBcc+VyyI9UOag7a1NF+Q==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, + "node_modules/@jitl/quickjs-wasmfile-release-sync": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-wasmfile-release-sync/-/quickjs-wasmfile-release-sync-0.32.0.tgz", + "integrity": "sha512-BKNDI/TPBfGlLNGYpLrhcDGXmIk4xHm4MRAisOBnOzpXVn9HZWsfmMAc9WMBrAHjvvds6HOikKeaOBKdPdpVrg==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, + "node_modules/@mixmark-io/domino": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz", + "integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==", + "license": "BSD-2-Clause" + }, + "node_modules/@mongodb-js/zstd": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/zstd/-/zstd-7.0.0.tgz", + "integrity": "sha512-mQ2s0pYYiav+tzCDR05Zptem8Ey2v8s11lri5RKGhTtL4COVCvVCk5vtyRYNT+9L8qSfyOqqefF9UtnW8mC5jA==", + "hasInstallScript": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "node-addon-api": "^8.5.0", + "prebuild-install": "^7.1.3" + }, + "engines": { + "node": ">= 20.19.0" + } + }, + "node_modules/@nodable/entities": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.0.0.tgz", + "integrity": "sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/nodable" + } + ], + "license": "MIT" + }, + "node_modules/@oxc-project/types": { + "version": "0.149.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.149.0.tgz", + "integrity": "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz", + "integrity": "sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.8.tgz", + "integrity": "sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.8.tgz", + "integrity": "sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.8.tgz", + "integrity": "sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.8.tgz", + "integrity": "sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.8.tgz", + "integrity": "sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.8.tgz", + "integrity": "sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.8.tgz", + "integrity": "sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.8.tgz", + "integrity": "sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.8.tgz", + "integrity": "sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.8.tgz", + "integrity": "sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.8.tgz", + "integrity": "sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.8.tgz", + "integrity": "sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.8.tgz", + "integrity": "sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.8.tgz", + "integrity": "sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@smithy/core": { + "version": "3.33.3", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.33.3.tgz", + "integrity": "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz", + "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.2", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz", + "integrity": "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.18.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.7.3", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.7.3.tgz", + "integrity": "sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.24.3", + "@smithy/types": "^4.14.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.3.tgz", + "integrity": "sha512-7ImGm+FkHRLcBaRttIAMZ6bzJZWb2cJGoYjq46F2UjycujWzrL9GEN9h4w7eQyXJYnltrUhxbbieBAIRrdqpow==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.18.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.18.0.tgz", + "integrity": "sha512-CgB6HHWer/vrKps24ulRIbpcpb7K4xAU7SkZ7YHzBPlwHsvsrCJFEXK421s+cJzX+ZrqtA/TuU5w1HzI7k9N8A==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT" + }, + "node_modules/@tokenizer/inflate": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz", + "integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "token-types": "^6.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.2.tgz", + "integrity": "sha512-xlvWf4Vs9n1PEVYwP1n4vvG07M6y8WgvJ2t0vbrWTmijsIHp1cS+uJ2kMIRdY3nHZK0nCYKrPeD171+SzF4/zw==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", + "license": "MIT" + }, + "node_modules/@xmldom/xmldom": { + "version": "0.9.12", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz", + "integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==", + "license": "MIT", + "engines": { + "node": ">=14.6" + } + }, + "node_modules/@xterm/addon-fit": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" + }, + "node_modules/@xterm/addon-unicode-graphemes": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-unicode-graphemes/-/addon-unicode-graphemes-0.4.0.tgz", + "integrity": "sha512-9+/CqwbKcnlkJU4d3wIgO+wjsL8f6vyz+UwUWLu6nADQz8Gr8ONqGCJfdDjIdI+yYZLABQqQy47FzEM6AWELjw==", + "license": "MIT" + }, + "node_modules/@xterm/xterm": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, + "node_modules/adm-zip": { + "version": "0.5.18", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.18.tgz", + "integrity": "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==", + "license": "MIT", + "engines": { + "node": ">=12.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/anynum": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/anynum/-/anynum-1.0.1.tgz", + "integrity": "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/argparse": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.2.tgz", + "integrity": "sha512-mFdDM6WqWKraGLsVb+C9CahPnzTXOefAOLq3jYcca2YZ8bEWpr++Tzj+zSaKW9+X9L5uSxcm1AZ3Y6aZJ09OhQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bignumber.js": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", + "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "optional": true, + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bl/node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/boolean": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz", + "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT" + }, + "node_modules/bowser": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz", + "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", + "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC", + "optional": true + }, + "node_modules/commander": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz", + "integrity": "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", + "license": "MIT" + }, + "node_modules/diff": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", + "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "optional": true, + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense" + }, + "node_modules/fast-xml-builder": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.1.tgz", + "integrity": "sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "path-expression-matcher": "^1.6.2", + "xml-naming": "^0.3.0" + } + }, + "node_modules/fast-xml-parser": { + "version": "5.11.1", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.11.1.tgz", + "integrity": "sha512-TBw6K/fxoQGGjCmZDw9w/ZwP3uDcnTM4YH/g+PFRWr8sbe5idXtxNN6vITh4+1ruCZaho6uBFurElsA7F0zzgw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "@nodable/entities": "^3.0.0", + "fast-xml-builder": "^1.2.0", + "is-unsafe": "^2.0.0", + "path-expression-matcher": "^1.6.2", + "strnum": "^2.4.2", + "xml-naming": "^0.3.0" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/file-type": { + "version": "21.3.4", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.3.4.tgz", + "integrity": "sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g==", + "license": "MIT", + "dependencies": { + "@tokenizer/inflate": "^0.4.1", + "strtok3": "^10.3.4", + "token-types": "^6.1.1", + "uint8array-extras": "^1.4.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT", + "optional": true + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gaxios": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz", + "integrity": "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "node-fetch": "^3.3.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/gcp-metadata": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz", + "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^7.0.0", + "google-logging-utils": "^1.0.0", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", + "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT", + "optional": true + }, + "node_modules/global-agent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz", + "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "es6-error": "^4.1.1", + "matcher": "^3.0.0", + "roarr": "^2.15.3", + "semver": "^7.3.2", + "serialize-error": "^7.0.1" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/google-auth-library": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz", + "integrity": "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^7.1.4", + "gcp-metadata": "8.1.2", + "google-logging-utils": "1.1.3", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/google-logging-utils": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz", + "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC" + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hash-wasm": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/hash-wasm/-/hash-wasm-4.12.0.tgz", + "integrity": "sha512-+/2B2rYLb48I/evdOIhP+K/DD2ca2fgBjp6O+GBEnCDk2e4rpeXIK8GvIyRPjTezgmWn9gmKwkQjjx6BtqDHVQ==", + "license": "MIT" + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC", + "optional": true + }, + "node_modules/ini": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-6.0.0.tgz", + "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==", + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/is-unsafe": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.2.tgz", + "integrity": "sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "license": "ISC" + }, + "node_modules/just-bash": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/just-bash/-/just-bash-3.4.2.tgz", + "integrity": "sha512-T0Vpy7YRgCjxJdqG3tkxn0ZnIDLJvVwb8hH4L+6NVdp+Te27jQxjxnszW9ODjEKbWxWujj83rP5S0GQxCSufgg==", + "license": "Apache-2.0", + "dependencies": { + "diff": "^8.0.4", + "fast-xml-parser": "^5.10.1", + "file-type": "^21.3.4", + "ini": "^6.0.0", + "minimatch": "^10.2.6", + "modern-tar": "^0.7.7", + "papaparse": "^5.6.0", + "quickjs-emscripten": "^0.32.0", + "re2js": "^1.3.3", + "seek-bzip": "^2.0.0", + "smol-toml": "^1.8.0", + "sprintf-js": "^1.1.3", + "sql.js": "^1.14.1", + "turndown": "^7.2.4", + "undici": "^7.29.0", + "yaml": "^2.9.0" + }, + "bin": { + "just-bash": "dist/bin/just-bash.js", + "just-bash-shell": "dist/bin/shell/shell.js" + }, + "engines": { + "node": ">=20.18.1" + }, + "optionalDependencies": { + "@mongodb-js/zstd": "^7.0.0", + "node-liblzma": "^2.2.0" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/linkify-it": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-6.1.0.tgz", + "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^3.0.0" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/markdown-it": { + "version": "15.0.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.2.tgz", + "integrity": "sha512-q4IGxMv56jCqT4OCRCADBoDP3LO4MhmTXjFbphHPXs4g3j9Xg5RDnxqN8IF/3vIWEU+VCnUq+7JUg/cfy2E6Qw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^3.0.0", + "entities": "^8.0.0", + "linkify-it": "^6.0.0", + "mdurl": "^2.1.0", + "punycode.js": "^2.3.1", + "uc.micro": "^3.0.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/marked": { + "version": "18.0.5", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.0.5.tgz", + "integrity": "sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/matcher": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz", + "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "license": "MIT" + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT", + "optional": true + }, + "node_modules/modern-tar": { + "version": "0.7.7", + "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.7.7.tgz", + "integrity": "sha512-t9VmxaqrmANnEOBhpSDI6HD192Ge48k8vmWqQQL7hSFEqHEYwZbbsu49+aKLWZeRvFs3j1pMhXOqqF4kPlvjkQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT", + "optional": true + }, + "node_modules/node-abi": { + "version": "3.96.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.96.0.tgz", + "integrity": "sha512-rebQ/lz7i0EkoLzUVSrKRzA69zMkwLp95kKMWoMDkkM00Suxz0D7zEQPwRml5fQum24mj7bPvmlgLAmu2JCiYg==", + "license": "MIT", + "optional": true, + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "license": "MIT", + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/node-liblzma": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/node-liblzma/-/node-liblzma-2.2.0.tgz", + "integrity": "sha512-s0KzNOWwOJJgPG6wxg6cKohnAl9Wk/oW1KrQaVzJBjQwVcUGPQCzpR46Ximygjqj/3KhOrtJXnYMp/xYAXp75g==", + "hasInstallScript": true, + "license": "LGPL-3.0", + "optional": true, + "dependencies": { + "node-addon-api": "^8.5.0", + "node-gyp-build": "^4.8.4" + }, + "bin": { + "nxz": "lib/cli/nxz.js" + }, + "engines": { + "node": ">=16.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/oorabona" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "optional": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onnxruntime-common": { + "version": "1.24.3", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.24.3.tgz", + "integrity": "sha512-GeuPZO6U/LBJXvwdaqHbuUmoXiEdeCjWi/EG7Y1HNnDwJYuk6WUbNXpF6luSUY8yASul3cmUlLGrCCL1ZgVXqA==", + "license": "MIT" + }, + "node_modules/onnxruntime-node": { + "version": "1.24.3", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.24.3.tgz", + "integrity": "sha512-JH7+czbc8ALA819vlTgcV+Q214/+VjGeBHDjX81+ZCD0PCVCIFGFNtT0V4sXG/1JXypKPgScQcB3ij/hk3YnTg==", + "hasInstallScript": true, + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "adm-zip": "^0.5.16", + "global-agent": "^3.0.0", + "onnxruntime-common": "1.24.3" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.26.0-dev.20260416-b7804b056c", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.26.0-dev.20260416-b7804b056c.tgz", + "integrity": "sha512-MD6Ss4GSpQBo6zqoJzyT9LRbKYs7x/JVN23FT24EcEvlqF4VuzPOeH6X38orZPKHQDbprn7K+SBpu0/mj2CQiw==", + "license": "MIT", + "dependencies": { + "flatbuffers": "^25.1.24", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.24.0-dev.20251116-b39e144322", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { + "version": "1.24.0-dev.20251116-b39e144322", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.24.0-dev.20251116-b39e144322.tgz", + "integrity": "sha512-BOoomdHYmNRL5r4iQ4bMvsl2t0/hzVQ3OM3PHD0gxeXu1PmggqBv3puZicEUVOA3AtHHYmqZtjMj9FOfGrATTw==", + "license": "MIT" + }, + "node_modules/openai": { + "version": "6.40.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-6.40.0.tgz", + "integrity": "sha512-MWtTjd/gQt4jpbji61NTgFWJLoY/PdRJ6wG9/ZDRMYNMlBKrCrSlkLI+KgHP1vR1qT6LKSAyAqIxno6lcK9JiA==", + "license": "Apache-2.0", + "peerDependencies": { + "ws": "^8.18.0", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "ws": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/p-retry": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/papaparse": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.7.0.tgz", + "integrity": "sha512-qBGxg/7Q3Kl9Wfhrz2Z74UnvnHTXLNG6jmKJFeBvP2+y4lV7So+7SR62+Zd47JvdrCkX+nDcnr0ObPzek/+6RA==", + "license": "MIT" + }, + "node_modules/partial-json": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz", + "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==", + "license": "MIT" + }, + "node_modules/path-expression-matcher": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.6.2.tgz", + "integrity": "sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT" + }, + "node_modules/playwright": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", + "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.58.2" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", + "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "optional": true, + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prismjs": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz", + "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "optional": true, + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/quickjs-emscripten": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/quickjs-emscripten/-/quickjs-emscripten-0.32.0.tgz", + "integrity": "sha512-So0Sqw869y/S2oE3Nuc0uT3Dhqgvsj8FSrwBdsuTosVsG8ME5/OcudU1GxsrIFdFABgy17GHnTVO9TYV/bLQcA==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-wasmfile-debug-asyncify": "0.32.0", + "@jitl/quickjs-wasmfile-debug-sync": "0.32.0", + "@jitl/quickjs-wasmfile-release-asyncify": "0.32.0", + "@jitl/quickjs-wasmfile-release-sync": "0.32.0", + "quickjs-emscripten-core": "0.32.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/quickjs-emscripten-core": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/quickjs-emscripten-core/-/quickjs-emscripten-core-0.32.0.tgz", + "integrity": "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "optional": true, + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/rc/node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC", + "optional": true + }, + "node_modules/re2js": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/re2js/-/re2js-1.3.3.tgz", + "integrity": "sha512-s/I5zEAo79SUK0Qw4dpZKpiMwbQ6Gz0KU2NRr7eaO4x/p2g7Vvmn3hdeXDg8VsaUjfj/ora+e9oi27LX/C9+mw==", + "license": "MIT" + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/roarr": { + "version": "2.15.4", + "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", + "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "detect-node": "^2.0.4", + "globalthis": "^1.0.1", + "json-stringify-safe": "^5.0.1", + "semver-compare": "^1.0.0", + "sprintf-js": "^1.1.2" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/rolldown": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz", + "integrity": "sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.149.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.8", + "@rolldown/binding-android-arm64": "1.2.8", + "@rolldown/binding-darwin-arm64": "1.2.8", + "@rolldown/binding-darwin-x64": "1.2.8", + "@rolldown/binding-freebsd-x64": "1.2.8", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.8", + "@rolldown/binding-linux-arm64-gnu": "1.2.8", + "@rolldown/binding-linux-arm64-musl": "1.2.8", + "@rolldown/binding-linux-ppc64-gnu": "1.2.8", + "@rolldown/binding-linux-s390x-gnu": "1.2.8", + "@rolldown/binding-linux-x64-gnu": "1.2.8", + "@rolldown/binding-linux-x64-musl": "1.2.8", + "@rolldown/binding-openharmony-arm64": "1.2.8", + "@rolldown/binding-win32-arm64-msvc": "1.2.8", + "@rolldown/binding-win32-x64-msvc": "1.2.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/seek-bzip": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/seek-bzip/-/seek-bzip-2.0.0.tgz", + "integrity": "sha512-SMguiTnYrhpLdk3PwfzHeotrcwi8bNV4iemL9tx9poR/yeaMYwB9VzR1w7b57DuWpuqR8n6oZboi0hj3AxZxQg==", + "license": "MIT", + "dependencies": { + "commander": "^6.0.0" + }, + "bin": { + "seek-bunzip": "bin/seek-bunzip", + "seek-table": "bin/seek-bzip-table" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==", + "license": "MIT" + }, + "node_modules/serialize-error": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz", + "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.13.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/smol-toml": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.8.0.tgz", + "integrity": "sha512-kCZr2V3ch9i00x8zXRhjUNVcjG9ijES5dDudkXvUVCT5QlJNQWElSJdZqyPemffHoLNUYwOcou0Fy+ojN0uHSQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "license": "BSD-3-Clause" + }, + "node_modules/sql.js": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/sql.js/-/sql.js-1.14.2.tgz", + "integrity": "sha512-3ZGPovObMFrdw79zrUHbfdE/DLIsy8jdNdssmMSQuRAymedU6q84asPt0kgiqrdMYlPegDItiIMfmIXzZnYFcw==", + "license": "MIT" + }, + "node_modules/standardwebhooks": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", + "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strnum": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.4.2.tgz", + "integrity": "sha512-rDG3Ah4TV0k1hWvLSzkZtMmLN9+eS+h3knq4MP6A42Y3Yh5qGNnOUs1jJkoSr8FG5dsL28c7KgkIBzSEykqtuw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "anynum": "^1.0.1" + } + }, + "node_modules/strtok3": { + "version": "10.3.5", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.5.tgz", + "integrity": "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "optional": true, + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/token-types": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz", + "integrity": "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==", + "license": "MIT", + "dependencies": { + "@borewit/text-codec": "^0.2.1", + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/turndown": { + "version": "7.2.4", + "resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.4.tgz", + "integrity": "sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ==", + "license": "MIT", + "dependencies": { + "@mixmark-io/domino": "^2.2.0" + }, + "engines": { + "node": ">=18", + "npm": ">=9" + } + }, + "node_modules/type-fest": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz", + "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typebox": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.7.tgz", + "integrity": "sha512-meKuifc33Pccx0O6PdIzYMq3Og8zvP4TIi/a+Bw3AEMZMxOD0+RHGQvpglEe6Zdy3wZ8nqn/j95h8LUZLk/6Hg==", + "license": "MIT" + }, + "node_modules/uc.micro": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-3.0.0.tgz", + "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "license": "MIT" + }, + "node_modules/uint8array-extras": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", + "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/undici": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", + "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT", + "optional": true + }, + "node_modules/vite": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz", + "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.6", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC", + "optional": true + }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-naming": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz", + "integrity": "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + } + } +} diff --git a/app/package.json b/app/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2b9e3d5436126cf811f7656ef5cf638a8d6bb75c --- /dev/null +++ b/app/package.json @@ -0,0 +1,49 @@ +{ + "name": "minicpm5-pi-browser", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --host 127.0.0.1", + "build": "vite build", + "preview": "vite preview --host 127.0.0.1", + "test": "node --test tests/*.test.mjs", + "test:browser": "node tests/browser.mjs", + "test:terminal": "node tests/terminal.mjs", + "test:render": "node tests/render.mjs", + "test:conversation": "node tests/conversation.mjs", + "test:first-message": "node tests/first-message.mjs", + "test:cached-start": "node tests/cached-start.mjs", + "test:runtime-meter": "node tests/runtime-meter.mjs", + "test:mascot": "node tests/mascot.mjs", + "test:modal-cat": "node tests/modal-cat.mjs", + "test:column-resizer": "node tests/column-resizer.mjs", + "test:load-flow": "node tests/load-flow.mjs", + "test:follow-read": "node tests/follow-read.mjs", + "test:editor": "node tests/editor.mjs", + "test:starter-products": "node tests/starter-products.mjs", + "test:sales-demo": "node tests/sales-demo.mjs", + "test:shell": "node tests/shell.mjs", + "test:context": "node tests/context.mjs" + }, + "dependencies": { + "@earendil-works/pi-agent-core": "0.85.1", + "@earendil-works/pi-ai": "0.85.1", + "@earendil-works/pi-tui": "0.85.1", + "@huggingface/transformers": "4.2.0", + "@xmldom/xmldom": "0.9.12", + "@xterm/addon-fit": "0.11.0", + "@xterm/addon-unicode-graphemes": "0.4.0", + "@xterm/xterm": "6.0.0", + "buffer": "6.0.3", + "events": "3.3.0", + "hash-wasm": "4.12.0", + "just-bash": "3.4.2", + "markdown-it": "15.0.2", + "prismjs": "1.30.0" + }, + "devDependencies": { + "playwright": "1.58.2", + "vite": "8.3.0" + } +} diff --git a/app/public/cat-meow-v1.mp3 b/app/public/cat-meow-v1.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..d59c823a1cf61fea89d83883fe867d118c442c88 Binary files /dev/null and b/app/public/cat-meow-v1.mp3 differ diff --git a/app/public/empty-cat-v1.png b/app/public/empty-cat-v1.png new file mode 100644 index 0000000000000000000000000000000000000000..6b5f9e1b7115ecbca224a690e244e5591608576b --- /dev/null +++ b/app/public/empty-cat-v1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:592558545d0ef05a4d29fd27eeeb5b63468f1f378bb1c50359a60f8d2a88f668 +size 668737 diff --git a/app/public/favicon.svg b/app/public/favicon.svg new file mode 100644 index 0000000000000000000000000000000000000000..c28d6242332dcb8dce3802cbc8cc8334ec69e245 --- /dev/null +++ b/app/public/favicon.svg @@ -0,0 +1,21 @@ + + + + + + diff --git a/app/public/file-icons/config.svg b/app/public/file-icons/config.svg new file mode 100644 index 0000000000000000000000000000000000000000..33ee889f350611b787ca9732c6ed0674ff1cfe12 --- /dev/null +++ b/app/public/file-icons/config.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/css.svg b/app/public/file-icons/css.svg new file mode 100644 index 0000000000000000000000000000000000000000..efaf67783a3ead779f521bdb1af7e9b651799ff1 --- /dev/null +++ b/app/public/file-icons/css.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/csv.svg b/app/public/file-icons/csv.svg new file mode 100644 index 0000000000000000000000000000000000000000..6485127fbf04a4877e3c5d2d8fc1d0bcfd807424 --- /dev/null +++ b/app/public/file-icons/csv.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/db.svg b/app/public/file-icons/db.svg new file mode 100644 index 0000000000000000000000000000000000000000..44d29506ef73be031657e6ae5f5df94b61aba39e --- /dev/null +++ b/app/public/file-icons/db.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/default.svg b/app/public/file-icons/default.svg new file mode 100644 index 0000000000000000000000000000000000000000..9f135621dada59eaf85dd480785bbcba867e92b8 --- /dev/null +++ b/app/public/file-icons/default.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/git.svg b/app/public/file-icons/git.svg new file mode 100644 index 0000000000000000000000000000000000000000..66656093c2caeb6c415dd5c6c53bdb597fce44c5 --- /dev/null +++ b/app/public/file-icons/git.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/html.svg b/app/public/file-icons/html.svg new file mode 100644 index 0000000000000000000000000000000000000000..3f99278f3e375623602b34423e77cf7d3fb99a4d --- /dev/null +++ b/app/public/file-icons/html.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/image.svg b/app/public/file-icons/image.svg new file mode 100644 index 0000000000000000000000000000000000000000..0b151d2fe7862228f2cab5dfe4b4c5c613e49cbf --- /dev/null +++ b/app/public/file-icons/image.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/javascript.svg b/app/public/file-icons/javascript.svg new file mode 100644 index 0000000000000000000000000000000000000000..1d0e367f4a41bd13ba1b2ea2389073618ee9ec5c --- /dev/null +++ b/app/public/file-icons/javascript.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/json.svg b/app/public/file-icons/json.svg new file mode 100644 index 0000000000000000000000000000000000000000..91b855c67c7cf693cf131c2c2751aa95df14572b --- /dev/null +++ b/app/public/file-icons/json.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/markdown.svg b/app/public/file-icons/markdown.svg new file mode 100644 index 0000000000000000000000000000000000000000..090cd70e04eacf5b7a1d8894cdac85d0100577b5 --- /dev/null +++ b/app/public/file-icons/markdown.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/pdf.svg b/app/public/file-icons/pdf.svg new file mode 100644 index 0000000000000000000000000000000000000000..2665a879117ab32da1e49a234d04a45d110ce365 --- /dev/null +++ b/app/public/file-icons/pdf.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/python.svg b/app/public/file-icons/python.svg new file mode 100644 index 0000000000000000000000000000000000000000..089fa123678ecc0f8c16e43909b0fe5f14dfbaec --- /dev/null +++ b/app/public/file-icons/python.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/react.svg b/app/public/file-icons/react.svg new file mode 100644 index 0000000000000000000000000000000000000000..c377abf9b71714aeb4dce5d76887686b33055e4b --- /dev/null +++ b/app/public/file-icons/react.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/shell.svg b/app/public/file-icons/shell.svg new file mode 100644 index 0000000000000000000000000000000000000000..5c44300286a56fbde29c427b881de455efa63f00 --- /dev/null +++ b/app/public/file-icons/shell.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/svg.svg b/app/public/file-icons/svg.svg new file mode 100644 index 0000000000000000000000000000000000000000..a64612498cd526b66cc90fa325be3573d0250d72 --- /dev/null +++ b/app/public/file-icons/svg.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/typescript.svg b/app/public/file-icons/typescript.svg new file mode 100644 index 0000000000000000000000000000000000000000..56ab8fe1d2a35a3dd15418335d82da316080c246 --- /dev/null +++ b/app/public/file-icons/typescript.svg @@ -0,0 +1 @@ + diff --git a/app/public/file-icons/zip.svg b/app/public/file-icons/zip.svg new file mode 100644 index 0000000000000000000000000000000000000000..ab124883f6c085e0a2652897f7bc1b20ce618967 --- /dev/null +++ b/app/public/file-icons/zip.svg @@ -0,0 +1 @@ + diff --git a/app/public/http-help.html b/app/public/http-help.html new file mode 100644 index 0000000000000000000000000000000000000000..479c68a98523501acd2cb95bddc38b96abfbc61f --- /dev/null +++ b/app/public/http-help.html @@ -0,0 +1,17 @@ + + +Browser HTTP experiment + +

HTTP from the browser shell

+

This experimental copy enables real curl and wget requests. The model and shell run on your device. Requests go directly from your browser to the destination; there is no proxy. Request URLs, headers, and bodies are sent to that service.

+

Allowed HTTPS hosts: api.github.com, raw.githubusercontent.com, huggingface.co, jsonplaceholder.typicode.com, and httpbin.org. GET, HEAD, and POST are enabled. Cookies are omitted. Requests have an 8-second deadline and a 1 MiB response limit.

+

Try in Shell

+
curl -fsS https://jsonplaceholder.typicode.com/todos/1 -o todo.json
+jq '{id, title, completed}' todo.json
+
set -o pipefail
+curl -fsS https://api.github.com/repos/huggingface/transformers.js | jq '{full_name, stargazers_count}'
+

Ask Pi

+

“Fetch https://jsonplaceholder.typicode.com/todos/1, save it as todo.json, and tell me its title and whether it is completed.”

+

The destination must allow browser access with CORS. Redirects are reported as errors: use the final URL directly, with the exact capitalization. A plain curl pipeline can hide an error unless you enable set -o pipefail. Python, Node.js, npm, and native binaries remain unavailable.

+

Back to the workspace · Original Space

+ diff --git a/app/public/library-icons/huggingface.svg b/app/public/library-icons/huggingface.svg new file mode 100644 index 0000000000000000000000000000000000000000..43c5d3c0c97a9150b19d10bc68f4c9042c5034cd --- /dev/null +++ b/app/public/library-icons/huggingface.svg @@ -0,0 +1,37 @@ + + + + + + + + + + + diff --git a/app/public/library-icons/onnxruntime.ico b/app/public/library-icons/onnxruntime.ico new file mode 100644 index 0000000000000000000000000000000000000000..b47880019f3c20d814a6cb40bc5523e5d48f8e88 Binary files /dev/null and b/app/public/library-icons/onnxruntime.ico differ diff --git a/app/public/licenses/library-icons-NOTICE.txt b/app/public/licenses/library-icons-NOTICE.txt new file mode 100644 index 0000000000000000000000000000000000000000..a059f382dc2334c86c9b846c198f56acd527baf2 --- /dev/null +++ b/app/public/licenses/library-icons-NOTICE.txt @@ -0,0 +1,12 @@ +Library credits icons, obtained 2026-09-14. + +Hugging Face logo (unmodified): +https://huggingface.co/front/assets/huggingface_logo-noborder.svg + +ONNX Runtime favicon (unmodified): +https://onnxruntime.ai/favicon.ico + +Pi mark: official paths reused from the header; see pi-logo-NOTICE.txt. +The terminal beside just-bash is an app-drawn generic shell icon. + +Names and marks identify the upstream projects used by this independent demo. diff --git a/app/public/licenses/onnxruntime-LICENSE b/app/public/licenses/onnxruntime-LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..48bc6bb4996ac924359e8e28b9ae88970e5ed3fc --- /dev/null +++ b/app/public/licenses/onnxruntime-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/public/licenses/onnxruntime-ThirdPartyNotices.txt b/app/public/licenses/onnxruntime-ThirdPartyNotices.txt new file mode 100644 index 0000000000000000000000000000000000000000..fbd9f9a95f6013d8ecaef81e02b0033e5882a675 --- /dev/null +++ b/app/public/licenses/onnxruntime-ThirdPartyNotices.txt @@ -0,0 +1,6121 @@ +THIRD PARTY SOFTWARE NOTICES AND INFORMATION + +Do Not Translate or Localize + +This software incorporates material from third parties. Microsoft makes certain +open source code available at http://3rdpartysource.microsoft.com, or you may +send a check or money order for US $5.00, including the product name, the open +source component name, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the +extent required to debug changes to any libraries licensed under the GNU Lesser +General Public License. + +_____ + +Intel Math Kernel Library (Intel MKL) + +Intel Simplified Software License (Version April 2018) + +Copyright (c) 2018 Intel Corporation. + +Use and Redistribution. You may use and redistribute the software (the “Software”), without modification, +provided the following conditions are met: + +* Redistributions must reproduce the above copyright notice and the following terms of use in the Software +and in the documentation and/or other materials provided with the distribution. + +* Neither the name of Intel nor the names of its suppliers may be used to endorse or promote products +derived from this Software without specific prior written permission. + +* No reverse engineering, decompilation, or disassembly of this Software is permitted. + +Limited patent license. Intel grants you a world-wide, royalty-free, non-exclusive license under patents it now +or hereafter owns or controls to make, have made, use, import, offer to sell and sell (“Utilize”) this Software, +but solely to the extent that any such patent is necessary to Utilize the Software alone. The patent license +shall not apply to any combinations which include this software. No hardware per se is licensed hereunder. + +Third party and other Intel programs. “Third Party Programs” are the files listed in the “third-party-programs.txt” +text file that is included with the Software and may include Intel programs under separate license terms. +Third Party Programs, even if included with the distribution of the Materials, are governed by +separate license terms and those license terms solely govern your use of those programs. + +DISCLAIMER. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. THIS SOFTWARE IS +NOT INTENDED FOR USE IN SYSTEMS OR APPLICATIONS WHERE FAILURE OF THE SOFTWARE +MAY CAUSE PERSONAL INJURY OR DEATH AND YOU AGREE THAT YOU ARE FULLY RESPONSIBLE FOR ANY +CLAIMS, COSTS, DAMAGES, EXPENSES, AND ATTORNEYS’ FEES ARISING OUT OF ANY SUCH USE, +EVEN IF ANY CLAIM ALLEGES THAT INTEL WAS NEGLIGENT REGARDING THE DESIGN OR MANUFACTURE OF +THE MATERIALS. + +LIMITATION OF LIABILITY. IN NO EVENT WILL INTEL BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGE. YOU AGREE TO INDEMNIFY AND HOLD INTEL HARMLESS AGAINST ANY CLAIMS +AND EXPENSES RESULTING FROM YOUR USE OR UNAUTHORIZED USE OF THE SOFTWARE. + +No support. Intel may make changes to the Software, at any time without notice, and is not obligated to +support, update or provide training for the Software. + +Termination. Intel may terminate your right to use the Software in the event of your breach of this Agreement +and you fail to cure the breach within a reasonable period of time. + +Feedback. Should you provide Intel with comments, modifications, corrections, enhancements or other input +(“Feedback”) related to the Software Intel will be free to use, disclose, reproduce, license or otherwise +distribute or exploit the Feedback in its sole discretion without any obligations or restrictions of any kind, +including without limitation, intellectual property rights or licensing obligations. + +Compliance with laws. You agree to comply with all relevant laws and regulations governing your use, +transfer, import or export (or prohibition thereof) of the Software. + +Governing law. All disputes will be governed by the laws of the United States of America and the State of +Delaware without reference to conflict of law principles and subject to the exclusive jurisdiction of the state or +federal courts sitting in the State of Delaware, and each party agrees that it submits to the personal +jurisdiction and venue of those courts and waives any objections. The United Nations Convention on +Contracts for the International Sale of Goods (1980) is specifically excluded and will not apply to the +Software. + +*Other names and brands may be claimed as the property of others. + +_____ + +protocolbuffers/protobuf + +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. + +_____ + +madler/zlib + +The deflate format used by zlib was defined by Phil Katz. The deflate and +zlib specifications were written by L. Peter Deutsch. Thanks to all the +people who reported problems and suggested various improvements in zlib; they +are too numerous to cite here. + +Copyright notice: + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. + +_____ + +pybind/pybind11 + +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Please also refer to the file CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. + +_____ + +onnx +Open Neural Network Exchange + +Copyright (c) Facebook, Inc. and Microsoft Corporation. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +Eigen + +MPL v2.0 +Mozilla Public License Version 2.0 + + +================================== + +1. Definitions + +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions + +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities + +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination + +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + +_____ + +intel/dnnl + +Copyright 2016-2018 Intel Corporation + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +sub-components: + +xbyak + +Copyright (c) 2007 MITSUNARI Shigeo. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. +Neither the name of the copyright owner nor the names of its contributors may +be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +Microsoft GSL + +Copyright (c) 2015 Microsoft Corporation. All rights reserved. + +This code is licensed under the MIT License (MIT). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +_____ + +Tensorflow + +Copyright 2018 The TensorFlow Authors. All rights reserved. + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017, The TensorFlow Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +Microsoft Cognitive Toolkit (CNTK) + +Copyright (c) Microsoft Corporation. All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +_____ + +NumPy License + +Copyright (c) 2005, NumPy Developers + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the NumPy Developers nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +Pytorch / Caffe2 + +From PyTorch: + +Copyright (c) 2016- Facebook, Inc (Adam Paszke) +Copyright (c) 2014- Facebook, Inc (Soumith Chintala) +Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) +Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) +Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) +Copyright (c) 2011-2013 NYU (Clement Farabet) +Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) +Copyright (c) 2006 Idiap Research Institute (Samy Bengio) +Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + +From Caffe2: + +Copyright (c) 2016-present, Facebook Inc. All rights reserved. + +All contributions by Facebook: +Copyright (c) 2016 Facebook Inc. + +All contributions by Google: +Copyright (c) 2015 Google Inc. +All rights reserved. + +All contributions by Yangqing Jia: +Copyright (c) 2015 Yangqing Jia +All rights reserved. + +All contributions from Caffe: +Copyright(c) 2013, 2014, 2015, the respective contributors +All rights reserved. + +All other contributions: +Copyright(c) 2015, 2016 the respective contributors +All rights reserved. + +Caffe2 uses a copyright model similar to Caffe: each contributor holds +copyright over their contributions to Caffe2. The project versioning records +all such contribution and copyright details. If a contributor wants to further +mark their specific copyright on a particular contribution, they should +indicate their copyright solely in the commit message of the change when it is +committed. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +_____ + +Caffe + +COPYRIGHT + +All contributions by the University of California: +Copyright (c) 2014-2017 The Regents of the University of California (Regents) +All rights reserved. + +All other contributions: +Copyright (c) 2014-2017, the respective contributors +All rights reserved. + +Caffe uses a shared copyright model: each contributor holds copyright over +their contributions to Caffe. The project versioning records all such +contribution and copyright details. If a contributor wants to further mark +their specific copyright on a particular contribution, they should indicate +their copyright solely in the commit message of the change when it is +committed. + +LICENSE + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +CONTRIBUTION AGREEMENT + +By contributing to the BVLC/caffe repository through pull-request, comment, +or otherwise, the contributor releases their content to the +license and copyright terms herein. + +_____ + +The LLVM Compiler Infrastructure + +============================================================================== +LLVM Release License +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== +Copyrights and Licenses for Third Party Software Distributed with LLVM: +============================================================================== +The LLVM software contains code written by third parties. Such software will +have its own individual LICENSE.TXT file in the directory in which it appears. +This file will describe the copyrights, license, and restrictions which apply +to that code. + +The disclaimer of warranty in the University of Illinois Open Source License +applies to all code in the LLVM Distribution, and nothing in any of the +other licenses gives permission to use the names of the LLVM Team or the +University of Illinois to endorse or promote products derived from this +Software. + +The following pieces of software have additional or alternate copyrights, +licenses, and/or restrictions: + +Program Directory +------- --------- +Google Test llvm/utils/unittest/googletest +OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex} +pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT} +ARM contributions llvm/lib/Target/ARM/LICENSE.TXT +md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h + +_____ + +google/benchmark + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +CONTRIBUTORS + +# People who have agreed to one of the CLAs and can contribute patches. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# Names should be added to this file only after verifying that +# the individual or the individual's organization has agreed to +# the appropriate Contributor License Agreement, found here: +# +# https://developers.google.com/open-source/cla/individual +# https://developers.google.com/open-source/cla/corporate +# +# The agreement for individuals can be filled out on the web. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file, depending on whether the +# individual or corporate CLA was used. +# +# Names should be added to this file as: +# Name +# +# Please keep the list sorted. + +Albert Pretorius +Arne Beer +Billy Robert O'Neal III +Chris Kennelly +Christopher Seymour +David Coeurjolly +Deniz Evrenci +Dominic Hamon +Dominik Czarnota +Eric Fiselier +Eugene Zhuk +Evgeny Safronov +Federico Ficarelli +Felix Homann +Ismael Jimenez Martinez +Jern-Kuan Leong +JianXiong Zhou +Joao Paulo Magalhaes +John Millikin +Jussi Knuuttila +Kai Wolf +Kishan Kumar +Kaito Udagawa +Lei Xu +Matt Clarkson +Maxim Vafin +Nick Hutchinson +Oleksandr Sochka +Pascal Leroy +Paul Redmond +Pierre Phaneuf +Radoslav Yovchev +Raul Marin +Ray Glover +Robert Guo +Roman Lebedev +Shuo Chen +Tobias Ulvgård +Tom Madams +Yixuan Qiu +Yusuke Suzuki +Zbigniew Skowron + +AUTHORS + +# This is the official list of benchmark authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. +# +# Names should be added to this file as: +# Name or Organization +# The email address is not required for organizations. +# +# Please keep the list sorted. + +Albert Pretorius +Arne Beer +Carto +Christopher Seymour +David Coeurjolly +Deniz Evrenci +Dirac Research +Dominik Czarnota +Eric Fiselier +Eugene Zhuk +Evgeny Safronov +Federico Ficarelli +Felix Homann +Google Inc. +International Business Machines Corporation +Ismael Jimenez Martinez +Jern-Kuan Leong +JianXiong Zhou +Joao Paulo Magalhaes +Jussi Knuuttila +Kaito Udagawa +Kishan Kumar +Lei Xu +Matt Clarkson +Maxim Vafin +MongoDB Inc. +Nick Hutchinson +Oleksandr Sochka +Paul Redmond +Radoslav Yovchev +Roman Lebedev +Shuo Chen +Steinar H. Gunderson +Stripe, Inc. +Yixuan Qiu +Yusuke Suzuki +Zbigniew Skowron + +_____ + +HalideIR + +Copyright (c) 2016 HalideIR contributors +Copyright (c) 2012-2014 MIT CSAIL, Google Inc., and other contributors +HalideIR is derived from the Halide project. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +_____ + +Distributed Machine Learning Common Codebase + +Copyright (c) 2015 by Contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +_____ + +DLPack: Open In Memory Tensor Structure + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 by Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +HowardHinnant/date + +The source code in this project is released using the MIT License. There is no +global license for the project because each file is licensed individually with +different author names and/or dates. + +If you contribute to this project, please add your name to the license of each +file you modify. If you have already contributed to this project and forgot to +add your name to the license, please feel free to submit a new P/R to add your +name to the license in each file you modified. + +For convenience, here is a copy of the MIT license found in each file except +without author names or dates: + +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ + +FreeBSD: getopt.c file + +Copyright (c) 1987, 1993, 1994 +The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the University nor the names of its contributors +may be used to endorse or promote products derived from this software +without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +_____ + + +google/googletest + +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +G3log : Asynchronous logger with Dynamic Sinks + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to +_____ + +Scikit-learn + +Copyright (c) 2007–2018 The scikit-learn developers. +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + a. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + b. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + c. Neither the name of the Scikit-learn Developers nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +_____ + +google/re2 + +Copyright (c) 2009 The RE2 Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +_____ +onnx/onnx-tensorrt + +MIT License + +Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. +Copyright (c) 2018 Open Neural Network Exchange + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ +nvidia/cutlass + +Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ +Boost + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +_____ + +JDAI-CV/DNNLibrary + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2019] [JD.com Inc. JD AI] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +_____ + +google/flatbuffers + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +_____ + +google/glog + +Copyright (c) 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +A function gettimeofday in utilities.cc is based on + +http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/COPYING&q=GetSystemTimeAsFileTime%20license:bsd + +The license of this code is: + +Copyright (c) 2003-2008, Jouni Malinen and contributors +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name(s) of the above-listed copyright holder(s) nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +abseil-cpp +https://github.com/abseil/abseil-cpp + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +_____ + +microsoft/wil + +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE + +_____ + +nlohmann/json + +MIT License + +Copyright (c) 2013-2019 Niels Lohmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ + +dcleblanc/SafeInt + +MIT License + +Copyright (c) 2018 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ +Open MPI + +3-Clause BSD License + +Most files in this release are marked with the copyrights of the +organizations who have edited them. The copyrights below are in no +particular order and generally reflect members of the Open MPI core +team who have contributed code to this release. The copyrights for +code used under license from other parties are included in the +corresponding files. + +Copyright (c) 2004-2010 The Trustees of Indiana University and Indiana + University Research and Technology + Corporation. All rights reserved. +Copyright (c) 2004-2017 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. +Copyright (c) 2004-2010 High Performance Computing Center Stuttgart, + University of Stuttgart. All rights reserved. +Copyright (c) 2004-2008 The Regents of the University of California. + All rights reserved. +Copyright (c) 2006-2017 Los Alamos National Security, LLC. All rights + reserved. +Copyright (c) 2006-2017 Cisco Systems, Inc. All rights reserved. +Copyright (c) 2006-2010 Voltaire, Inc. All rights reserved. +Copyright (c) 2006-2017 Sandia National Laboratories. All rights reserved. +Copyright (c) 2006-2010 Sun Microsystems, Inc. All rights reserved. + Use is subject to license terms. +Copyright (c) 2006-2017 The University of Houston. All rights reserved. +Copyright (c) 2006-2009 Myricom, Inc. All rights reserved. +Copyright (c) 2007-2017 UT-Battelle, LLC. All rights reserved. +Copyright (c) 2007-2017 IBM Corporation. All rights reserved. +Copyright (c) 1998-2005 Forschungszentrum Juelich, Juelich Supercomputing + Centre, Federal Republic of Germany +Copyright (c) 2005-2008 ZIH, TU Dresden, Federal Republic of Germany +Copyright (c) 2007 Evergrid, Inc. All rights reserved. +Copyright (c) 2008 Chelsio, Inc. All rights reserved. +Copyright (c) 2008-2009 Institut National de Recherche en + Informatique. All rights reserved. +Copyright (c) 2007 Lawrence Livermore National Security, LLC. + All rights reserved. +Copyright (c) 2007-2017 Mellanox Technologies. All rights reserved. +Copyright (c) 2006-2010 QLogic Corporation. All rights reserved. +Copyright (c) 2008-2017 Oak Ridge National Labs. All rights reserved. +Copyright (c) 2006-2012 Oracle and/or its affiliates. All rights reserved. +Copyright (c) 2009-2015 Bull SAS. All rights reserved. +Copyright (c) 2010 ARM ltd. All rights reserved. +Copyright (c) 2016 ARM, Inc. All rights reserved. +Copyright (c) 2010-2011 Alex Brick . All rights reserved. +Copyright (c) 2012 The University of Wisconsin-La Crosse. All rights + reserved. +Copyright (c) 2013-2016 Intel, Inc. All rights reserved. +Copyright (c) 2011-2017 NVIDIA Corporation. All rights reserved. +Copyright (c) 2016 Broadcom Limited. All rights reserved. +Copyright (c) 2011-2017 Fujitsu Limited. All rights reserved. +Copyright (c) 2014-2015 Hewlett-Packard Development Company, LP. All + rights reserved. +Copyright (c) 2013-2017 Research Organization for Information Science (RIST). + All rights reserved. +Copyright (c) 2017-2018 Amazon.com, Inc. or its affiliates. All Rights + reserved. +Copyright (c) 2018 DataDirect Networks. All rights reserved. +Copyright (c) 2018-2019 Triad National Security, LLC. All rights reserved. + +$COPYRIGHT$ + +Additional copyrights may follow + +$HEADER$ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. + +- Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +The copyright holders provide no reassurances that the source code +provided does not infringe any patent, copyright, or any other +intellectual property rights of third parties. The copyright holders +disclaim any liability to any recipient for claims brought against +recipient by any third party for infringement of that parties +intellectual property rights. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +The Android Open Source Project + +Copyright (C) 2017 The Android Open Source Project +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------ + +libprotobuf-mutator + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ----- + + openucx/ucx + https://github.com/openucx/ucx + + Copyright (c) 2014-2015 UT-Battelle, LLC. All rights reserved. + Copyright (C) 2014-2020 Mellanox Technologies Ltd. All rights reserved. + Copyright (C) 2014-2015 The University of Houston System. All rights reserved. + Copyright (C) 2015 The University of Tennessee and The University + of Tennessee Research Foundation. All rights reserved. + Copyright (C) 2016-2020 ARM Ltd. All rights reserved. + Copyright (c) 2016 Los Alamos National Security, LLC. All rights reserved. + Copyright (C) 2016-2020 Advanced Micro Devices, Inc. All rights reserved. + Copyright (C) 2019 UChicago Argonne, LLC. All rights reserved. + Copyright (c) 2018-2020 NVIDIA CORPORATION. All rights reserved. + Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + Copyright (C) 2016-2020 Stony Brook University. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ----- + + From PyTorch: + + Copyright (c) 2016- Facebook, Inc (Adam Paszke) + Copyright (c) 2014- Facebook, Inc (Soumith Chintala) + Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) + Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) + Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) + Copyright (c) 2011-2013 NYU (Clement Farabet) + Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) + Copyright (c) 2006 Idiap Research Institute (Samy Bengio) + Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + + From Caffe2: + + Copyright (c) 2016-present, Facebook Inc. All rights reserved. + + All contributions by Facebook: + Copyright (c) 2016 Facebook Inc. + + All contributions by Google: + Copyright (c) 2015 Google Inc. + All rights reserved. + + All contributions by Yangqing Jia: + Copyright (c) 2015 Yangqing Jia + All rights reserved. + + All contributions from Caffe: + Copyright(c) 2013, 2014, 2015, the respective contributors + All rights reserved. + + All other contributions: + Copyright(c) 2015, 2016 the respective contributors + All rights reserved. + + Caffe2 uses a copyright model similar to Caffe: each contributor holds + copyright over their contributions to Caffe2. The project versioning records + all such contribution and copyright details. If a contributor wants to further + mark their specific copyright on a particular contribution, they should + indicate their copyright solely in the commit message of the change when it is + committed. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +_____ + + mpi4py + https://github.com/mpi4py/mpi4py/ + + ======================= + LICENSE: MPI for Python + ======================= + + :Author: Lisandro Dalcin + :Contact: dalcinl@gmail.com + + + Copyright (c) 2019, Lisandro Dalcin. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +_____ +huggingface/transformers + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +_____ +msgpack/msgpack-python + +Copyright (C) 2008-2011 INADA Naoki + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +_____ +lanpa/tensorboardX + +MIT License + +Copyright (c) 2017 Tzu-Wei Huang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +_____ +tensorflow/tensorboard + +Copyright 2017 The TensorFlow Authors. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017, The TensorFlow Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +_____ + +cerberus + +Cerberus is a lightweight and extensible data validation library for Python. + +ISC License + +Copyright (c) 2012-2016 Nicola Iarocci. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +_____ + +MurmurHash3 + +MIT license + +https://github.com/aappleby/smhasher + +SMHasher is a test suite designed to test the distribution, collision, and +performance properties of non-cryptographic hash functions. +This is the home for the MurmurHash family of hash functions along with the +SMHasher test suite used to verify them. +SMHasher is released under the MIT license. +All MurmurHash versions are public domain software, and the author disclaims all copyright to their code. + +_____ + +gtest-ios-framework + +https://github.com/mestevens/gtest-ios-framework + +Copyright (c) 2013 Matthew Stevens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +_____ + +DLPack + +https://github.com/dmlc/dlpack + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 by Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +emsdk + +MIT/Expat license + +https://github.com/emscripten-core/emsdk + +Copyright (c) 2018 Emscripten authors (see AUTHORS in Emscripten) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +---------------------------------------------------------------------------- + +This is the MIT/Expat License. For more information see: + +1. http://www.opensource.org/licenses/mit-license.php + +2. http://en.wikipedia.org/wiki/MIT_License + +_____ + +coremltools + +BSD-3-Clause License + +https://github.com/apple/coremltools + +Copyright (c) 2020, Apple Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +© 2021 GitHub, Inc. + +_____ + +react-native + +MIT License + +https://github.com/facebook/react-native + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ + +pytorch/cpuinfo + +BSD 2-Clause "Simplified" License + +https://github.com/pytorch/cpuinfo + +Copyright (c) 2019 Google LLC +Copyright (c) 2017-2018 Facebook Inc. +Copyright (C) 2012-2017 Georgia Institute of Technology +Copyright (C) 2010-2012 Marat Dukhan + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +SQLite Is Public Domain + +All of the code and documentation in SQLite has been dedicated to the public +domain by the authors. All code authors, and representatives of the companies +they work for, have signed affidavits dedicating their contributions to the +public domain and originals of those signed affidavits are stored in a firesafe +at the main offices of Hwaci. Anyone is free to copy, modify, publish, use, +compile, sell, or distribute the original SQLite code, either in source code +form or as a compiled binary, for any purpose, commercial or non-commercial, +and by any means. + +The previous paragraph applies to the deliverable code and documentation in +SQLite - those parts of the SQLite library that you actually bundle and ship +with a larger application. Some scripts used as part of the build process (for +example the "configure" scripts generated by autoconf) might fall under other +open-source licenses. Nothing from these build scripts ever reaches the final +deliverable SQLite library, however, and so the licenses associated with those +scripts should not be a factor in assessing your rights to copy and use the +SQLite library. + +All of the deliverable code in SQLite has been written from scratch. No code +has been taken from other projects or from the open internet. Every line of +code can be traced back to its original author, and all of those authors have +public domain dedications on file. So the SQLite code base is clean and is +uncontaminated with licensed code from other projects. + +_____ + +google/XNNPACK + +BSD License + +For XNNPACK software + +Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +Copyright 2019 Google LLC + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +google/sentencepiece, https://github.com/google/sentencepiece +(included when statically linked with onnxruntime-extensions) + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +dlfcn-win32/dlfcn-win32 is licensed under the MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +_____ + +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh + +Pillow is the friendly PIL fork. It is + + Copyright © 2010-2023 by Alex Clark and contributors + +Like PIL, Pillow is licensed under the open source HPND License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify, and distribute this software and its +associated documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +_____ + +openssl/openssl, https://github.com/openssl/openssl + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +_____ + +Tencent/rapidjson, https://github.com/Tencent/rapidjson + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License. +If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license. +A copy of the MIT License is included in this file. + +Other dependencies and licenses: + +Open Source Software Licensed Under the BSD License: +-------------------------------------------------------------------- + +The msinttypes r29 +Copyright (c) 2006-2013 Alexander Chemeris +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Open Source Software Licensed Under the JSON License: +-------------------------------------------------------------------- + +json.org +Copyright (c) 2002 JSON.org +All Rights Reserved. + +JSON_checker +Copyright (c) 2002 JSON.org +All Rights Reserved. + + +Terms of the JSON License: +--------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +Terms of the MIT License: +-------------------------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +_____ + +boostorg/boost, https://github.com/boostorg/boost + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +_____ + +libb64/libb64, https://github.com/libb64/libb64 + +Copyright-Only Dedication (based on United States law) or Public Domain Certification + +The person or persons who have associated work with this document (the "Dedicator" or "Certifier") hereby either (a) certifies that, to the best of his knowledge, the work of authorship identified is in the public domain of the country from which the work is published, or (b) hereby dedicates whatever copyright the dedicators holds in the work of authorship identified below (the "Work") to the public domain. A certifier, moreover, dedicates any copyright interest he may have in the associated work, and for these purposes, is described as a "dedicator" below. + +A certifier has taken reasonable steps to verify the copyright status of this work. Certifier recognizes that his good faith efforts may not shield him from liability if in fact the work certified is not in the public domain. + +Dedicator makes this dedication for the benefit of the public at large and to the detriment of the Dedicator's heirs and successors. Dedicator intends this dedication to be an overt act of relinquishment in perpetuity of all present and future rights under copyright law, whether vested or contingent, in the Work. Dedicator understands that such relinquishment of all rights includes the relinquishment of all rights to enforce (by lawsuit or otherwise) those copyrights in the Work. + +Dedicator recognizes that, once placed in the public domain, the Work may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived. + +_____ + +posix pthread library, https://sourceforge.net/projects/pthreads4w + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +Triton Inference Server & Client, https://github.com/triton-inference-server + +Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of NVIDIA CORPORATION nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +microsoft/mimalloc, https://github.com/microsoft/mimalloc + +MIT License + +Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ + +TensorFlow.js + +https://github.com/tensorflow/tfjs + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +—— + +curl/curl + +https://github.com/curl + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (C) Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. + +_____ + +Intel neural-compressor + +https://github.com/intel/neural-compressor + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + ============================================================================ + + Copyright 2016-2019 Intel Corporation + Copyright 2018 YANDEX LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + This distribution includes third party software ("third party programs"). + This third party software, even if included with the distribution of + the Intel software, may be governed by separate license terms, including + without limitation, third party license terms, other Intel software license + terms, and open source software license terms. These separate license terms + govern your use of the third party programs as set forth in the + "THIRD-PARTY-PROGRAMS" file. + +_____ + +FlashAttention, https://github.com/Dao-AILab/flash-attention + +BSD 3-Clause License + +Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +neural-speed + +https://github.com/intel/neural-speed + + Apache License + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + ============================================================================ + + Copyright 2016-2019 Intel Corporation + Copyright 2018 YANDEX LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + This distribution includes third party software ("third party programs"). + This third party software, even if included with the distribution of + the Intel software, may be governed by separate license terms, including + without limitation, third party license terms, other Intel software license + terms, and open source software license terms. These separate license terms + govern your use of the third party programs as set forth in the + "THIRD-PARTY-PROGRAMS" file. + +_____ + +dawn + +https://dawn.googlesource.com/dawn + + BSD 3-Clause License + + Copyright 2017-2023 The Dawn & Tint Authors + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +KleidiAI + +https://gitlab.arm.com/kleidi/kleidiai + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2024-2025 Arm Limited and/or its affiliates + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/app/public/licenses/openbmb-avatar-NOTICE.txt b/app/public/licenses/openbmb-avatar-NOTICE.txt new file mode 100644 index 0000000000000000000000000000000000000000..34a599936270415c03d957bfff2cecb47394306a --- /dev/null +++ b/app/public/licenses/openbmb-avatar-NOTICE.txt @@ -0,0 +1,6 @@ +OpenBMB avatar obtained from its Hugging Face organization on 2026-09-14. +Organization: https://huggingface.co/openbmb +Source: https://cdn-avatars.huggingface.co/v1/production/uploads/1670387859384-633fe7784b362488336bbfad.png + +The unmodified WebP image returned by the CDN is hosted locally and identifies +the model's publisher. diff --git a/app/public/licenses/pi-LICENSE b/app/public/licenses/pi-LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0a8e9b81083294360c69b4ec45d3d39a2b28197 --- /dev/null +++ b/app/public/licenses/pi-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Mario Zechner + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/app/public/licenses/pi-logo-NOTICE.txt b/app/public/licenses/pi-logo-NOTICE.txt new file mode 100644 index 0000000000000000000000000000000000000000..a325563a5cabf914a403ceaffc3f0268eb13b9b8 --- /dev/null +++ b/app/public/licenses/pi-logo-NOTICE.txt @@ -0,0 +1,9 @@ +Pi logo: official Pi / Earendil mark, obtained 2026-09-14. +Source and brand files: https://pi.dev/press-kit +Primary logo: https://pi.dev/logo-auto.svg +Favicon: https://pi.dev/favicon.svg + +The header and setup dialog preserve the official SVG paths, with a tighter +viewBox and currentColor for sizing and the app's dark palette. The favicon +is the unmodified official badge. Pi's name and logo identify the upstream +project; this browser demo is an independent integration. diff --git a/app/public/licenses/seti-icons-LICENSE.txt b/app/public/licenses/seti-icons-LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..0686d9e64771ecfe3d755fbc412be64a3a4b2a77 --- /dev/null +++ b/app/public/licenses/seti-icons-LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2014 Jesse Weed + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/app/public/licenses/seti-icons-NOTICE.txt b/app/public/licenses/seti-icons-NOTICE.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d8dbec5b3798d173deb5e88551537c5f0c37f86 --- /dev/null +++ b/app/public/licenses/seti-icons-NOTICE.txt @@ -0,0 +1,6 @@ +Seti UI file icons by Jesse Weed and contributors, MIT license. +Upstream: https://github.com/jesseweed/seti-ui +Revision: 2d6c5e68b4ded73c92dac291845ee44e1182d511 +Used by VS Code’s built-in Seti file icon theme. +Only 18 icons are included. SVG paths are preserved; viewBoxes are tightened for consistent 16px sizing. Colors use the Seti palette. +The ZIP icon’s white knockout shapes are encoded as a luminance mask so its zipper remains visible when tinted. diff --git a/app/public/licenses/seti-icons-sources.json b/app/public/licenses/seti-icons-sources.json new file mode 100644 index 0000000000000000000000000000000000000000..93d071c13d2a805f02ea7a2adbee1081cc1348b2 --- /dev/null +++ b/app/public/licenses/seti-icons-sources.json @@ -0,0 +1,74 @@ +{ + "default": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/default.svg", + "upstream_sha256": "91cd6ad5e03ba15b5f763cb7f0a7eef4f5e95c72c6e3192b9187c703ed9e7dd6" + }, + "markdown": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/markdown.svg", + "upstream_sha256": "d6e4b4d8b4b32dcaf0defcb0858236326a17a50931dcd30926c8b047dadc0d6c" + }, + "csv": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/csv.svg", + "upstream_sha256": "77adc99b60bfef400b7619484e8646b5b89fcf7f5a28c50563006327f7c4d0e6" + }, + "json": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/json.svg", + "upstream_sha256": "24429711d8ac39d70e0fd3398b2137d82d2637786781c8ed10f3de0b81a0e547" + }, + "javascript": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/javascript.svg", + "upstream_sha256": "dfac57ebdebfea573cd92b04178feee655452e24021a6b5ad4da84c3f5cf8615" + }, + "typescript": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/typescript.svg", + "upstream_sha256": "af103ea54f8ac748c4c785a8074d0ba13c71df614669af4739575ceb000f191d" + }, + "react": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/react.svg", + "upstream_sha256": "ef9d06d0487eac79e90d3c186fb73310231a331896482643ab33931c05073e5e" + }, + "html": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/html.svg", + "upstream_sha256": "96c58a9a1dd9467412383caaf94d1f2afdceca7ea3a86c0da799219482e14709" + }, + "css": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/css.svg", + "upstream_sha256": "710485c53da43d6ca2b24c653feb38e2fe8826437293c1db433e212e14c127fc" + }, + "python": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/python.svg", + "upstream_sha256": "366e9a8b7ef95ec16d876e893703f8aa2150935a4798a6f8e4ed3838bd8be7a1" + }, + "shell": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/shell.svg", + "upstream_sha256": "6451507061f339c16d7e04793bb2531245498dc1e2d8ede1c385337f1e847a2c" + }, + "config": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/config.svg", + "upstream_sha256": "217cf6c3ccc4e8b4bfb852541c39346f02e0697079175ec7302bc22a30bd59ca" + }, + "image": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/image.svg", + "upstream_sha256": "cc80f50862719e8873e28e7d02aa72f31fafe136b80edcdb2717a7d4e2200439" + }, + "svg": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/svg.svg", + "upstream_sha256": "1008d60478d5ee5c8b9ce557c589ecce69da48c899a94760c52ef5ea0b5b7555" + }, + "git": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/git.svg", + "upstream_sha256": "d489688dde724ee4ba28182ba21185ee9cd8524a6bab40bae72c82c5cafd9af1" + }, + "pdf": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/pdf.svg", + "upstream_sha256": "c1f3f09b2283f797f5e977cca244eba8e6d1ec50b3e7944f8d75348efed4a3c8" + }, + "zip": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/zip.svg", + "upstream_sha256": "ef76ed8cac7f1203def4fdd138037601d6b96272ac8b833ab91439ec582bd3ee" + }, + "db": { + "source": "https://raw.githubusercontent.com/jesseweed/seti-ui/2d6c5e68b4ded73c92dac291845ee44e1182d511/icons/db.svg", + "upstream_sha256": "12d620a9c1d8da4207867a9c595d0acb267f59e6b4dca2500b3ac8de26dcd28c" + } +} \ No newline at end of file diff --git a/app/public/modal-cat-v1.png b/app/public/modal-cat-v1.png new file mode 100644 index 0000000000000000000000000000000000000000..375f9a312a5ced0721801a840bb4037bb7a96e8e --- /dev/null +++ b/app/public/modal-cat-v1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a766512083268f7d7bb31f37171d6cd05a5af81e38c2612ac41cbb473a2c5f6c +size 513254 diff --git a/app/public/openbmb-avatar.webp b/app/public/openbmb-avatar.webp new file mode 100644 index 0000000000000000000000000000000000000000..0061a2ff05c560618714b7bbec6b5a8ccdaec051 Binary files /dev/null and b/app/public/openbmb-avatar.webp differ diff --git a/app/public/social-thumbnail-v3.png b/app/public/social-thumbnail-v3.png new file mode 100644 index 0000000000000000000000000000000000000000..208fe71953ff6f958df361b9ab00db51dd2c6b6c --- /dev/null +++ b/app/public/social-thumbnail-v3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eec706e1875b722ec2147a6edc0a0abc562d6f9a7a1158e356aad421a21ebb48 +size 2116362 diff --git a/app/scripts/licenses.mjs b/app/scripts/licenses.mjs new file mode 100644 index 0000000000000000000000000000000000000000..751577f5f7ce45739c6fc2be4359d337001f7991 --- /dev/null +++ b/app/scripts/licenses.mjs @@ -0,0 +1,27 @@ +import { readdir, readFile, mkdir, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +// Include dependency notices with the static distributable, without fetching +// anything at build time. Some upstream Pi packages omit a LICENSE file; +// their repository license is included in public/licenses/pi-LICENSE. +export async function collectLicenses() { + const notices = []; + async function scan(root) { + for (const entry of await readdir(root, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name.startsWith('.')) continue; + const directory = path.join(root, entry.name); + if (entry.name.startsWith('@')) { await scan(directory); continue; } + let pkg; + try { pkg = JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8')); } catch { continue; } + const texts = []; + for (const file of await readdir(directory, { withFileTypes: true })) { + if (file.isFile() && /^(licen[cs]e|copying|notice|thirdpartynotices)/i.test(file.name)) texts.push(await readFile(path.join(directory, file.name), 'utf8')); + } + notices.push(`${pkg.name}@${pkg.version} (${pkg.license ?? 'see upstream'})\n${texts.join('\n')}\n`); + } + } + await scan('node_modules'); + await mkdir('dist/licenses', { recursive: true }); + await writeFile('dist/licenses/dependencies.txt', notices.sort().join('\n----------------------------------------\n\n')); + await writeFile('dist/licenses/pi-components.json', await readFile('vendor/pi-coding-agent/provenance.json')); +} diff --git a/app/scripts/pi-browser.mjs b/app/scripts/pi-browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e8d3638f57521b182d0db32c36236e89675c59b5 --- /dev/null +++ b/app/scripts/pi-browser.mjs @@ -0,0 +1,34 @@ +import { resolve } from 'node:path'; +import { readFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; + +// Adapt host services at build time; never edit installed or vendored Pi code. +// Exact package pin + component checksums make this boundary reviewable. +export function piBrowser() { + const sourceRoot = resolve('vendor/pi-coding-agent'); + const provenance = JSON.parse(readFileSync(resolve(sourceRoot, 'provenance.json'), 'utf8')); + for (const [file, expected] of Object.entries(provenance.files)) { + const actual = createHash('sha256').update(readFileSync(resolve(sourceRoot, file))).digest('hex'); + if (actual !== expected) throw Error(`Vendored Pi component differs from its upstream checksum: ${file}`); + } + const host = resolve('src/pi/browser-host.mjs'); + return { + name: 'pi-browser-host', enforce: 'pre', + resolveId(source, importer = '') { + if (source === '@earendil-works/pi-tui') return resolve('src/pi/entry.mjs'); + if (importer.includes('/@earendil-works/pi-tui/')) { + if (source.endsWith('/terminal-image.js')) return resolve('src/pi/capabilities.mjs'); + if (source === 'node:perf_hooks') return host; + } + if (importer.includes('/vendor/pi-coding-agent/') && source === '../theme/theme.js') return resolve('src/pi/theme.mjs'); + }, + transform(code, id) { + if (!id.includes('/@earendil-works/pi-tui/') || !id.split('?')[0].endsWith('.js')) return; + // Browser timer IDs don't have Node's event-loop keepalive methods. + // Scrolling, selection autoscroll and flash timers still run normally. + let adapted = code.replace(/\.unref\(\)/g, '.unref?.()'); + if (/\b(?:process|Buffer)\./.test(code)) adapted = `import { browserProcess as process, Buffer } from ${JSON.stringify(host)};\n${adapted}`; + if (adapted !== code) return { code: adapted, map: null }; + }, + }; +} diff --git a/app/src/agent.worker.mjs b/app/src/agent.worker.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5c5abcf34c87b214b616e58e4876b505fe213ca5 --- /dev/null +++ b/app/src/agent.worker.mjs @@ -0,0 +1,102 @@ +import { Agent } from '@earendil-works/pi-agent-core'; +import { createInference, localModel } from './inference.mjs'; +import { createWorkspace, initialFiles, legacyProductsCsv, legacyProductsJson, legacyCostProductsJson, legacySalesCsv, legacyWorkspaceReadme, legacyProfitReadme } from './workspace.mjs'; +import { openStorage } from './storage.mjs'; +import { isModelCached } from './download.mjs'; + +const emit = data => postMessage(data); +const inference = createInference(emit); +let workspace, agent, storage, busy = false, operation, turnCount = 0; +const systemPrompt = `You are Pi, a coding assistant powered by MiniCPM5-2B, a language model from OpenBMB. +The model, inference, tools, and workspace run entirely in the user's browser. Workspace files are stored in this browser, not on the user's operating-system filesystem. +Use your tools to inspect and change actual files. Never claim a command ran or a file changed without a successful tool result. +When the user explicitly asks you to use a tool, call that tool even if you already know the answer. +Working directory: /workspace. Use read, write, edit, and bash. Keep tool calls and answers concise. +The bash tool supports cat, ls, find, grep, sed, awk, jq, sort, wc, printf, pipes, redirects, and shell scripts. +Use jq for JSON and awk for CSV and calculations; python, python3, node, npm, and native binaries are unavailable. +Use curl -fsS for HTTP requests to the hosts listed by the bash tool. To save a response, use curl -fsS URL -o file.json, then inspect it with jq or read. For pipelines use set -o pipefail so failed downloads are not mistaken for success. CORS and redirect errors are browser limitations: report them accurately; do not invent fetched content or repeatedly retry blocked requests. +You can create and edit text files, including HTML, CSS, JavaScript, and shell scripts. External URLs may be referenced without fetching them. Only claim an asset was fetched or tested after a successful tool result. HTTP requests send the requested URL and any explicit request data to that external server; model inference stays local. +Interpret short follow-ups using the conversation and inspect the relevant files when needed. +Inspect files before editing them. After changing files, verify the result with a tool. Finish with a short factual answer.`; + +async function snapshot() { return { version: 1, demoVersion: 4, files: await workspace.snapshot(), entries: await workspace.serialize(), messages: agent.state.messages }; } +async function persist() { + const state = await snapshot(); + try { await storage?.save(state); } catch (e) { emit({ type: 'persistence_error', error: 'Changes are in memory, but browser storage failed: ' + e.message }); } + emit({ type: 'workspace', files: state.files }); + return state; +} +const initialized = (async () => { + let saved; + try { storage = await openStorage(); saved = await storage.load(); } + catch (e) { emit({ type: 'persistence_error', error: 'Workspace saving is unavailable: ' + e.message }); } + workspace = createWorkspace(saved?.files, saved?.entries); + await workspace.ready; + const upgradeDemo = saved && (saved.demoVersion ?? 0) < 4; + if (upgradeDemo) { + // Move prices and quantities together only for a recognized untouched demo. + // Never remove a price column if its companion file was edited or deleted. + const paths = workspace.bash.fs.getAllPaths(); + const csv = '/workspace/products.csv', json = '/workspace/products.json', sales = '/workspace/sales.csv'; + const untouched = async (file, versions) => paths.includes(file) && (await workspace.bash.fs.lstat(file)).isFile && versions.includes(await workspace.read(file)); + if (await untouched(sales, [legacySalesCsv])) { + const oldJson = await untouched(json, [legacyProductsJson, legacyCostProductsJson]); + const oldCsv = !paths.includes(json) && await untouched(csv, [legacyProductsCsv]); + const originalDemo = (saved.demoVersion ?? 0) < 1 && !paths.includes(json) && !paths.includes(csv); + if (oldJson || oldCsv || originalDemo) { + await workspace.write(sales, initialFiles[sales]); + await workspace.write(json, initialFiles[json]); + if (oldCsv) await workspace.bash.fs.rm(csv); + } + } + const readme = '/workspace/README.md'; + if (await untouched(readme, [legacyWorkspaceReadme, legacyProfitReadme])) { + await workspace.write(readme, initialFiles[readme]); + } + } + agent = new Agent({ initialState: { model: localModel, thinkingLevel: 'medium', systemPrompt, tools: workspace.tools, messages: saved?.messages ?? [] }, + streamFn: inference.streamFn, toolExecution: 'sequential', + afterToolCall: ({ result, isError }) => ({ isError: isError || (result.details?.exitCode !== undefined && result.details.exitCode !== 0) }), + shouldStopAfterTurn: ({ toolResults }) => { + const stop = ++turnCount >= 12 && toolResults.length > 0; + if (stop) emit({ type: 'notice', text: 'Paused after 12 agent turns. Send a follow-up to continue.' }); + return stop; + }, + }); + agent.subscribe(async event => { + emit({ type: 'agent_event', event }); + if (event.type === 'tool_execution_end' || event.type === 'agent_end') await persist(); + }); + const state = await snapshot(); + if (upgradeDemo) { + try { await storage?.save(state); } + catch (e) { emit({ type: 'persistence_error', error: 'Changes are in memory, but browser storage failed: ' + e.message }); } + } + emit({ type: 'initialized', ...state }); +})(); + +onmessage = async ({ data }) => { + const { id, action, args = {} } = data; + const reply = value => emit({ type: 'reply', id, value }); + try { + await initialized; + if (action === 'stop') { operation?.abort(); agent.abort(); inference.stop(); return reply(true); } + if (action === 'snapshot') return reply(await snapshot()); + if (action === 'cache_status') return reply(await isModelCached()); + if (busy) throw Error('Wait for the current operation or stop it first.'); + busy = true; operation = new AbortController(); emit({ type: 'busy', action, cachedOnly: args.cachedOnly === true }); + try { + let value; + if (action === 'load') { await inference.load(args, operation.signal); value = inference.device; } + else if (action === 'prompt') { + turnCount = 0; await agent.prompt(args.text); value = await snapshot(); + } else if (action === 'shell') { + value = await workspace.bash.exec(args.command, { signal: operation.signal }); await persist(); + } else if (action === 'write') { await workspace.write(args.path, args.content); value = await persist(); } + else if (action === 'new_chat') { agent.reset(); value = await persist(); } + else if (action === 'read') value = await workspace.read(args.path); + else throw Error('Unknown action: ' + action); + reply(value); + } finally { busy = false; operation = undefined; emit({ type: 'idle' }); } + } catch (error) { emit({ type: 'reply', id, error: error?.name === 'AbortError' ? 'Stopped.' : String(error?.message ?? error), errorName: error?.name, errorCode: error?.code }); } +}; diff --git a/app/src/browser-http.mjs b/app/src/browser-http.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a9a282104154c6f2e109f6836a977e232a2b304f --- /dev/null +++ b/app/src/browser-http.mjs @@ -0,0 +1,67 @@ +// just-bash's curl/wget use this browser transport. There is no proxy/server. +export const HTTP_ORIGINS = Object.freeze([ + 'https://api.github.com', + 'https://raw.githubusercontent.com', + 'https://huggingface.co', + 'https://jsonplaceholder.typicode.com', + 'https://httpbin.org', +]); +export const HTTP_METHODS = Object.freeze(['GET', 'HEAD', 'POST']); +export const HTTP_LIMIT = 1024 * 1024; +export const HTTP_TIMEOUT = 8_000; + +export function createBrowserFetch({ transport = globalThis.fetch, origins = HTTP_ORIGINS, + timeoutMs = HTTP_TIMEOUT, maxBytes = HTTP_LIMIT } = {}) { + const allowed = new Set(origins); + return async (input, options = {}) => { + const url = new URL(input); + if (url.protocol !== 'https:' || !allowed.has(url.origin)) { + throw Error(`HTTP destination is not enabled in this experiment. Allowed hosts: ${[...allowed].map(x => new URL(x).host).join(', ')}.`); + } + if (url.username || url.password) throw Error('Credentials in URLs are unsupported. Use an explicit Authorization header if needed.'); + const method = (options.method ?? 'GET').toUpperCase(); + if (!HTTP_METHODS.includes(method)) throw Error(`HTTP method ${method} is not enabled. Use GET, HEAD, or POST.`); + const requestedTimeout = options.timeoutMs > 0 ? options.timeoutMs : timeoutMs; + const controller = new AbortController(); + const deadline = Math.min(requestedTimeout, timeoutMs); + const timer = setTimeout(() => controller.abort(new DOMException(`HTTP request timed out after ${deadline} ms.`, 'TimeoutError')), deadline); + const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal; + let reader; + try { + signal.throwIfAborted(); + const response = await transport(url.href, { method, headers: options.headers, + body: ['GET', 'HEAD'].includes(method) ? undefined : options.body, + mode: 'cors', credentials: 'omit', redirect: 'manual', referrerPolicy: 'no-referrer', signal }); + // Browsers hide both the Location header and status on manual redirects. + // Following automatically would skip the host check at intermediate hops. + if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400 && response.status !== 304)) { + throw Error('HTTP redirect cannot be followed safely in this browser shell. Use the final HTTPS URL directly (including exact capitalization).'); + } + if (response.status === 0 || response.type === 'opaque') throw Error('HTTP response is unreadable. The destination must allow browser access with CORS.'); + if (Number(response.headers.get('content-length')) > maxBytes) { + await response.body?.cancel(); + throw Error(`HTTP response exceeds the ${maxBytes}-byte limit.`); + } + const chunks = []; let size = 0; + if (response.body) { + reader = response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + signal.throwIfAborted(); + if (done) break; + size += value.byteLength; + if (size > maxBytes) { await reader.cancel(); throw Error(`HTTP response exceeds the ${maxBytes}-byte limit.`); } + chunks.push(value); + } + } + const body = new Uint8Array(size); let offset = 0; + for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; } + return { status: response.status, statusText: response.statusText, + headers: Object.fromEntries(response.headers.entries()), body, url: response.url || url.href }; + } catch (error) { + if (signal.aborted) throw signal.reason; + if (error instanceof TypeError) throw Error('HTTP request failed: the server may block browser requests (CORS), or the connection failed. No proxy is used.'); + throw error; + } finally { clearTimeout(timer); reader?.releaseLock(); } + }; +} diff --git a/app/src/cat-sound.mjs b/app/src/cat-sound.mjs new file mode 100644 index 0000000000000000000000000000000000000000..da939109bd60e34ca4d21ce800124f5b1759aa39 --- /dev/null +++ b/app/src/cat-sound.mjs @@ -0,0 +1,12 @@ +// Share one preloaded clip so rapid clicks replay it without stacking meows. +const meow = new Audio(new URL('../public/cat-meow-v1.mp3', import.meta.url).href); +meow.preload = 'auto'; +meow.volume = .65; + +export function playCatSound() { + // Call directly from the click handler so mobile browsers allow playback. + try { + meow.currentTime = 0; + void meow.play().catch(() => {}); + } catch { /* A failed audio download must not interrupt the cat interaction. */ } +} diff --git a/app/src/column-resizer.mjs b/app/src/column-resizer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..14c1739a5ccd7c6aae25e014379b2c2341ffc5bc --- /dev/null +++ b/app/src/column-resizer.mjs @@ -0,0 +1,84 @@ +const STORAGE_KEY = 'pi-column-ratio'; +const DEFAULT_RATIO = 1 / 1.83; + +export function createColumnResizer(layout, handle) { + const desktop = matchMedia('(min-width: 851px)'); + const style = getComputedStyle(layout); + const minimumChat = parseFloat(style.getPropertyValue('--conversation-min')); + const minimumWorkspace = parseFloat(style.getPropertyValue('--workspace-min')); + let ratio = DEFAULT_RATIO, drag, frame = 0; + try { + const saved = Number(localStorage.getItem(STORAGE_KEY)); + if (Number.isFinite(saved) && saved > 0 && saved < 1) ratio = saved; + } catch { /* The divider also works when browser storage is unavailable. */ } + + function apply() { + if (!desktop.matches) return; + const width = layout.getBoundingClientRect().width; + if (!width) return; + const chat = Math.max(minimumChat, Math.min(width - minimumWorkspace, width * ratio)); + layout.style.setProperty('--conversation-width', `${chat}px`); + const percent = Math.round(chat / width * 100); + handle.setAttribute('aria-valuemin', String(Math.round(minimumChat / width * 100))); + handle.setAttribute('aria-valuemax', String(Math.round((width - minimumWorkspace) / width * 100))); + handle.setAttribute('aria-valuenow', String(percent)); + handle.setAttribute('aria-valuetext', `Chat ${percent}%, workspace ${100 - percent}%`); + } + function save() { try { localStorage.setItem(STORAGE_KEY, String(ratio)); } catch {} } + function setWidth(pixels) { + const width = layout.getBoundingClientRect().width; + ratio = Math.max(minimumChat, Math.min(width - minimumWorkspace, pixels)) / width; + apply(); + } + function flushDrag() { + cancelAnimationFrame(frame); frame = 0; + if (drag) setWidth(drag.x - layout.getBoundingClientRect().left - drag.offset); + } + function finish(commit) { + if (!drag) return; + if (commit) flushDrag(); + else { cancelAnimationFrame(frame); frame = 0; ratio = drag.initialRatio; } + const pointer = drag.pointer; drag = undefined; + if (handle.hasPointerCapture(pointer)) handle.releasePointerCapture(pointer); + document.documentElement.classList.remove('is-resizing-columns'); + apply(); if (commit) save(); + } + function reset() { finish(false); ratio = DEFAULT_RATIO; apply(); save(); } + handle.addEventListener('pointerdown', event => { + if (!desktop.matches || event.button !== 0 || !event.isPrimary || drag) return; + event.preventDefault(); handle.focus({ preventScroll: true }); + const boundary = layout.querySelector('.conversation').getBoundingClientRect().right; + drag = { pointer: event.pointerId, initialRatio: ratio, x: event.clientX, offset: event.clientX - boundary }; + handle.setPointerCapture(event.pointerId); + document.documentElement.classList.add('is-resizing-columns'); + }); + handle.addEventListener('pointermove', event => { + if (!drag || event.pointerId !== drag.pointer) return; + drag.x = event.clientX; + if (!frame) frame = requestAnimationFrame(flushDrag); + }); + handle.addEventListener('pointerup', event => { + if (!drag || event.pointerId !== drag.pointer) return; + drag.x = event.clientX; finish(true); + }); + handle.addEventListener('pointercancel', () => finish(false)); + handle.addEventListener('lostpointercapture', () => finish(false)); + handle.addEventListener('dblclick', reset); + handle.addEventListener('keydown', event => { + if (!desktop.matches) return; + if (event.key === 'Escape' && drag) { event.preventDefault(); finish(false); return; } + if (!['ArrowLeft', 'ArrowRight', 'Home', 'End', 'Enter'].includes(event.key)) return; + event.preventDefault(); + if (event.key === 'Enter') { reset(); return; } + finish(false); + const width = layout.querySelector('.conversation').getBoundingClientRect().width; + const step = event.shiftKey ? 48 : 16; + setWidth(event.key === 'Home' ? 0 : event.key === 'End' ? Infinity : width + (event.key === 'ArrowLeft' ? -step : step)); + save(); + }); + window.addEventListener('blur', () => finish(false)); + desktop.addEventListener('change', () => { finish(false); apply(); }); + // Keep the preferred ratio on window resize, clamping only its displayed size. + new ResizeObserver(apply).observe(layout); + apply(); +} diff --git a/app/src/context-usage.mjs b/app/src/context-usage.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d80c05c25119bf40ce099d68597d457f5746d841 --- /dev/null +++ b/app/src/context-usage.mjs @@ -0,0 +1,16 @@ +export const CONTEXT_LIMIT = 8192; + +// Usage describes the latest model call, not unsent draft text or the full +// saved transcript (which can contain turns excluded from model context). +export function restoredContextUsage(messages) { + const last = messages.findLast(message => message.role === 'assistant' && message.usage?.input > 0); + if (last) return { inputTokens: last.usage.input, outputTokens: last.usage.output ?? 0 }; + return messages.length ? null : { inputTokens: 0, outputTokens: 0 }; +} + +export function contextLabel(usage) { + if (!usage) return `—/${CONTEXT_LIMIT.toLocaleString('en-US')} context`; + const used = usage.inputTokens + usage.outputTokens; + const remaining = Math.max(0, CONTEXT_LIMIT - used); + return `${used.toLocaleString('en-US')}/${CONTEXT_LIMIT.toLocaleString('en-US')} context · ${remaining.toLocaleString('en-US')} free`; +} diff --git a/app/src/download.mjs b/app/src/download.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f35a4f0d543d5c026cac42420823b137bfaa8964 --- /dev/null +++ b/app/src/download.mjs @@ -0,0 +1,144 @@ +import { createSHA256 } from 'hash-wasm'; +import manifest from './model-manifest.json'; + +export const REVISION = '04a6c49fcba3a65a0351c92644c3a7e9d4343059'; +export const MODEL_ID = 'Mike0021/MiniCPM5-2B-ONNX'; +export const MODEL_BYTES = Object.values(manifest.files).reduce((n, f) => n + f.bytes, 0); +const CHUNK = 32 * 1024 ** 2; +const sleep = (ms, signal) => new Promise((resolve, reject) => { + signal?.throwIfAborted(); + const abort = () => { clearTimeout(timer); reject(signal.reason); }; + const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, ms); + signal?.addEventListener('abort', abort, { once: true }); +}); + +async function fetchPart(url, start, end, total, signal) { + for (let attempt = 0; ; attempt++) { + try { + const part = total > CHUNK; + const response = await fetch(url, { headers: part ? { Range: `bytes=${start}-${end}` } : {}, + signal: AbortSignal.any([signal, AbortSignal.timeout(90_000)]), cache: 'no-store' }); + if (!response.ok) throw Error(`Download returned HTTP ${response.status}`); + if (part && response.status !== 206) { + await response.body?.cancel(); + throw Error('The model host did not honor byte ranges.'); + } + const range = response.headers.get('Content-Range'); + if (range && range !== `bytes ${start}-${end}/${total}`) { + await response.body?.cancel(); throw Error('Incorrect download range.'); + } + const data = new Uint8Array(await response.arrayBuffer()); + if (data.length !== end - start + 1) throw Error('Incomplete download chunk.'); + return data; + } catch (error) { + signal.throwIfAborted(); + if (attempt === 2) throw error; + await sleep(500 * 2 ** attempt, signal); + } + } +} + +export async function prepareModelCache(baseURL, options) { + if (navigator.locks) return navigator.locks.request('pi-minicpm5-download-' + REVISION, + { signal: options.signal }, () => downloadModel(baseURL, options)); + return downloadModel(baseURL, options); +} + +async function readCacheState(create = false) { + if (!navigator.storage?.getDirectory) throw Error('This app needs browser file storage (OPFS) to cache the 1.84 GB model. Open it in a regular browser tab.'); + const root = await (await navigator.storage.getDirectory()).getDirectoryHandle('pi-minicpm5-' + REVISION, { create }); + const receiptsFile = await root.getFileHandle('verified.json', { create }); + let receipts; + try { receipts = JSON.parse(await (await receiptsFile.getFile()).text()); } catch { receipts = {}; } + if (!receipts || typeof receipts !== 'object' || Array.isArray(receipts)) receipts = {}; + let cached = 0; + const pending = []; + const key = file => encodeURIComponent(file); + for (const [file, spec] of Object.entries(manifest.files)) { + try { + const stored = await (await root.getFileHandle(key(file))).getFile(); + const receipt = receipts[file]; + if (stored.size === spec.bytes && receipt?.sha256 === spec.sha256 && receipt.modified === stored.lastModified) { + cached += spec.bytes; continue; + } + } catch (e) { if (e.name !== 'NotFoundError') throw e; } + pending.push([file, spec]); + } + return { root, receiptsFile, receipts, pending, cached }; +} + +export async function isModelCached() { + try { return (await readCacheState()).pending.length === 0; } + catch { return false; } +} + +function cacheMiss() { + return Object.assign(Error('The saved model is incomplete. Confirm the download to restore it.'), { code: 'MODEL_CACHE_MISS' }); +} + +async function downloadModel(baseURL, { signal, cachedOnly = false, onProgress = () => {} }) { + let state; + try { state = await readCacheState(!cachedOnly); } + catch (error) { if (cachedOnly && error.name === 'NotFoundError') throw cacheMiss(); throw error; } + const { root, receiptsFile, receipts, pending, cached } = state; + // Recheck under the download lock: another tab or eviction may have changed + // the cache after the UI checked it. Automatic restores never fetch weights. + if (cachedOnly && pending.length) throw cacheMiss(); + let completed = cached; + const key = file => encodeURIComponent(file); + onProgress({ phase: 'download', loaded: completed, total: MODEL_BYTES, cached }); + if (pending.length) { + const estimate = await navigator.storage.estimate(); + if (estimate.quota && estimate.quota - estimate.usage < MODEL_BYTES - completed + CHUNK) { + throw Error('Not enough browser storage for the model. Free at least 2 GB and retry.'); + } + } + const controller = new AbortController(); + const combined = AbortSignal.any([signal, controller.signal]); + let receiptWrites = Promise.resolve(); + const saveReceipts = () => { + const serialized = JSON.stringify(receipts); + const write = receiptWrites.then(async () => { + const stream = await receiptsFile.createWritable(); await stream.write(serialized); await stream.close(); + }); + receiptWrites = write.catch(() => {}); return write; + }; + async function worker() { + while (pending.length) { + combined.throwIfAborted(); + const [file, spec] = pending.shift(); + const handle = await root.getFileHandle(key(file), { create: true }); + const output = await handle.createWritable(); + try { + const hash = await createSHA256(); hash.init(); + for (let start = 0; start < spec.bytes; start += CHUNK) { + const end = Math.min(start + CHUNK, spec.bytes) - 1; + const data = await fetchPart(baseURL + file, start, end, spec.bytes, combined); + combined.throwIfAborted(); + hash.update(data); await output.write(data); completed += data.length; + onProgress({ phase: 'download', file, loaded: completed, total: MODEL_BYTES, cached }); + } + if (hash.digest('hex') !== spec.sha256) throw Error('SHA-256 verification failed: ' + file); + await output.close(); + receipts[file] = { sha256: spec.sha256, modified: (await handle.getFile()).lastModified }; + await saveReceipts(); + } catch (error) { await output.abort().catch(() => {}); controller.abort(error); throw error; } + } + } + const outcomes = await Promise.allSettled(Array.from({ length: 6 }, worker)); + const failed = outcomes.find(r => r.status === 'rejected'); + if (failed) throw failed.reason; + await receiptWrites; + return { + cachedBytes: cached, + async match(request) { + const url = typeof request === 'string' ? request : request.url; + if (!url.startsWith(baseURL)) return undefined; + const file = url.slice(baseURL.length); + if (!Object.hasOwn(manifest.files, file)) return undefined; + const stored = await (await root.getFileHandle(key(file))).getFile(); + return new Response(stored, { headers: { 'Content-Length': String(stored.size) } }); + }, + async put() { /* All supported files are already downloaded and verified. */ }, + }; +} diff --git a/app/src/editor-highlight.worker.mjs b/app/src/editor-highlight.worker.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8730871b8405e8d439536f0a8735e3fbbc70efeb --- /dev/null +++ b/app/src/editor-highlight.worker.mjs @@ -0,0 +1,39 @@ +import './prism-worker-setup.mjs'; +import Prism from 'prismjs/components/prism-core.js'; +import 'prismjs/components/prism-markup.js'; +import 'prismjs/components/prism-css.js'; +import 'prismjs/components/prism-clike.js'; +import 'prismjs/components/prism-javascript.js'; +import 'prismjs/components/prism-typescript.js'; +import 'prismjs/components/prism-jsx.js'; +import 'prismjs/components/prism-tsx.js'; +import 'prismjs/components/prism-json.js'; +import 'prismjs/components/prism-yaml.js'; +import 'prismjs/components/prism-markdown.js'; +import 'prismjs/components/prism-python.js'; +import 'prismjs/components/prism-bash.js'; +import 'prismjs/components/prism-toml.js'; +import 'prismjs/components/prism-sql.js'; +import 'prismjs/components/prism-csv.js'; +import 'prismjs/components/prism-c.js'; +import 'prismjs/components/prism-cpp.js'; +import 'prismjs/components/prism-csharp.js'; +import 'prismjs/components/prism-java.js'; +import 'prismjs/components/prism-go.js'; +import 'prismjs/components/prism-rust.js'; +import 'prismjs/components/prism-diff.js'; +import 'prismjs/components/prism-docker.js'; +import { canHighlight } from './editor-language.mjs'; + +Prism.manual = true; +self.onmessage = ({ data: { id, text, language } }) => { + let html = null; + try { + if (canHighlight(text) && Prism.languages[language]) { + const highlighted = Prism.highlight(text, Prism.languages[language], language); + // Avoid building a huge DOM even for short, unusually token-dense files. + if (highlighted.length < 1_000_000 && (highlighted.match(/ 200_000) return false; + let lines = 1; + for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10 && ++lines > 5000) return false; + return true; +} diff --git a/app/src/editor-ui.mjs b/app/src/editor-ui.mjs new file mode 100644 index 0000000000000000000000000000000000000000..238a5f63c1e3fa952ba6cb90c86720716a70813c --- /dev/null +++ b/app/src/editor-ui.mjs @@ -0,0 +1,66 @@ +import { canHighlight, editorLanguage } from './editor-language.mjs'; + +export function createEditorUI(element) { + const input = element.querySelector('#editor'), highlight = element.querySelector('#editor-highlight'); + let path = '', revision = 0, timer, watchdog, worker, active = false, composing = false, queued; + + function syncScroll() { + // Match the textarea's actual viewport, excluding either native scrollbar. + highlight.style.width = input.clientWidth + 'px'; + highlight.style.height = input.clientHeight + 'px'; + highlight.scrollTop = input.scrollTop; + highlight.scrollLeft = input.scrollLeft; + } + function plain() { element.classList.remove('is-highlighted'); } + function stopWorker() { + clearTimeout(watchdog); + worker?.terminate(); worker = undefined; active = false; + } + function send() { + if (active || !queued) return; + const job = queued; queued = undefined; + try { + if (!worker) { + worker = new Worker(new URL('./editor-highlight.worker.mjs', import.meta.url), { type: 'module' }); + worker.onmessage = ({ data }) => { + clearTimeout(watchdog); active = false; + if (data.id === revision && data.html !== null) { + // Prism escapes file contents before adding its own token spans. + highlight.innerHTML = data.html + '\n'; + syncScroll(); element.classList.add('is-highlighted'); + } + send(); + }; + worker.onerror = () => { stopWorker(); queued = undefined; }; + } + active = true; + worker.postMessage(job); + // A pathological regex can only occupy this worker, and is terminated. + watchdog = setTimeout(() => { stopWorker(); send(); }, 1500); + } catch { stopWorker(); } + } + function refresh(delay = 0) { + revision++; clearTimeout(timer); queued = undefined; plain(); + const language = editorLanguage(path), text = input.value; + element.dataset.language = language ?? 'plain'; + if (composing || !text || !language || !canHighlight(text)) return; + const id = revision; + timer = setTimeout(() => { queued = { id, text, language }; send(); }, delay); + } + input.addEventListener('input', () => refresh(80)); + input.addEventListener('compositionstart', () => { composing = true; refresh(); }); + input.addEventListener('compositionend', () => { composing = false; refresh(80); }); + input.addEventListener('scroll', syncScroll, { passive: true }); + const resize = new ResizeObserver(syncScroll); resize.observe(input); + return { + setFile(nextPath, text) { + if (path === nextPath && input.value === text) return; + const changed = path !== nextPath; + path = nextPath; + if (input.value !== text) input.value = text; + if (changed) { input.scrollTop = 0; input.scrollLeft = 0; } + refresh(); + }, + dispose() { clearTimeout(timer); stopWorker(); resize.disconnect(); }, + }; +} diff --git a/app/src/file-icons.mjs b/app/src/file-icons.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9562a17c13b4116b55378b21ef36f876291e5ebc --- /dev/null +++ b/app/src/file-icons.mjs @@ -0,0 +1,29 @@ +const types = { + default: '#b0b0bd', markdown: '#519aba', csv: '#8dc149', json: '#cbcb41', + javascript: '#cbcb41', typescript: '#519aba', react: '#519aba', html: '#e37933', + css: '#519aba', python: '#519aba', shell: '#8dc149', config: '#b0b0bd', + image: '#a074c4', svg: '#a074c4', git: '#e37933', pdf: '#cc3e44', zip: '#b0b0bd', db: '#cbcb41', +}; +const extensions = { + md: 'markdown', markdown: 'markdown', mdx: 'markdown', csv: 'csv', tsv: 'csv', + json: 'json', jsonc: 'json', jsonl: 'json', js: 'javascript', mjs: 'javascript', cjs: 'javascript', + ts: 'typescript', mts: 'typescript', cts: 'typescript', jsx: 'react', tsx: 'react', + html: 'html', htm: 'html', xml: 'html', css: 'css', scss: 'css', sass: 'css', less: 'css', + py: 'python', pyi: 'python', sh: 'shell', bash: 'shell', zsh: 'shell', fish: 'shell', + yaml: 'config', yml: 'config', toml: 'config', ini: 'config', conf: 'config', env: 'config', + png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', webp: 'image', avif: 'image', ico: 'image', svg: 'svg', + pdf: 'pdf', zip: 'zip', gz: 'zip', tar: 'zip', sql: 'db', sqlite: 'db', db: 'db', +}; +export function fileIconType(path) { + const name = path.split('/').at(-1).toLowerCase(); + if (['.gitignore', '.gitattributes', '.gitmodules'].includes(name)) return 'git'; + if (name === '.env' || name.startsWith('.env.') || name === '.editorconfig') return 'config'; + return extensions[name.split('.').at(-1)] ?? 'default'; +} +export function createFileIcon(path) { + const kind = fileIconType(path), icon = document.createElement('span'); + icon.className = 'file-icon'; icon.dataset.kind = kind; icon.setAttribute('aria-hidden', 'true'); + icon.style.setProperty('--file-color', types[kind]); + icon.style.setProperty('--file-icon', `url("${new URL(`file-icons/${kind}.svg`, document.baseURI).href}")`); + return icon; +} diff --git a/app/src/inference.mjs b/app/src/inference.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7a99f226031b00d90be0b8b8b5d81e24b14456bc --- /dev/null +++ b/app/src/inference.mjs @@ -0,0 +1,188 @@ +import { AutoTokenizer, AutoModelForCausalLM, TextStreamer, InterruptableStoppingCriteria, env } from '@huggingface/transformers'; +import { AssistantMessageEventStream } from '@earendil-works/pi-ai/utils/event-stream'; +import { prepareModelCache, MODEL_ID, REVISION } from './download.mjs'; +import { fitContext, parseCompletion, splitThinking } from './protocol.mjs'; +import { CONTEXT_LIMIT } from './context-usage.mjs'; +import { nucleusProcessor } from './sampling.mjs'; +import { TokenRateWindow } from './token-rate.mjs'; + +const MAX_OUTPUT_TOKENS = 2048; + +export const localModel = { id: MODEL_ID, name: 'MiniCPM5-2B · q4f16', api: 'minicpm-webgpu', + provider: 'browser', baseUrl: '', reasoning: true, input: ['text'], + contextWindow: CONTEXT_LIMIT, maxTokens: MAX_OUTPUT_TOKENS, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }; + +export function createInference(notify) { + let model, tokenizer, device, loadPromise; + const stopping = new InterruptableStoppingCriteria(); + async function load({ runtimeURL, local = false, origin, limit128 = false, cachedOnly = false }, signal) { + if (model) return; + if (loadPromise) return loadPromise; + loadPromise = (async () => { + const adapter = await navigator.gpu?.requestAdapter({ powerPreference: 'high-performance' }); + if (!adapter) throw Error('WebGPU is unavailable. Try an up-to-date browser with GPU acceleration enabled.'); + if (!adapter.features.has('shader-f16')) throw Error('This model requires WebGPU shader-f16 support on your device.'); + if (limit128) { + const requestDevice = GPUAdapter.prototype.requestDevice; + GPUAdapter.prototype.requestDevice = function (descriptor = {}) { + return requestDevice.call(this, { ...descriptor, requiredLimits: { ...descriptor.requiredLimits, + maxStorageBufferBindingSize: 128 * 1024 ** 2, maxBufferSize: 256 * 1024 ** 2 } }); + }; + } + device = { vendor: adapter.info.vendor, architecture: adapter.info.architecture, + maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize, features: [...adapter.features] }; + notify({ type: 'device', device }); + const allowedLocal = local && ['localhost', '127.0.0.1'].includes(new URL(origin).hostname); + env.allowRemoteModels = true; env.allowLocalModels = false; + env.remoteHost = allowedLocal ? origin + '/' : 'https://huggingface.co/'; + env.remotePathTemplate = allowedLocal ? 'models/{model}/' : `{model}/resolve/${REVISION}/`; + const name = allowedLocal ? 'minicpm5-webgpu' : MODEL_ID; + const baseURL = env.remoteHost + env.remotePathTemplate.replace('{model}', name); + env.customCache = await prepareModelCache(baseURL, { signal, cachedOnly, onProgress: p => notify({ type: 'load_progress', ...p }) }); + env.useCustomCache = true; env.useBrowserCache = false; + env.backends.onnx.wasm.wasmPaths = runtimeURL; env.backends.onnx.wasm.numThreads = 1; + signal.throwIfAborted(); + notify({ type: 'load_progress', phase: 'compile' }); + [tokenizer, model] = await Promise.all([ + AutoTokenizer.from_pretrained(name), + AutoModelForCausalLM.from_pretrained(name, { device: 'webgpu', dtype: 'q4f16' }), + ]); + signal.throwIfAborted(); + notify({ type: 'load_progress', phase: 'warmup' }); + const input = tokenizer('Hello'); + await model.generate({ ...input, max_new_tokens: 1, do_sample: false, top_k: 0 }); + signal.throwIfAborted(); + const gpu = env.backends.onnx.webgpu.device; + device.actualLimits = { maxStorageBufferBindingSize: gpu?.limits.maxStorageBufferBindingSize, maxBufferSize: gpu?.limits.maxBufferSize }; + gpu?.lost.then(info => { if (info.reason !== 'destroyed') notify({ type: 'fatal', error: 'GPU device was lost. Reload this page to reload the cached model.' }); }); + notify({ type: 'loaded', device, cachedBytes: env.customCache.cachedBytes }); + })().catch(async error => { + await model?.dispose().catch(() => {}); model = undefined; tokenizer = undefined; + if (signal.aborted) throw new DOMException('Stopped.', 'AbortError'); + throw error; + }).finally(() => { loadPromise = undefined; }); + return loadPromise; + } + + function streamFn(piModel, context, options = {}) { + const stream = new AssistantMessageEventStream(); + const message = { role: 'assistant', api: piModel.api, provider: piModel.provider, model: piModel.id, + timestamp: Date.now(), content: [], + usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }; + void (async () => { + const abort = () => stopping.interrupt(); + const tokenRate = new TokenRateWindow(); + let rateTimer; + let lastUsageUpdate = 0; + const publishUsage = (force = false) => { + const now = performance.now(); + if (!force && now - lastUsageUpdate < 80) return; + lastUsageUpdate = now; + notify({ type: 'context_usage', inputTokens: message.usage.input, outputTokens: message.usage.output }); + }; + try { + if (!model) throw Error('Load the model first.'); + stopping.reset(); options.signal?.throwIfAborted(); + options.signal?.addEventListener('abort', abort, { once: true }); + notify({ type: 'inference_activity', phase: 'prefill' }); + const maxTokens = Math.min(options.maxTokens ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS); + const tools = context.tools ?? []; + const templateTools = tools.map(t => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } })); + const { inputs, dropped } = fitContext(context, messages => tokenizer.apply_chat_template(messages, { + tools: templateTools, enable_thinking: true, add_generation_prompt: true, return_dict: true, + }), CONTEXT_LIMIT - maxTokens); + if (dropped) notify({ type: 'context_trim', dropped }); + message.usage.input = inputs.input_ids.dims[1]; + message.usage.totalTokens = message.usage.input; + publishUsage(true); + stream.push({ type: 'start', partial: structuredClone(message) }); + let raw = '', visible = '', started = false, thought = '', thinkingStarted = false, thinkingEnded = false; + let textIndex = 0; + const start = performance.now(); let firstTokenMs; + const streamer = new TextStreamer(tokenizer, { skip_prompt: true, skip_special_tokens: false, + token_callback_function: tokens => { + if (!tokens.length) return; + const now = performance.now(); + firstTokenMs ??= now - start; + tokenRate.add(tokens.length, now); + if (rateTimer === undefined) { + notify({ type: 'inference_activity', phase: 'decode', rate: null, outputTokens: tokenRate.total }); + rateTimer = setInterval(() => notify({ type: 'inference_activity', phase: 'decode', rate: tokenRate.rate(performance.now()), outputTokens: tokenRate.total }), 250); + } + message.usage.output += tokens.length; + message.usage.totalTokens = message.usage.input + message.usage.output; + publishUsage(); + }, + callback_function: delta => { + raw += delta; + // The prompt already ends in \n. Generated text starts + // inside reasoning, so looking only for an opening tag is wrong. + const parts = splitThinking(raw, { thinkingPrefilled: true }); + const nextThought = parts.complete ? parts.thinking : parts.thinking.slice(0, Math.max(0, parts.thinking.length - 8)); + if (nextThought.length > thought.length) { + if (!thinkingStarted) { + message.content = [{ type: 'thinking', thinking: '' }]; + stream.push({ type: 'thinking_start', contentIndex: 0, partial: structuredClone(message) }); + thinkingStarted = true; textIndex = 1; + } + message.content[0].thinking = nextThought; + stream.push({ type: 'thinking_delta', contentIndex: 0, delta: nextThought.slice(thought.length), partial: structuredClone(message) }); + thought = nextThought; + } + if (!parts.complete) return; + if (thinkingStarted && !thinkingEnded) { + stream.push({ type: 'thinking_end', contentIndex: 0, content: thought, partial: structuredClone(message) }); + thinkingEnded = true; + } + // Hold possible tags until completion. Tool XML is shown by tool events. + const safe = parts.answer.split('<')[0]; + if (safe.length <= visible.length) return; + if (!started) { message.content.push({ type: 'text', text: '' }); stream.push({ type: 'text_start', contentIndex: textIndex, partial: structuredClone(message) }); started = true; } + message.content[textIndex].text = safe; + stream.push({ type: 'text_delta', contentIndex: textIndex, delta: safe.slice(visible.length), partial: structuredClone(message) }); + visible = safe; + }, + }); + const output = await model.generate({ ...inputs, max_new_tokens: maxTokens, + do_sample: true, temperature: 1.0, top_p: 0.95, top_k: 0, repetition_penalty: 1.0, + logits_processor: [nucleusProcessor(0.95)], + eos_token_id: [1, 130073], streamer, stopping_criteria: stopping }); + const ids = output.tolist()[0].slice(inputs.input_ids.dims[1]).map(Number); + message.usage.output = ids.length; message.usage.totalTokens = message.usage.input + ids.length; + publishUsage(true); + options.signal?.throwIfAborted(); + raw = tokenizer.decode(ids, { skip_special_tokens: false }); + const content = parseCompletion(raw, tools, { thinkingPrefilled: true }); + if (started) stream.push({ type: 'text_end', contentIndex: textIndex, content: visible, partial: structuredClone(message) }); + message.content = content; + const hasTools = content.some(c => c.type === 'toolCall'); + // Never execute even a complete prefix of a truncated tool response. + const ended = [1, 130073].includes(ids.at(-1)); + if (hasTools && !ended) throw Error('The tool response exceeded the output limit. No tool was executed. Try a smaller edit.'); + message.stopReason = hasTools ? 'toolUse' : ended ? 'stop' : 'length'; + for (const [index, block] of content.entries()) { + if (block.type !== 'toolCall') continue; + stream.push({ type: 'toolcall_start', contentIndex: index, partial: structuredClone(message) }); + stream.push({ type: 'toolcall_end', contentIndex: index, toolCall: block, partial: structuredClone(message) }); + } + notify({ type: 'generation', raw, thinking: true, sampling: { temperature: 1, topP: 0.95, topK: 0, minP: 0, repetitionPenalty: 1 }, + inputTokens: message.usage.input, outputTokens: ids.length, + elapsedMs: performance.now() - start, firstTokenMs, stopReason: message.stopReason }); + stream.push({ type: 'done', reason: message.stopReason, message }); stream.end(message); + } catch (error) { + if (message.usage.input) publishUsage(true); + message.content = message.content.filter(c => c.type !== 'toolCall'); + message.stopReason = options.signal?.aborted ? 'aborted' : 'error'; + message.errorMessage = options.signal?.aborted ? 'Stopped.' : String(error.message ?? error); + stream.push({ type: 'error', reason: message.stopReason, error: message }); stream.end(message); + } finally { + clearInterval(rateTimer); + notify({ type: 'inference_activity', phase: 'end' }); + options.signal?.removeEventListener('abort', abort); + } + })(); + return stream; + } + return { load, streamFn, stop: () => stopping.interrupt(), get device() { return device; } }; +} diff --git a/app/src/load-dialog.mjs b/app/src/load-dialog.mjs new file mode 100644 index 0000000000000000000000000000000000000000..40d0ebb75f4fbf6e7fb16b27c22e39b65ec6a68a --- /dev/null +++ b/app/src/load-dialog.mjs @@ -0,0 +1,72 @@ +import { playCatSound } from './cat-sound.mjs'; + +// Native modal dialog provides focus trapping, background inertness and Escape. +export function createLoadDialog(dialog, { onClose }) { + const find = selector => dialog.querySelector(selector); + const confirm = find('#model-confirm'), cancel = find('#model-cancel'); + const error = find('#model-error'); + const cat = find('.setup-cat img'); + const figure = cat.parentElement, tail = find('.setup-cat-tail'); + const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)'); + let tailReaction; + function stopCatReaction() { tailReaction?.cancel(); tailReaction = undefined; } + figure.onpointerdown = event => event.preventDefault(); + figure.onmousedown = event => event.preventDefault(); + figure.onclick = () => { + playCatSound(); + if (!dialog.open || document.hidden || reducedMotion.matches || !figure.classList.contains('is-ready')) return; + const pose = getComputedStyle(tail).transform; + stopCatReaction(); + // Restart the idle rest period so it meets the click animation at neutral. + const idle = tail.getAnimations().find(animation => animation.animationName === 'setup-tail-swish'); + if (idle) idle.currentTime = 0; + tailReaction = tail.animate([ + { transform: pose }, + { transform: 'rotate(-7deg)', offset: .3 }, + { transform: 'rotate(4deg)', offset: .6 }, + { transform: 'rotate(-1deg)', offset: .82 }, + { transform: 'rotate(0deg)' }, + ], { id: 'cat-tail-reaction', duration: 1200, easing: 'ease-in-out' }); + tailReaction.onfinish = () => { tailReaction = undefined; }; + }; + dialog.addEventListener('close', stopCatReaction); + // The HTML preloads the sprite; decode it now, including on a warm cache hit. + // A slow or failed image must never hold up model setup. + void cat.decode().then(() => { + // Both layers reuse the decoded, preloaded sprite; no second asset download. + cat.parentElement.style.setProperty('--cat-sprite', `url("${cat.currentSrc || cat.src}")`); + cat.parentElement.classList.add('is-ready'); + }).catch(() => {}); + const syncCatMotion = () => { + dialog.style.setProperty('--cat-play-state', document.hidden ? 'paused' : 'running'); + if (document.hidden || reducedMotion.matches) stopCatReaction(); + }; + document.addEventListener('visibilitychange', syncCatMotion); + reducedMotion.addEventListener('change', syncCatMotion); + syncCatMotion(); + let resolveRequest; + function finish(send) { + if (!resolveRequest) return; + stopCatReaction(); + const resolve = resolveRequest; resolveRequest = undefined; + dialog.close(); onClose(); resolve(send); + } + cancel.onclick = () => finish(false); + dialog.addEventListener('cancel', event => { event.preventDefault(); finish(false); }); + confirm.onclick = () => finish(true); + return { + request(text, { errorMessage } = {}) { + if (resolveRequest) throw Error('Finish the current model setup before sending another message.'); + confirm.textContent = errorMessage ? 'Try again' : 'Load model & send'; + find('#model-title').textContent = errorMessage ? 'Load model' : 'Download model weights'; + find('#model-preview').textContent = text; + error.textContent = errorMessage ?? ''; error.hidden = !errorMessage; + const storageLink = document.querySelector('#open-tab'); + find('#model-open-tab').hidden = !errorMessage || storageLink.hidden; + find('#model-open-tab').href = storageLink.href; + const request = new Promise(resolve => { resolveRequest = resolve; }); + dialog.showModal(); find('.setup-body').scrollTop = 0; confirm.focus(); + return request; + }, + }; +} diff --git a/app/src/main.mjs b/app/src/main.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ce1c5075f921b50a868921b9e224569fd06cc2e8 --- /dev/null +++ b/app/src/main.mjs @@ -0,0 +1,254 @@ +import './style.css'; +import { createTerminalUI } from './pi/terminal-ui.mjs'; +import { createLoadDialog } from './load-dialog.mjs'; +import { createShellUI } from './shell-ui.mjs'; +import { restoredContextUsage } from './context-usage.mjs'; +import { createRuntimeMeter } from './runtime-meter.mjs'; +import { createFileIcon } from './file-icons.mjs'; +import { createEditorUI } from './editor-ui.mjs'; +import { createColumnResizer } from './column-resizer.mjs'; + +const $ = selector => document.querySelector(selector); +createColumnResizer($('main'), $('#column-resizer')); +const worker = new Worker(new URL('./agent.worker.mjs', import.meta.url), { type: 'module' }); +const pending = new Map(); +let nextId = 1, busy = false, loaded = false, selected, dirty = false, files = {}, messages = [], readyResolve; +let pendingReadPath; +const ready = new Promise(resolve => { readyResolve = resolve; }); +const diagnostics = { events: [], generations: [], runtimeSamples: [], device: null, contextUsage: restoredContextUsage([]) }; +const runtimeMeter = createRuntimeMeter($('#runtime-meter')); +const editorUI = createEditorUI($('.editor-input')); +const terminalUI = createTerminalUI($('#pi-terminal'), { + onInput: text => $('#send').classList.toggle('has-input', Boolean(text.trim())), + load: () => ready.then(load), prompt: text => ready.then(() => prompt(text)), + newChat: () => ready.then(newChat), stop: () => rpc('stop'), + shell: command => { if (dirty) throw Error('Save your file edits before running commands.'); return rpc('shell', { command }); }, +}); +const loadDialog = createLoadDialog($('#model-dialog'), { onClose: () => terminalUI.focus() }); +const shellUI = createShellUI($('.workspace > .terminal'), { run: async command => { + await ready; + if (dirty) throw Error('Save your file edits before running commands.'); + if (busy) throw Error('Wait for Pi to finish or stop the current task first.'); + return rpc('shell', { command }); +} }); +function rpc(action, args) { + return new Promise((resolve, reject) => { + const id = nextId++; pending.set(id, { resolve, reject }); worker.postMessage({ id, action, args }); + }); +} +function notice(text) { $('#notice').textContent = text; $('#notice').hidden = !text; } +function storageHelp(error) { + if (window.self === window.top || !/denied|storage directory access/i.test(error)) return error; + $('#open-tab').href = location.href; + $('#open-tab').hidden = false; + return 'Your browser blocked storage in this embedded app. Open the workspace in a new tab to load the model and save files.'; +} +function controls() { + $('#load').disabled = busy || loaded; + $('#load').classList.toggle('is-loaded', loaded); + if (loaded) $('#load').textContent = 'Loaded'; + else if (!busy) $('#load').textContent = 'Load model'; + $('#load').title = $('#load-status').textContent + ' ' + $('#load-detail').textContent; + $('#send').disabled = busy; + $('#newline').disabled = busy; + terminalUI.setState({ busy, loaded, activity: $('#activity').textContent }); + $('#stop').hidden = !busy; + for (const id of ['#new-chat', '#add-file', '#upload']) $(id).disabled = busy; + shellUI.setBusy(busy); + $('#save').disabled = busy || !selected || !dirty; + $('#editor').disabled = busy || !selected; +} +function renderFiles() { + terminalUI.setFiles(files); + $('#files').replaceChildren(); + for (const file of Object.keys(files).sort()) { + const button = document.createElement('button'), label = document.createElement('span'); + label.className = 'file-name'; label.textContent = file.replace(/^\/workspace\//, ''); + button.append(createFileIcon(file), label); + button.title = file; button.classList.toggle('selected', file === selected); + button.onclick = () => selectFile(file); $('#files').append(button); + } + if (selected && !dirty) editorUI.setFile(selected, files[selected] ?? ''); +} +function selectFile(file) { + pendingReadPath = undefined; + if (dirty) { notice('Save the open file before selecting another file.'); return; } + selected = file; $('#filename').textContent = file; + $('#filetype').replaceChildren(createFileIcon(file)); + renderFiles(); controls(); +} +function followReadFile() { + if (dirty) { pendingReadPath = undefined; return; } + if (!pendingReadPath || !Object.hasOwn(files, pendingReadPath)) return; + const file = pendingReadPath, changed = file !== selected; + selectFile(file); + if (changed) { $('#editor').scrollTop = 0; $('#editor').scrollLeft = 0; } + // Reveal the highlighted row inside the file list, without scrolling the + // page away from the conversation on narrow screens or moving focus. + const row = [...$('#files').children].find(button => button.title === file); + if (row) { + const bounds = row.getBoundingClientRect(), list = $('#files').getBoundingClientRect(); + if (bounds.top < list.top) $('#files').scrollTop += bounds.top - list.top; + else if (bounds.bottom > list.bottom) $('#files').scrollTop += bounds.bottom - list.bottom; + } +} +function renderMessages() { terminalUI.setMessages(messages); } +function updateContextUsage(usage) { + diagnostics.contextUsage = usage; + terminalUI.setState({ contextUsage: usage }); +} +worker.onmessage = ({ data }) => { + runtimeMeter.update(data); + if (data.type === 'inference_activity') { + diagnostics.runtimeSamples.push(data); + if (diagnostics.runtimeSamples.length > 160) diagnostics.runtimeSamples.shift(); + } + if (data.type === 'reply') { + const request = pending.get(data.id); pending.delete(data.id); + if (data.error) request?.reject(Object.assign(Error(data.error), { name: data.errorName || 'Error', code: data.errorCode })); else request?.resolve(data.value); + } else if (data.type === 'initialized') { + files = data.files; messages = data.messages; renderFiles(); renderMessages(); + updateContextUsage(restoredContextUsage(messages)); + if (files['/workspace/README.md']) selectFile('/workspace/README.md'); + // Do not steal focus if the user chose another control during startup. + if (document.activeElement === document.body) terminalUI.focus(); + readyResolve(); + } else if (data.type === 'busy') { + if (data.action === 'load') $('#load').textContent = 'Loading…'; + busy = true; $('#activity').textContent = data.action === 'prompt' ? 'Pi is working…' : data.action === 'load' ? (data.cachedOnly ? 'Loading local model…' : 'Loading model…') : 'Working…'; controls(); + } else if (data.type === 'idle') { + busy = false; $('#progress').hidden = true; $('#activity').textContent = loaded ? 'Ready · running on your device' : 'Files and chat are saved on this device.'; controls(); + } else if (data.type === 'workspace') { files = data.files; renderFiles(); followReadFile(); } + else if (data.type === 'device') { diagnostics.device = data.device; } + else if (data.type === 'load_progress') { + $('#progress').hidden = false; + if (data.phase === 'download') { + $('#progress').hidden = false; $('#progress').value = data.loaded / data.total * 100; + $('#load-status').textContent = data.loaded === data.total ? 'Download verified. Preparing model…' : 'Downloading model weights from Hugging Face…'; + $('#load-detail').textContent = `${(data.loaded / 1e9).toFixed(2)} / ${(data.total / 1e9).toFixed(2)} GB · ${Math.round(data.loaded / data.total * 100)}%${data.cached ? ` · ${(data.cached / 1e9).toFixed(2)} GB cached` : ''}`; + $('#load').textContent = `Loading ${Math.round(data.loaded / data.total * 100)}%`; + } else { $('#load-status').textContent = data.phase === 'compile' ? 'Preparing WebGPU session…' : 'Warming up GPU shaders…'; $('#load-detail').textContent = ''; $('#progress').removeAttribute('value'); $('#load').textContent = data.phase === 'compile' ? 'Preparing…' : 'Almost ready…'; } + $('#load').title = $('#load-status').textContent + ' ' + $('#load-detail').textContent; + } else if (data.type === 'loaded') { + loaded = true; diagnostics.device = data.device; $('#progress').hidden = true; $('#load').textContent = 'Loaded'; + $('#load-status').textContent = 'Ready. Model inference and tools run entirely in this browser.'; + $('#load-detail').textContent = data.cachedBytes ? 'Verified model restored from browser storage.' : 'SHA-256 verified · model cached for next time.'; controls(); + } else if (data.type === 'agent_event') { + const event = data.event; + diagnostics.events.push(event.type); if (diagnostics.events.length > 500) diagnostics.events.shift(); + if (event.message) { + const index = messages.findIndex(m => m.timestamp === event.message.timestamp && m.role === event.message.role && m.toolCallId === event.message.toolCallId); + if (index < 0) messages.push(event.message); else messages[index] = event.message; + renderMessages(); + } + if (event.type === 'tool_execution_start') $('#activity').textContent = `Running ${event.toolName}…`; + if (event.type === 'tool_execution_end' && event.toolName === 'read' && !event.isError && typeof event.result?.details?.path === 'string') { + pendingReadPath = event.result.details.path; + followReadFile(); + } + if (event.type === 'turn_start') $('#activity').textContent = 'Pi is thinking…'; + terminalUI.setState({ activity: $('#activity').textContent }); + } else if (data.type === 'context_usage') { updateContextUsage({ inputTokens: data.inputTokens, outputTokens: data.outputTokens }); } + else if (data.type === 'generation') { diagnostics.generations.push(data); if (diagnostics.generations.length > 100) diagnostics.generations.shift(); } + else if (data.type === 'context_trim') notice('Older turns were left out of the model context. Your full chat remains saved.'); + else if (data.type === 'notice') notice(data.text); + else if (data.type === 'persistence_error') notice(storageHelp(data.error)); + else if (data.type === 'fatal') { loaded = false; notice(data.error); controls(); } +}; +worker.onerror = event => { + runtimeMeter.update({ type: 'fatal' }); + const error = Error(event.message || 'The worker stopped. Reload to restore your saved workspace.'); + notice(error.message); for (const request of pending.values()) request.reject(error); pending.clear(); busy = false; loaded = false; $('#progress').hidden = true; controls(); +}; +const guarded = fn => async event => { event?.preventDefault(); try { await ready; await fn(event); } catch (e) { notice(e.message); } }; +async function load({ cachedOnly = false } = {}) { + if (busy) throw Error('Wait for the current operation or stop it first.'); + notice(''); const query = new URLSearchParams(location.search); + busy = true; + $('#load').textContent = 'Loading…'; + $('#activity').textContent = cachedOnly ? 'Loading local model…' : 'Loading model…'; + $('#load-status').textContent = cachedOnly ? 'Loading local model…' : 'Checking your browser and saved model…'; + $('#load-detail').textContent = ''; + $('#progress').hidden = false; $('#progress').removeAttribute('value'); + runtimeMeter.update({ type: 'busy', action: 'load', cachedOnly }); controls(); + try { + return await rpc('load', { runtimeURL: new URL('./runtime/', location.href).href, + local: query.get('source') === 'local', origin: location.origin, limit128: query.has('limit128'), cachedOnly }); + } catch (error) { error.message = storageHelp(error.message); $('#load-status').textContent = error.message; $('#progress').hidden = true; throw error; } +} +async function prompt(text) { + if (!text.trim()) return; + if (dirty) throw Error('Save your file edits before asking Pi to work on them.'); + try { + if (!loaded) { + let loadError; + if (await rpc('cache_status')) { + try { terminalUI.setQueuedPrompt(text); await load({ cachedOnly: true }); } + catch (error) { + if (error.name === 'AbortError') throw error; + if (error.code !== 'MODEL_CACHE_MISS') loadError = error.message; + } + } + while (!loaded) { + terminalUI.setQueuedPrompt(''); + if (!await loadDialog.request(text, { errorMessage: loadError })) throw new DOMException('Message kept for later.', 'AbortError'); + terminalUI.setQueuedPrompt(text); + try { await load(); } + catch (error) { + if (error.name === 'AbortError') throw error; + loadError = error.message; + } + } + } + terminalUI.setQueuedPrompt(''); + notice(''); const result = await rpc('prompt', { text }); messages = result.messages; renderMessages(); return result; + } finally { terminalUI.setQueuedPrompt(''); } +} +$('#load').onclick = guarded(load); +$('#send').onclick = () => { terminalUI.submit(); terminalUI.focus(); }; +$('#newline').onclick = () => terminalUI.newline(); +$('#stop').onclick = guarded(() => rpc('stop')); +$('.terminal-panel').addEventListener('click', event => { + // Let Pi handle its own mouse targets, and keep controls and text selection + // independent of the surrounding space that returns focus to the editor. + if (event.defaultPrevented || event.button !== 0 || !(event.target instanceof Element)) return; + if (event.target.closest('#pi-terminal, button, a, input, textarea, select, label, summary, [role="button"], [contenteditable]')) return; + if (window.getSelection()?.isCollapsed === false) return; + terminalUI.focus(); +}); +async function newChat() { + pendingReadPath = undefined; + const state = await rpc('new_chat'); messages = state.messages; + updateContextUsage(restoredContextUsage(messages)); + terminalUI.setMessages(messages, { reset: true }); notice(''); + terminalUI.focus(); +} +$('#new-chat').onclick = guarded(newChat); +$('#editor').oninput = () => { dirty = true; controls(); }; +$('#save').onclick = guarded(async () => { await rpc('write', { path: selected, content: $('#editor').value }); dirty = false; renderFiles(); controls(); notice(''); }); +$('#add-file').onclick = guarded(async () => { + if (dirty) throw Error('Save the open file first.'); + const name = window.prompt('File path, relative to /workspace:'); if (!name?.trim()) return; + const path = name.startsWith('/') ? name : '/workspace/' + name; + if (Object.hasOwn(files, path)) throw Error('That file already exists.'); + await rpc('write', { path, content: '' }); selectFile(path); +}); +$('#upload').onchange = guarded(async () => { + if (dirty) throw Error('Save the open file first.'); + for (const file of $('#upload').files) { + if (file.size > 1024 ** 2) throw Error('Import text files of 1 MiB or less.'); + const content = await file.text(); + if (content.includes('\0')) throw Error('Import supports text files only.'); + const path = '/workspace/' + file.name; + if (Object.hasOwn(files, path)) throw Error(file.name + ' already exists. Rename it before importing.'); + await rpc('write', { path, content }); selectFile(path); + } + $('#upload').value = ''; +}); +$('#export').onclick = guarded(async () => { + const state = await rpc('snapshot'), url = URL.createObjectURL(new Blob([JSON.stringify(state, null, 2)], { type: 'application/json' })); + const a = document.createElement('a'); a.href = url; a.download = 'pi-workspace.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); +}); +// Browser verification exercises the same worker and real Pi / WebGPU paths as the UI. +window.browserPi = { ready, load, prompt, rpc, diagnostics, terminal: terminalUI, runtimeMeter, get loaded() { return loaded; }, get busy() { return busy; } }; +controls(); diff --git a/app/src/markdown.mjs b/app/src/markdown.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0856951bc02e17284687d5d9e3278ed18ef175ad --- /dev/null +++ b/app/src/markdown.mjs @@ -0,0 +1,10 @@ +import MarkdownIt from 'markdown-it'; +const md = new MarkdownIt({ html: false, linkify: false, breaks: true }); +// Model output cannot initiate image requests. Links open only on user action. +md.renderer.rules.image = (tokens, index) => md.utils.escapeHtml(tokens[index].content); +const defaultLink = md.renderer.rules.link_open ?? ((tokens, index, options, env, self) => self.renderToken(tokens, index, options)); +md.renderer.rules.link_open = (tokens, index, options, env, self) => { + tokens[index].attrSet('target', '_blank'); tokens[index].attrSet('rel', 'noopener noreferrer'); + return defaultLink(tokens, index, options, env, self); +}; +export const renderMarkdown = text => md.render(text); diff --git a/app/src/model-manifest.json b/app/src/model-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8e69983522b9ad92412e77c965c2e15f14889477 --- /dev/null +++ b/app/src/model-manifest.json @@ -0,0 +1,106 @@ +{ + "source": { + "repo": "openbmb/MiniCPM5-2B", + "revision": "abe115e887989b14f05e64a3b260648329324c3f", + "files": { + "config.json": { + "bytes": 704, + "sha256": "59613157e5357d62bcb121e04cb90f2170b43d789b142380c12c3d4277d95180" + }, + "generation_config.json": { + "bytes": 213, + "sha256": "9ac4f32e5f32358697a9f438a3ea89ef80e6ba786c72c49e932f9f21c122fdb1" + }, + "tokenizer.json": { + "bytes": 9894271, + "sha256": "3e065a558a034185fe299917b398685c1facd0169a9eea1e629eb30c171fed81" + }, + "tokenizer_config.json": { + "bytes": 94391, + "sha256": "e9b1064649e771d7a8e15637c68b2d2749724877ba3648bd74a4ece31c26303b" + }, + "special_tokens_map.json": { + "bytes": 551, + "sha256": "82d96d7a9e6ced037f12394b7ea6a5b02e6ca87e0d11edaa8d60d9be857ce7db" + }, + "chat_template.jinja": { + "bytes": 9060, + "sha256": "cc945752db555d60949b16989df4ccfeb52a313d6b4b5c5229dd786e2e9fcf1c" + }, + "model.safetensors.index.json": { + "bytes": 31378, + "sha256": "6d839cd76e8395de548a0e6cc310386f66d1ecbb2c75d198a8dfd3d70892b756" + }, + "model-00000-of-00001.safetensors": { + "bytes": 5033557096, + "sha256": "14fb8e7f0a18d53d1f239773758bf581cee7e456a4523a54622c3a245b64402c" + } + } + }, + "changes": [ + "last-position LM head at export", + "four lossless embedding column shards", + "concrete cache head dimensions", + "template serialization and compatibility" + ], + "graph_nodes": 480, + "external_chunks": 7, + "files": { + "chat_template.jinja": { + "bytes": 8154, + "sha256": "48636abac6ea1ae7442893ee234e55cce5d45c770ddcc87476555fbf4efde8fe" + }, + "config.json": { + "bytes": 822, + "sha256": "9103173d5af7567b80f15914f95205652f6475f459e843fdc47a4bbb5bdadade" + }, + "generation_config.json": { + "bytes": 213, + "sha256": "9ac4f32e5f32358697a9f438a3ea89ef80e6ba786c72c49e932f9f21c122fdb1" + }, + "onnx/model_q4f16.onnx": { + "bytes": 318519, + "sha256": "d83a86b8ae2566b5bdde23fae366f94a35383f3aefdf3300f138e6dde4ad9d57" + }, + "onnx/model_q4f16.onnx_data": { + "bytes": 265703424, + "sha256": "57ad7c0aef4bdb7ea57ae34f5f2327b88de701c65b52a45b5dc94ff9af1bb985" + }, + "onnx/model_q4f16.onnx_data_1": { + "bytes": 265420800, + "sha256": "19e766345e32a1f1162ab1d418583d94643c01c5ea89b4160c1e68afeca5cfe4" + }, + "onnx/model_q4f16.onnx_data_2": { + "bytes": 265420800, + "sha256": "a83508febe793e70a5c2ce13d7fe029ee5116f33d69863c75a17343caf72ca56" + }, + "onnx/model_q4f16.onnx_data_3": { + "bytes": 265420800, + "sha256": "5d5e46728e6101139e5e8527a0d192a5552393d74f6075f7ffee28fd5881ef0b" + }, + "onnx/model_q4f16.onnx_data_4": { + "bytes": 237109248, + "sha256": "62fe730b14bc33fce8fafa4797b43579abc9b366ec30fb966ba9daad8243be5a" + }, + "onnx/model_q4f16.onnx_data_5": { + "bytes": 267386880, + "sha256": "87c6ba0cd37a3bbbbcba46f33a4adf44214ad9d06854e6cd49e67a03769c1df1" + }, + "onnx/model_q4f16.onnx_data_6": { + "bytes": 267386880, + "sha256": "1b054f4046373d1a4f8c4a70421472e4f6b8fc419151e6911ffe33f8614bb77c" + }, + "special_tokens_map.json": { + "bytes": 551, + "sha256": "82d96d7a9e6ced037f12394b7ea6a5b02e6ca87e0d11edaa8d60d9be857ce7db" + }, + "tokenizer.json": { + "bytes": 9894271, + "sha256": "3e065a558a034185fe299917b398685c1facd0169a9eea1e629eb30c171fed81" + }, + "tokenizer_config.json": { + "bytes": 102804, + "sha256": "36b50abe63f32fc16e21a2ab30af359601915c6d2e58d7466629458adc2492a1" + } + } +} \ No newline at end of file diff --git a/app/src/pi/browser-host.mjs b/app/src/pi/browser-host.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4467b69c6f6fe781c5d0a680e0989058d5e9500d --- /dev/null +++ b/app/src/pi/browser-host.mjs @@ -0,0 +1,8 @@ +// Only Pi's terminal modules import this host adapter. No global Node shim. +export { Buffer } from 'buffer'; +export const performance = globalThis.performance; +export const browserProcess = { + env: { TERM: 'xterm-256color', TERM_PROGRAM: 'xtermjs' }, + platform: 'browser', + nextTick: callback => queueMicrotask(callback), +}; diff --git a/app/src/pi/capabilities.mjs b/app/src/pi/capabilities.mjs new file mode 100644 index 0000000000000000000000000000000000000000..977fdcbd91329da75a3f226309d734e3d9a5a302 --- /dev/null +++ b/app/src/pi/capabilities.mjs @@ -0,0 +1,25 @@ +// xterm.js renders text/ANSI; this app does not install Kitty/iTerm image addons. +// Pi's native image module also probes tmux via child_process. Keep that host +// dependency out of the browser and advertise only capabilities we implement. +let capabilities = { images: null, trueColor: true, hyperlinks: true }; +let dimensions = { widthPx: 8, heightPx: 16 }; +export const getCapabilities = () => capabilities; +export const setCapabilities = value => { capabilities = { ...value, images: null }; }; +export const getCellDimensions = () => dimensions; +export const setCellDimensions = value => { dimensions = value; }; +export const isImageLine = () => false; +export const getKittyImagePlacement = () => undefined; +export const getKittyImageMetadata = () => undefined; +export const cropKittyImageLine = line => line; +export const deleteKittyImage = () => ''; +export const deleteAllKittyImages = () => ''; +export const deleteAllKittyPlacements = () => ''; +export function hyperlink(text, url) { + // Generated text may contain arbitrary URLs. Only explicit user clicks open + // HTTP(S) links, and no terminal control bytes may enter their OSC envelope. + try { + const parsed = new URL(url); + if (!['https:', 'http:'].includes(parsed.protocol) || /[\x00-\x20\x7f-\x9f]/.test(url)) return text; + return `\x1b]8;;${parsed.href}\x07${text}\x1b]8;;\x07`; + } catch { return text; } +} diff --git a/app/src/pi/empty-mascot.mjs b/app/src/pi/empty-mascot.mjs new file mode 100644 index 0000000000000000000000000000000000000000..659076cdcaf8ee9167b1445afbf1cd5e25d2badf --- /dev/null +++ b/app/src/pi/empty-mascot.mjs @@ -0,0 +1,119 @@ +import { playCatSound } from '../cat-sound.mjs'; + +export function createEmptyMascot(element, onSelect) { + const measure = document.createElement('canvas').getContext('2d'); + const baselineMarker = document.createElement('span'); + baselineMarker.style.cssText = 'display:inline-block;width:0;height:0;padding:0;border:0;vertical-align:baseline'; + const mascot = document.createElement('div'); + mascot.className = 'empty-mascot'; mascot.hidden = true; + // Measure its final position while keeping the bubble and cat hidden together. + mascot.style.visibility = 'hidden'; + const suggestion = document.createElement('button'); + suggestion.type = 'button'; suggestion.className = 'mascot-suggestion'; + const figure = document.createElement('div'); + figure.className = 'mascot-cat'; figure.setAttribute('aria-hidden', 'true'); + const cat = document.createElement('img'); + cat.width = cat.height = 104; cat.alt = ''; cat.draggable = false; + const eyelids = document.createElement('span'); + eyelids.className = 'mascot-eyelids'; eyelids.setAttribute('aria-hidden', 'true'); + figure.append(cat, eyelids); + mascot.append(suggestion, figure); element.append(mascot); + let prompt = '', imageReady = false; + let bumped = false, bumpTimer = 0, blinkTimer = 0; + const animations = new Set(); + const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)'); + function animate(target, frames, options) { + for (const active of animations) if (active.id === options.id) { active.cancel(); animations.delete(active); } + const animation = target.animate(frames, options); + animations.add(animation); + animation.onfinish = () => animations.delete(animation); + } + function hop() { + clearTimeout(bumpTimer); bumpTimer = 0; + if (mascot.hidden || document.hidden || reducedMotion.matches || !imageReady) return; + bumped = true; + animate(figure, [{ transform: 'translate3d(0, 0, 0)', easing: 'ease-out' }, { transform: 'translate3d(0, -4px, 0)', offset: .4, easing: 'ease-in' }, { transform: 'translate3d(0, 0, 0)' }], + { id: 'mascot-bump', duration: 420 }); + } + figure.onclick = () => { playCatSound(); hop(); }; + figure.onpointerdown = event => event.preventDefault(); + figure.onmousedown = event => event.preventDefault(); + function stopMotion() { + clearTimeout(bumpTimer); clearTimeout(blinkTimer); + bumpTimer = blinkTimer = 0; + for (const animation of animations) animation.cancel(); + animations.clear(); + } + function syncMotion() { + if (mascot.hidden || document.hidden || reducedMotion.matches || !imageReady) { stopMotion(); return; } + if (!bumped && !bumpTimer) bumpTimer = setTimeout(hop, 1800); + if (!blinkTimer) blinkTimer = setTimeout(() => { + blinkTimer = 0; + animate(eyelids, [{ opacity: 0, easing: 'steps(1, end)' }, { opacity: 1, offset: .15 }, { opacity: 1, offset: .8, easing: 'steps(1, end)' }, { opacity: 0 }], + { id: 'mascot-blink', duration: 180 }); + syncMotion(); + }, 5000 + Math.random() * 4000); + } + function hide() { mascot.hidden = true; stopMotion(); } + async function revealImage() { + try { await cat.decode(); } catch { return; } + if (!mascot.isConnected) return; + imageReady = true; + mascot.style.visibility = ''; + syncMotion(); + } + cat.addEventListener('load', revealImage); + document.addEventListener('visibilitychange', syncMotion); + reducedMotion.addEventListener('change', syncMotion); + suggestion.onclick = () => onSelect(prompt); + return { + hide, + get statusInset() { return mascot.hidden ? 0 : figure.offsetWidth + 20; }, + update({ screen, rows, viewportRows, contentRows, draft, hasSales, hasProducts }) { + if (!screen || !rows) { hide(); return; } + const area = screen.getBoundingClientRect(), root = element.getBoundingClientRect(); + const rowHeight = area.height / rows; + const room = (viewportRows - contentRows) * rowHeight - 16; + if (room < 48) { hide(); return; } + if (!cat.hasAttribute('src')) cat.src = new URL('../../public/empty-cat-v1.png', import.meta.url).href; + const withSuggestion = !draft.trim() && room >= 180; + suggestion.hidden = !withSuggestion; + suggestion.textContent = hasSales && hasProducts + ? 'Ask me to calculate our total sales.' + : 'Ask me to explore your files.'; + prompt = hasSales && hasProducts + ? "What's our total sales revenue?" + : 'Explore the workspace files and summarize what is here.'; + suggestion.setAttribute('aria-label', `Use suggested prompt: ${prompt}`); + const size = Math.min(104, Math.floor(withSuggestion ? room - 76 : room)); + figure.style.width = figure.style.height = `${size}px`; + mascot.hidden = false; + // One status row precedes the editor's top border. Measure the actual + // box-drawing glyph so its baseline follows the browser's font and scale. + let ground = area.top + (viewportRows + 1.5) * rowHeight; + const border = screen.querySelector('.xterm-rows')?.children[viewportRows + 1]?.firstElementChild; + const scale = devicePixelRatio || 1; + if (border && measure) { + const style = getComputedStyle(border); + border.parentElement.append(baselineMarker); + const baseline = baselineMarker.getBoundingClientRect().top; + baselineMarker.remove(); + measure.font = `${style.fontWeight} ${parseFloat(style.fontSize) * scale}px ${style.fontFamily}`; + const ink = measure.measureText('─'); + ground = baseline - (ink.actualBoundingBoxAscent - ink.actualBoundingBoxDescent) / 2 / scale; + } + ground = Math.floor(ground * scale + .0001) / scale; + // The paws end at row 1156 in the 1250px sprite; exclude its black margin. + const pawHeight = Math.round(size * 1156 / 1250 * scale) / scale; + mascot.style.top = `${ground - root.top + size - pawHeight - mascot.getBoundingClientRect().height}px`; + syncMotion(); + }, + dispose() { + hide(); + cat.removeEventListener('load', revealImage); + document.removeEventListener('visibilitychange', syncMotion); + reducedMotion.removeEventListener('change', syncMotion); + mascot.remove(); + }, + }; +} diff --git a/app/src/pi/entry.mjs b/app/src/pi/entry.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0667dadaad1bca5fb00396d924e58bd161d91543 --- /dev/null +++ b/app/src/pi/entry.mjs @@ -0,0 +1,17 @@ +// Import the real upstream components directly, excluding ProcessTerminal and +// native filesystem autocomplete from pi-tui's Node-oriented barrel export. +export { TuiAltScreen } from '@earendil-works/pi-tui/dist/tui-alt-screen.js'; +export { Container } from '@earendil-works/pi-tui/dist/tui.js'; +export { Editor } from '@earendil-works/pi-tui/dist/components/editor.js'; +export { Text } from '@earendil-works/pi-tui/dist/components/text.js'; +export { TruncatedText } from '@earendil-works/pi-tui/dist/components/truncated-text.js'; +export { Markdown } from '@earendil-works/pi-tui/dist/components/markdown.js'; +export { Box } from '@earendil-works/pi-tui/dist/components/box.js'; +export { Spacer } from '@earendil-works/pi-tui/dist/components/spacer.js'; +export { MouseRegion } from '@earendil-works/pi-tui/dist/components/mouse-region.js'; +export { ScrollView } from '@earendil-works/pi-tui/dist/components/scroll-view.js'; +export { VStack } from '@earendil-works/pi-tui/dist/components/v-stack.js'; +export { KeybindingsManager, TUI_KEYBINDINGS, setKeybindings } from '@earendil-works/pi-tui/dist/keybindings.js'; +export { matchesKey } from '@earendil-works/pi-tui/dist/keys.js'; +export { StdinBuffer } from '@earendil-works/pi-tui/dist/stdin-buffer.js'; +export { visibleWidth, stripTerminalSequences } from '@earendil-works/pi-tui/dist/utils.js'; diff --git a/app/src/pi/idle-paws.mjs b/app/src/pi/idle-paws.mjs new file mode 100644 index 0000000000000000000000000000000000000000..032234f54720b6465bada09b93cbe3b0709beac1 --- /dev/null +++ b/app/src/pi/idle-paws.mjs @@ -0,0 +1,71 @@ +const IDLE_DELAY = 7_000; +const TRAIL_DURATION = 6_500; + +export function createIdlePaws(element, getArea) { + const layer = document.createElement('div'); + layer.className = 'terminal-paws'; layer.hidden = true; + layer.setAttribute('aria-hidden', 'true'); + for (let i = 0; i < 6; i++) layer.append(document.createElement('i')); + element.append(layer); + const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)'); + const listeners = new AbortController(); + let enabled = false, visible = false, disposed = false; + let timer = 0, trailTimer = 0, wakeAt = 0, nextAt = 0; + + function canRun() { + return enabled && visible && !disposed && !document.hidden && document.hasFocus() + && !reducedMotion.matches && !document.querySelector('dialog[open]'); + } + function hide() { + clearTimeout(trailTimer); trailTimer = 0; + if (!layer.hidden) layer.hidden = true; + } + function schedule() { + if (!canRun()) { clearTimeout(timer); timer = 0; return; } + // Reuse the pending timer when repeated input moves the deadline later. + if (timer && wakeAt <= nextAt) return; + clearTimeout(timer); wakeAt = nextAt; + timer = setTimeout(tick, Math.max(0, nextAt - Date.now())); + } + function reset() { + hide(); nextAt = Date.now() + IDLE_DELAY; schedule(); + } + function tick() { + timer = 0; + if (!canRun()) return; + if (Date.now() < nextAt) { schedule(); return; } + const area = getArea(); + if (area && area.width >= 220 && area.height >= 180) { + Object.assign(layer.style, { + left: `${area.left}px`, top: `${area.top}px`, + width: `${area.width}px`, height: `${area.height}px`, + }); + layer.style.setProperty('--trail-shift', `${Math.random() * 10}%`); + layer.hidden = false; + trailTimer = setTimeout(hide, TRAIL_DURATION); + } + nextAt = Date.now() + TRAIL_DURATION + 45_000 + Math.random() * 15_000; + schedule(); + } + const options = { passive: true, capture: true, signal: listeners.signal }; + for (const event of ['pointerdown', 'keydown', 'input', 'wheel', 'scroll', 'touchstart', 'touchmove', 'focusin']) { + document.addEventListener(event, reset, options); + } + document.addEventListener('visibilitychange', reset, options); + window.addEventListener('blur', reset, options); + window.addEventListener('focus', reset, options); + reducedMotion.addEventListener('change', reset, options); + const dialogs = new MutationObserver(reset); + for (const dialog of document.querySelectorAll('dialog')) dialogs.observe(dialog, { attributes: true, attributeFilter: ['open'] }); + const visibility = new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; reset(); }); + visibility.observe(element); + + return { + reset, + setEnabled(value) { if (value !== enabled) { enabled = value; reset(); } }, + dispose() { + disposed = true; hide(); clearTimeout(timer); + listeners.abort(); dialogs.disconnect(); visibility.disconnect(); layer.remove(); + }, + }; +} diff --git a/app/src/pi/terminal-ui.mjs b/app/src/pi/terminal-ui.mjs new file mode 100644 index 0000000000000000000000000000000000000000..955033598a421862129f771b5fdbd158df8dd695 --- /dev/null +++ b/app/src/pi/terminal-ui.mjs @@ -0,0 +1,307 @@ +import { Terminal } from '@xterm/xterm'; +import { FitAddon } from '@xterm/addon-fit'; +import { UnicodeGraphemesAddon } from '@xterm/addon-unicode-graphemes'; +import '@xterm/xterm/css/xterm.css'; +import { TuiAltScreen, Container, Text, TruncatedText, Box, Spacer, ScrollView, VStack, + KeybindingsManager, TUI_KEYBINDINGS, setKeybindings, stripTerminalSequences } from './entry.mjs'; +import { CustomEditor } from '../../vendor/pi-coding-agent/components/custom-editor.js'; +import { UserMessageComponent } from '../../vendor/pi-coding-agent/components/user-message.js'; +import { AssistantMessageComponent } from '../../vendor/pi-coding-agent/components/assistant-message.js'; +import { getEditorTheme, theme, terminalTheme } from './theme.mjs'; +import { XtermTerminal } from './xterm-terminal.mjs'; +import { textContent } from '../protocol.mjs'; +import { contextLabel, restoredContextUsage } from '../context-usage.mjs'; +import { createEmptyMascot } from './empty-mascot.mjs'; +import { createIdlePaws } from './idle-paws.mjs'; + +// Model output and workspace files are text, never terminal instructions. +export const terminalText = value => stripTerminalSequences(String(value ?? '')) + .replace(/\r\n?/g, '\n').replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, ''); + +const commands = [ + { value: '/help', label: '/help', description: 'Browser terminal commands' }, + { value: '/load', label: '/load', description: 'Load MiniCPM on this device' }, + { value: '/new', label: '/new', description: 'Start a new conversation; keep files' }, + { value: '/clear', label: '/clear', description: 'Same as /new' }, +]; + +export function createTerminalUI(element, actions) { + const xterm = new Terminal({ + fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', fontSize: 13, lineHeight: 1.3, + theme: terminalTheme, + // Pi owns alternate-screen scrolling. Native scrollback would reserve an + // unused 15px scrollbar gutter in FitAddon and make right padding uneven. + cursorBlink: false, scrollback: 0, screenReaderMode: true, allowProposedApi: true, + }); + // Pi measures grapheme clusters. Match that in xterm so emoji/ZWJ sequences + // don't displace padding or put the editing cursor in the wrong column. + xterm.loadAddon(new UnicodeGraphemesAddon()); + const mount = document.createElement('div'); mount.className = 'pi-terminal-mount'; element.append(mount); + const fitAddon = new FitAddon(); xterm.loadAddon(fitAddon); xterm.open(mount); + const terminal = new XtermTerminal(xterm); + const ui = new TuiAltScreen(terminal, true, undefined, { + copyOnSelect: false, + copySelection: async text => { try { await navigator.clipboard.writeText(text); return true; } catch { return false; } }, + openUrl: url => { if (/^https?:\/\//i.test(url)) window.open(url, '_blank', 'noopener,noreferrer'); }, + scrollToEndIndicator: () => theme.fg('accent', ' ↓ Latest '), + searchMatchStyle: text => theme.bg('selectedBg', theme.fg('text', text)), + searchCurrentMatchStyle: text => theme.bg('accent', theme.fg('userMessageBg', theme.bold(text))), + }); + const keybindings = new KeybindingsManager({ ...TUI_KEYBINDINGS, + 'app.interrupt': { defaultKeys: ['escape', 'ctrl+c'] }, 'app.exit': { defaultKeys: 'ctrl+d' }, + 'app.tools.expand': { defaultKeys: 'ctrl+o' }, + 'tui.editor.historyPrevious': { defaultKeys: 'ctrl+p' }, 'tui.editor.historyNext': { defaultKeys: 'ctrl+n' }, + }); + setKeybindings(keybindings); + // Pi defaults: outputPad=1, editorPaddingX=0. + const editor = new CustomEditor(ui, getEditorTheme(), keybindings, { paddingX: 0 }); + const transcript = new Container(); + const scroll = new ScrollView(transcript, { follow: 'end', primary: true, scrollbar: 'auto', + scrollbarTrackStyle: text => theme.fg('borderMuted', text), scrollbarThumbStyle: text => theme.fg('muted', text) }); + const status = new TruncatedText('', 0, 0); + let statusReservedColumns = 0; + const renderStatus = status.render.bind(status); + status.render = width => { + const reserved = Math.min(statusReservedColumns, Math.max(0, width - 1)); + const lines = renderStatus(width - reserved).map(line => line + ' '.repeat(reserved)); + // Give live activity a little breathing room below the transcript. + return state.busy ? ['', ...lines] : lines; + }; + const footer = { + invalidate() {}, + render(width) { + const location = '/workspace · MiniCPM5-2B'; + const usage = contextLabel(state.contextUsage); + const combined = `${location} · ${usage}`; + const lines = combined.length <= width - 2 ? [combined] : [location, usage]; + return lines.flatMap(line => new TruncatedText(theme.fg('dim', line), 1, 0).render(width)); + }, + }; + ui.setLayoutRoot(new VStack([ + // On a short viewport the editor takes priority over transcript rows. + { component: scroll, basis: 0, grow: 1, minSize: 0 }, + { component: new VStack([status, editor, footer]), basis: 'auto', shrink: 0 }, + ])); + ui.setFocus(editor); + let state = { loaded: false, busy: false, activity: '', contextUsage: restoredContextUsage([]) }, files = [], messages = [], expanded = false; + let inputPending = false; + let queuedPrompt; + let hydrated = false; + const idlePaws = createIdlePaws(element, () => { + const screen = mount.querySelector('.xterm-screen')?.getBoundingClientRect(); + if (!screen || !xterm.rows) return; + const root = element.getBoundingClientRect(); + // Keep every print inside the transcript, above the status and input rows. + return { left: screen.left - root.left, top: screen.top - root.top, + width: screen.width, height: screen.height * scroll.viewportHeight / xterm.rows }; + }); + const mascot = createEmptyMascot(element, text => { + if (state.busy || inputPending || editor.getText().trim()) return; + editor.setText(text); xterm.focus(); ui.requestRender(); + }); + function refreshMascot() { + idlePaws.setEnabled(hydrated && !state.busy && !inputPending && !queuedPrompt); + const screen = mount.querySelector('.xterm-screen'); + if (!hydrated || messages.some(message => message.role === 'user') || state.busy || inputPending) mascot.hide(); + else mascot.update({ screen, rows: xterm.rows, + viewportRows: scroll.viewportHeight, contentRows: transcript.render(xterm.cols).length, + draft: editor.getText(), hasSales: files.includes('sales.csv'), hasProducts: files.includes('products.json') || files.includes('products.csv') }); + // Keep the status text to the left of the cat's lower body. + const cellWidth = screen?.getBoundingClientRect().width / xterm.cols; + const reserved = cellWidth > 0 ? Math.ceil(mascot.statusInset / cellWidth) : 0; + if (reserved !== statusReservedColumns) { statusReservedColumns = reserved; ui.requestRender(); } + } + const mascotRender = xterm.onRender(refreshMascot); + const components = new Map(); + const localEntries = []; + const history = new Set(); + const welcome = new Container(); + welcome.addChild(new Text(theme.fg('accent', theme.bold('π Pi')) + theme.fg('muted', ' browser workspace'), 1, 1)); + welcome.addChild(new Text('Ask Pi to work with your files.\n\n/load load MiniCPM\n/help show commands\n!ls run a workspace command', 1, 0)); + welcome.addChild(new Spacer(1)); + // Keep the first suggested task visible on small phones. Command help stays + // available through /help without taking up the empty conversation area. + const compactWelcome = new Text(theme.fg('accent', theme.bold('π Pi')) + theme.fg('muted', ' browser workspace') + '\nAsk Pi to work with your files.', 1, 0); + const renderWelcome = welcome.render.bind(welcome); + welcome.render = width => xterm.rows < 30 ? compactWelcome.render(width) : renderWelcome(width); + + function addLocal(text, error = false) { + localEntries.push({ at: messages.length, component: new Text(theme.fg(error ? 'error' : 'muted', terminalText(text)), 1, 1) }); + renderMessages(); ui.scrollToBottom(); + } + function remember(text) { + if (!text || history.has(text)) return; + history.add(text); editor.addToHistory(text); + } + function toolComponent(call, result) { + const container = new Container(); + container.addChild(new Spacer(1)); + // Match ToolExecutionComponent's default shell: one outer blank row and + // Box(1, 1), with a ten-line collapsed preview and no extra inner padding. + const box = new Box(1, 1, text => theme.bg(result ? result.isError ? 'toolErrorBg' : 'toolSuccessBg' : 'toolPendingBg', text)); + const title = theme.fg('toolTitle', theme.bold(terminalText(call.name))) + ' ' + + theme.fg('accent', terminalText(call.arguments?.path ?? call.arguments?.command ?? '')); + box.addChild(new Text(title, 0, 0)); + const args = terminalText(JSON.stringify(call.arguments, null, 2)); + const output = terminalText(result ? textContent(result.content) : 'Running…').replace(/\n+$/, ''); + const lines = output.split('\n'); + box.addChild(new Text(theme.fg('toolOutput', expanded ? args + '\n\n' + output : lines.slice(0, 10).join('\n')), 0, 0)); + if (!expanded && lines.length > 10) box.addChild(new Text(theme.fg('dim', `… ${lines.length - 10} more lines · Ctrl+O to expand`), 0, 0)); + container.addChild(box); return container; + } + function renderMessages() { + transcript.clear(); transcript.addChild(welcome); + const results = new Map(messages.filter(m => m.role === 'toolResult').map(m => [m.toolCallId, m])); + const liveKeys = new Set(); + for (let i = 0; i <= messages.length; i++) { + for (const local of localEntries) if (local.at === i) transcript.addChild(local.component); + const message = messages[i]; + if (!message || message.role === 'toolResult') continue; + const key = message.role + ':' + message.timestamp + ':' + i; liveKeys.add(key); + let cached = components.get(key); + if (!cached) { + cached = { component: message.role === 'user' ? new UserMessageComponent(terminalText(textContent(message.content))) : new AssistantMessageComponent(undefined, true) }; + components.set(key, cached); + } + if (message.role === 'user') remember(textContent(message.content)); + if (message.role === 'assistant' && cached.message !== message) { + const clean = { ...message, content: message.content.map(block => block.type === 'text' ? { ...block, text: terminalText(block.text) } : + block.type === 'thinking' ? { ...block, thinking: terminalText(block.thinking) } : block), + errorMessage: message.errorMessage ? terminalText(message.errorMessage) : undefined }; + cached.component.setHiddenThinkingLabel(message.stopReason ? 'Thoughts · click to expand' : 'Thinking…'); + cached.component.updateContent(clean, !message.stopReason); + } + // Pi's assistant and tool components start with a separator. Apply the + // same outer gap before user boxes; keep their native inner padding. + if (message.role === 'user' && (i > 0 || localEntries.length)) transcript.addChild(new Spacer(1)); + cached.message = message; transcript.addChild(cached.component); + for (const call of Array.isArray(message.content) ? message.content : []) { + if (call.type !== 'toolCall') continue; + const result = results.get(call.id), toolKey = 'tool:' + call.id; liveKeys.add(toolKey); + const signature = JSON.stringify([call, result, expanded]); + let tool = components.get(toolKey); + if (tool?.signature !== signature) { tool = { signature, component: toolComponent(call, result) }; components.set(toolKey, tool); } + transcript.addChild(tool.component); + } + } + for (const key of components.keys()) if (!liveKeys.has(key)) components.delete(key); + if (queuedPrompt) { + transcript.addChild(new Spacer(1)); + transcript.addChild(queuedPrompt); + transcript.addChild(new Text(theme.fg('muted', 'Queued · sends when the model is ready'), 1, 0)); + } + refreshMascot(); + ui.requestRender(); + } + function refreshStatus() { + status.text = theme.fg(state.busy ? 'accent' : 'muted', terminalText(state.activity || (state.busy ? '' : state.loaded ? 'Ready' : 'Send a message to get started · /help'))); + editor.disableSubmit = state.busy || inputPending; + editor.borderColor = text => theme.fg(state.busy ? 'accent' : 'borderMuted', text); + actions.onInput?.(editor.getText()); ui.requestRender(); + refreshMascot(); + } + async function submit(text) { + if (!text.trim() || state.busy || inputPending) return; + inputPending = true; refreshStatus(); + remember(text); ui.scrollToBottom(); + try { + const trimmed = text.trim(); + if (trimmed === '/help') { + addLocal('/load Load MiniCPM on this device\n/new Clear the conversation; keep workspace files\n!cmd Run cmd with just-bash\n\nEnter: send · Shift+Enter: newline\n↑/↓: edit/history · Ctrl+P/N: history\nEsc or Ctrl+C: stop · Ctrl+O: expand tools\nCtrl+Shift+F: search transcript\n\nPi’s original terminal UI and agent core run here.\nNode CLI extensions, npm, Python and native binaries are unavailable.'); + } else if (trimmed === '/load') { await actions.load(); } + else if (trimmed === '/new' || trimmed === '/clear') { await actions.newChat(); localEntries.length = 0; renderMessages(); } + else if (trimmed.startsWith('/')) { throw Error('Unknown browser command. Type /help for available commands.'); } + else if (trimmed.startsWith('!')) { + const command = trimmed.slice(1).trim(); if (!command) throw Error('Enter a shell command after !.'); + const result = await actions.shell(command); + addLocal(`$ ${command}\n${result.stdout}${result.stderr}\n[exit ${result.exitCode}]`, result.exitCode !== 0); + } else { await actions.prompt(text); } + } catch (error) { + if (error.name !== 'AbortError') addLocal(error.message, true); + // Preserve a failed submission without overwriting a draft typed meanwhile. + if (!editor.getText()) editor.setText(text); + } finally { inputPending = false; refreshStatus(); } + } + editor.onSubmit = text => { void submit(text); }; + editor.onChange = () => { actions.onInput?.(editor.getText()); ui.requestRender(); }; + editor.onEscape = () => { if (state.busy) void actions.stop().catch(error => addLocal(error.message, true)); }; + editor.onCtrlD = () => addLocal('This terminal lives in your browser. Close the tab to leave.'); + editor.onAction('app.tools.expand', () => { expanded = !expanded; renderMessages(); }); + editor.setAutocompleteProvider({ + getSuggestions(lines, line, col) { + const before = lines[line].slice(0, col), prefix = before.match(/\S*$/)?.[0] ?? ''; + if (!prefix) return null; + const candidates = before.startsWith('/') ? commands : files.map(path => ({ value: path, label: path, description: 'workspace file' })); + const items = candidates.filter(item => item.value.startsWith(prefix) && item.value !== prefix); + return items.length ? { items, prefix } : null; + }, + applyCompletion(lines, line, col, item, prefix) { + const updated = [...lines]; updated[line] = lines[line].slice(0, col - prefix.length) + item.value + ' ' + lines[line].slice(col); + return { lines: updated, cursorLine: line, cursorCol: col - prefix.length + item.value.length + 1 }; + }, + }); + xterm.attachCustomKeyEventHandler(event => { + if (event.type !== 'keydown' || event.isComposing) return true; + // Let the browser deliver its native paste event (no clipboard permission + // request). xterm then applies bracketed paste before Pi sees the text. + if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'v') return false; + // Legacy xterm input folds Ctrl+Shift+F into Ctrl+F. Preserve the modifier + // in CSI-u form for Pi's existing fullscreen transcript-search binding. + if (event.ctrlKey && event.shiftKey && event.code === 'KeyF') { + event.preventDefault(); terminal.inputData('\x1b[102;6u'); return false; + } + if (event.key === 'Enter' && event.shiftKey) { event.preventDefault(); terminal.inputData('\x1b\r'); return false; } + if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'c' && (xterm.hasSelection() || ui.hasActiveSelection())) { + if (ui.hasActiveSelection()) { event.preventDefault(); void ui.copyActiveSelectionToClipboard(); } + return false; + } + return true; + }); + // xterm's alternate buffer has no native scrollback. Route touch gestures to + // Pi's ScrollView while leaving taps/IME handling with xterm itself. + let touchY; + element.addEventListener('touchstart', event => { if (event.touches.length === 1) touchY = event.touches[0].clientY; }, { passive: true }); + element.addEventListener('touchmove', event => { + if (touchY === undefined || event.touches.length !== 1) return; + const y = event.touches[0].clientY, rows = Math.trunc((touchY - y) / 18); + if (rows) { ui.scrollBy(rows); touchY = y; event.preventDefault(); } + }, { passive: false }); + element.addEventListener('touchend', () => { touchY = undefined; }, { passive: true }); + function fit() { + idlePaws.reset(); + if (element.clientWidth > 0 && element.clientHeight > 0) { fitAddon.fit(); ui.requestRender(); } + } + const observer = new ResizeObserver(fit); observer.observe(element); + fit(); ui.start(); renderMessages(); refreshStatus(); + document.fonts.ready.then(fit); + xterm.textarea.setAttribute('aria-label', 'Message Pi'); + xterm.textarea.setAttribute('autocapitalize', 'off'); + xterm.textarea.setAttribute('spellcheck', 'false'); + return { + setMessages(value, { reset = false } = {}) { hydrated = true; messages = value; if (reset) { localEntries.length = 0; components.clear(); } renderMessages(); }, + setFiles(value) { files = Object.keys(value).map(path => path.replace(/^\/workspace\//, '')); refreshMascot(); }, + setState(value) { state = { ...state, ...value }; refreshStatus(); }, + setQueuedPrompt(text) { + if (!text && !queuedPrompt) return; + queuedPrompt = text ? new UserMessageComponent(terminalText(text)) : undefined; + renderMessages(); ui.scrollToBottom(); + }, + submit() { const text = editor.getExpandedText(); if (!editor.disableSubmit && text.trim()) { editor.setText(''); return submit(text); } }, + focus() { xterm.focus(); }, + newline() { terminal.inputData('\x1b\r'); xterm.focus(); }, + get text() { return editor.getExpandedText(); }, + get cols() { return xterm.cols; }, get rows() { return xterm.rows; }, + get viewportTop() { return ui.viewportTop; }, + readScreen() { return Array.from({ length: xterm.buffer.active.length }, (_, i) => xterm.buffer.active.getLine(i)?.translateToString(true) ?? '').join('\n'); }, + readDocument() { return scroll.render(xterm.cols).map(line => stripTerminalSequences(line).trimEnd()); }, + readCells() { + return Array.from({ length: xterm.rows }, (_, row) => Array.from({ length: xterm.cols }, (_, col) => { + const cell = xterm.buffer.active.getLine(row)?.getCell(col); + return cell ? { text: cell.getChars(), width: cell.getWidth(), + fg: cell.isFgDefault() ? terminalTheme.foreground : cell.getFgColor(), + bg: cell.isBgDefault() ? terminalTheme.background : cell.getBgColor() } : null; + })); + }, + dispose() { observer.disconnect(); mascotRender.dispose(); mascot.dispose(); idlePaws.dispose(); ui.stop({ preserveScreen: true }); xterm.dispose(); }, + }; +} diff --git a/app/src/pi/theme.mjs b/app/src/pi/theme.mjs new file mode 100644 index 0000000000000000000000000000000000000000..45e611482a8b2e39520a5371f616f3d2be760928 --- /dev/null +++ b/app/src/pi/theme.mjs @@ -0,0 +1,40 @@ +import palette from '../../vendor/pi-coding-agent/theme/dark.json'; + +// Upstream Pi dark palette; browser styling replaces the theme file watcher +// and Node's syntax highlighter. Code blocks use Pi's plain-code fallback. +// Lift secondary text so small terminal text stays legible on tool backgrounds. +const readable = { muted: '#b0b0bd', toolOutput: '#b0b0bd', thinkingText: '#b0b0bd', + dim: '#aaaab7', mdLinkUrl: '#aaaab7', mdCodeBlockBorder: '#aaaab7', mdQuote: '#b0b0bd' }; +function color(name, text, background = false) { + const value = readable[name] ?? palette.vars[palette.colors[name]] ?? palette.colors[name] ?? palette.vars.text; + const rgb = value.slice(1).match(/../g).map(part => parseInt(part, 16)).join(';'); + const open = `\x1b[${background ? 48 : 38};2;${rgb}m`, close = `\x1b[${background ? 49 : 39}m`; + return open + String(text).replaceAll(close, open) + close; +} +export const terminalTheme = { + background: palette.export.pageBg, foreground: palette.vars.text, + cursor: palette.vars.accent, cursorAccent: palette.export.pageBg, + selectionBackground: palette.vars.selectedBg, selectionForeground: palette.vars.text, + black: '#18181e', brightBlack: '#9696a4', white: '#d4d4d4', brightWhite: '#f2f2f4', +}; +export const theme = { + fg: (name, text) => color(name, text), bg: (name, text) => color(name, text, true), + bold: text => `\x1b[1m${text}\x1b[22m`, italic: text => `\x1b[3m${text}\x1b[23m`, + underline: text => `\x1b[4m${text}\x1b[24m`, +}; +export function getMarkdownTheme() { + return { + ...Object.fromEntries(Object.entries({ heading: 'mdHeading', link: 'mdLink', linkUrl: 'mdLinkUrl', code: 'mdCode', + codeBlock: 'mdCodeBlock', codeBlockBorder: 'mdCodeBlockBorder', quote: 'mdQuote', quoteBorder: 'mdQuoteBorder', + hr: 'mdHr', listBullet: 'mdListBullet' }).map(([key, value]) => [key, text => theme.fg(value, text)])), + bold: theme.bold, italic: theme.italic, underline: theme.underline, + strikethrough: text => `\x1b[9m${text}\x1b[29m`, + highlightCode: code => code.split('\n').map(line => theme.fg('mdCodeBlock', line)), + }; +} +export function getEditorTheme() { + return { borderColor: text => theme.fg('borderMuted', text), selectList: { + selectedPrefix: text => theme.fg('accent', text), selectedText: text => theme.fg('accent', text), + description: text => theme.fg('muted', text), scrollInfo: text => theme.fg('muted', text), noMatch: text => theme.fg('muted', text), + } }; +} diff --git a/app/src/pi/xterm-terminal.mjs b/app/src/pi/xterm-terminal.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9206079a7995ee3ae4164e85a0001ebacb62950e --- /dev/null +++ b/app/src/pi/xterm-terminal.mjs @@ -0,0 +1,31 @@ +import { StdinBuffer } from './entry.mjs'; + +// Implements Pi's Terminal interface using xterm.js instead of a Node PTY. +export class XtermTerminal { + constructor(xterm) { this.xterm = xterm; this.subscriptions = []; } + start(onInput, onResize) { + this.input = new StdinBuffer(); + this.input.on('data', onInput); + this.input.on('paste', text => onInput(`\x1b[200~${text}\x1b[201~`)); + this.subscriptions.push(this.xterm.onData(data => this.input.process(data)), this.xterm.onResize(onResize)); + this.write('\x1b[?2004h'); + } + stop() { + this.subscriptions.forEach(subscription => subscription.dispose()); this.subscriptions = []; + this.input?.destroy(); this.write('\x1b[?2004l'); + } + async drainInput() { /* There is no parent process or SSH input to drain. */ } + write(data) { this.xterm.write(data); } + get columns() { return this.xterm.cols; } + get rows() { return this.xterm.rows; } + get kittyProtocolActive() { return false; } + moveBy(lines) { if (lines) this.write(`\x1b[${Math.abs(lines)}${lines > 0 ? 'B' : 'A'}`); } + hideCursor() { this.write('\x1b[?25l'); } + showCursor() { this.write('\x1b[?25h'); } + clearLine() { this.write('\x1b[K'); } + clearFromCursor() { this.write('\x1b[J'); } + clearScreen() { this.write('\x1b[2J\x1b[H'); } + setTitle(title) { this.xterm.element?.setAttribute('aria-label', title); } + setProgress(active) { this.xterm.element?.setAttribute('aria-busy', String(active)); } + inputData(data) { this.input?.process(data); } +} diff --git a/app/src/prism-worker-setup.mjs b/app/src/prism-worker-setup.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b0e55803f128949d9b5ba631026fa18a1edd3101 --- /dev/null +++ b/app/src/prism-worker-setup.mjs @@ -0,0 +1,3 @@ +// Must execute before Prism core: this worker uses our versioned message +// protocol, rather than Prism's built-in JSON-string worker protocol. +self.Prism = { manual: true, disableWorkerMessageHandler: true }; diff --git a/app/src/protocol.mjs b/app/src/protocol.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7d21b412278bf677eaa4577a2b900b5f0c9d37e9 --- /dev/null +++ b/app/src/protocol.mjs @@ -0,0 +1,118 @@ +import { DOMParser } from '@xmldom/xmldom'; + +export const textContent = content => typeof content === 'string' ? content : + (content ?? []).filter(c => c.type === 'text').map(c => c.text).join('\n'); + +export function toMiniMessages(context) { + const messages = context.messages.filter(m => m.role !== 'assistant' || !['error', 'aborted'].includes(m.stopReason)); + return [{ role: 'system', content: context.systemPrompt }, ...messages.map(m => { + if (m.role === 'toolResult') return { role: 'tool', content: JSON.stringify({ + name: m.toolName, isError: m.isError, output: textContent(m.content), + }) }; + if (m.role === 'assistant') return { role: 'assistant', + // Explicit even when empty: the upstream template otherwise mistakes + // literal inside code or tool arguments for a reasoning boundary. + reasoning_content: m.content.filter(c => c.type === 'thinking').map(c => c.thinking).join('\n'), + content: m.content.map(c => c.type === 'text' ? c.text : c.type === 'toolCall' ? '' : '').join(''), + tool_calls: m.content.filter(c => c.type === 'toolCall').map(c => ({ + type: 'function', function: { name: c.name, arguments: c.arguments }, + })) }; + return { role: 'user', content: textContent(m.content) }; + })]; +} + +// Scan function boundaries outside CDATA; regex alone breaks shell commands +// containing XML (including literal inside a here-document). +function functionEnd(raw, start) { + let at = start; + while (at < raw.length) { + const cdata = raw.indexOf('', at); + if (end < 0) throw Error('Incomplete tool call. No command was executed. Try again with a shorter task.'); + if (cdata < 0 || cdata > end) return end + 11; + const close = raw.indexOf(']]>', cdata + 9); + if (close < 0) throw Error('Incomplete CDATA in tool call. No command was executed.'); + at = close + 3; + } +} + +function nextFunction(raw, start) { + let fence = null, inline = 0; + for (let at = start; at < raw.length;) { + if (at === 0 || raw[at - 1] === '\n') { + const line = raw.slice(at).split('\n')[0]; + const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1]; + if (marker) { + if (!fence) fence = marker; + else if (marker[0] === fence[0] && marker.length >= fence.length) fence = null; + at += line.length + 1; continue; + } + } + if (fence) { at++; continue; } + if (raw[at] === '`') { + const count = /^`+/.exec(raw.slice(at))[0].length; + if (!inline) inline = count; else if (inline === count) inline = 0; + at += count; continue; + } + if (!inline && /^\n?/.exec(raw); + if (!thinkingPrefilled && !opening) return { thinking: '', answer: raw, complete: true }; + const start = opening?.[0].length ?? 0; + const end = raw.indexOf('', start); + if (end < 0) return { thinking: raw.slice(start), answer: '', complete: false }; + return { thinking: raw.slice(start, end), answer: raw.slice(end + 8), complete: true }; +} + +export function parseCompletion(raw, tools, options) { + raw = raw.replace(/<\|im_end\|>$|<\/s>$/, ''); + const reasoning = splitThinking(raw, options); + if (!reasoning.complete) throw Error('The model used its response budget before finishing its thoughts. Try a smaller task.'); + raw = reasoning.answer; + const blocks = reasoning.thinking.trim() ? [{ type: 'thinking', thinking: reasoning.thinking.trim() }] : []; + let at = 0; + while (at < raw.length) { + const start = nextFunction(raw, at); + if (start < 0) { if (raw.slice(at).trim()) blocks.push({ type: 'text', text: raw.slice(at).trim() }); break; } + if (raw.slice(at, start).trim()) blocks.push({ type: 'text', text: raw.slice(at, start).trim() }); + const end = functionEnd(raw, start); + const errors = []; + const doc = new DOMParser({ onError: (level, message) => errors.push(message) }) + .parseFromString(raw.slice(start, end), 'application/xml'); + if (errors.length || doc.doctype || doc.documentElement.tagName !== 'function') throw Error('Malformed model tool call.'); + const fn = doc.documentElement, name = fn.getAttribute('name'); + const tool = tools.find(t => t.name === name); + if (!tool) throw Error('Unknown model tool: ' + name); + const args = Object.create(null); + for (const node of Array.from(fn.childNodes)) { + if (node.nodeType === 3 && !node.textContent.trim()) continue; + if (node.nodeType !== 1 || node.tagName !== 'param') throw Error('Unexpected content in tool call.'); + const key = node.getAttribute('name'); + if (Object.hasOwn(args, key) || !Object.hasOwn(tool.parameters.properties, key)) throw Error('Unknown or duplicate tool parameter: ' + key); + if (Array.from(node.childNodes).some(c => ![3, 4].includes(c.nodeType))) throw Error('Tool values containing XML must use CDATA.'); + const schema = tool.parameters.properties[key]; + args[key] = schema.type === 'string' ? node.textContent : JSON.parse(node.textContent); + } + blocks.push({ type: 'toolCall', id: crypto.randomUUID(), name, arguments: args }); + at = end; + } + return blocks; +} + +// Keep complete user turns together so tool results never lose their calls. +export function fitContext(context, tokenize, maxPromptTokens) { + const messages = [...context.messages]; + let dropped = 0; + while (true) { + const inputs = tokenize(toMiniMessages({ ...context, messages })); + if (inputs.input_ids.dims[1] <= maxPromptTokens) return { inputs, dropped }; + const nextUser = messages.findIndex((m, i) => i > 0 && m.role === 'user'); + if (nextUser < 0) throw Error('This task exceeds the browser context budget. Start a new chat or use smaller files and shorter tool output.'); + messages.splice(0, nextUser); dropped += nextUser; + } +} diff --git a/app/src/runtime-meter.mjs b/app/src/runtime-meter.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e18fb1a4b614a5544161392982a8bd18ef9d2b01 --- /dev/null +++ b/app/src/runtime-meter.mjs @@ -0,0 +1,79 @@ +export function createRuntimeMeter(element) { + const value = element.querySelector('.runtime-value'); + const chart = element.querySelector('.runtime-sparkline'); + const bars = element.querySelector('.runtime-bars'); + const announcement = element.querySelector('[role="status"]'); + const engine = element.querySelector('.runtime-engine'); + // Measure the intrinsic contents so CSS can animate between numeric widths. + // This also follows font changes without reserving empty space while idle. + const content = element.querySelector('.runtime-content'); + const sizeObserver = new ResizeObserver(([entry]) => { + element.style.width = `calc(${Math.ceil(entry.contentRect.width)}px + 2 * var(--runtime-padding))`; + }); + sizeObserver.observe(content); + let loaded = false, phase, rates = [], staleTimer; + function show(nextPhase, label, description) { + clearTimeout(staleTimer); + if (nextPhase !== phase) announcement.textContent = description ?? `${label} in this browser.`; + phase = nextPhase; + engine.textContent = phase === 'tool' ? 'JavaScript' : 'WebGPU'; + element.dataset.state = phase; + value.textContent = label; + chart.setAttribute('hidden', ''); + element.title = description ?? `${label} in this browser.`; + if (phase !== 'generating') { rates = []; bars.replaceChildren(); } + } + function idle() { show('idle', loaded ? 'Ready' : 'Idle', loaded ? 'Model ready. Inference and tools run in this browser.' : 'Model loads when you send a message. Inference and tools run in this browser.'); } + function sample(rate) { + if (!Number.isFinite(rate) || rate < 0) { show('generating', 'Generating…'); return; } + show('generating', `${rate < 10 ? rate.toFixed(1) : Math.round(rate)} tok/s`, 'Live token generation speed, including thinking tokens. Prompt-processing time is excluded.'); + rates.push(rate); if (rates.length > 12) rates.shift(); + const ceiling = Math.max(40, ...rates); + // Keep all twelve positions visible; dots mark gaps without inventing samples. + const slots = [...Array(12 - rates.length).fill(null), ...rates]; + bars.replaceChildren(...slots.map((rate, index) => { + if (rate === null || rate === 0) { + const dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); + dot.setAttribute('cx', String(index * 4 + 1)); + dot.setAttribute('cy', '17'); dot.setAttribute('r', '1'); + dot.setAttribute('opacity', rate === null ? '.35' : '.6'); + return dot; + } + const bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); + const height = Math.max(2, Math.min(16, rate / ceiling * 16)); + bar.setAttribute('x', String(index * 4)); + bar.setAttribute('y', (18 - height).toFixed(2)); + bar.setAttribute('width', '2'); bar.setAttribute('height', height.toFixed(2)); bar.setAttribute('rx', '1'); + return bar; + })); + chart.removeAttribute('hidden'); + // If worker updates stop arriving, do not leave an old speed looking live. + staleTimer = setTimeout(() => { show('generating', 'Generating…'); rates = []; bars.replaceChildren(); }, 2000); + } + idle(); + return { + update(data) { + if (data.type === 'loaded') { loaded = true; idle(); } + else if (data.type === 'idle' || data.type === 'initialized') idle(); + else if (data.type === 'fatal') { loaded = false; show('error', 'Unavailable'); } + else if (data.type === 'busy') { + if (data.action === 'load') show('loading', 'Loading…', data.cachedOnly ? 'Loading local model…' : undefined); + else if (data.action === 'prompt') show('prefill', 'Reading prompt…'); + else if (data.action === 'shell') show('tool', 'Running bash…'); + else if (data.action === 'read') show('tool', 'Reading file…'); + else if (data.action === 'write') show('tool', 'Writing file…'); + else show('working', 'Working…'); + } else if (data.type === 'load_progress') { + const label = data.phase === 'download' && data.loaded < data.total ? `Downloading ${Math.round(data.loaded / data.total * 100)}%` : data.phase === 'warmup' ? 'Warming up…' : 'Preparing…'; + show('loading', label); + } else if (data.type === 'inference_activity') { + if (data.phase === 'prefill') show('prefill', 'Reading prompt…'); + else if (data.phase === 'decode') sample(data.rate); + else if (phase === 'generating' || phase === 'prefill') show('working', 'Working…'); + } else if (data.type === 'agent_event' && data.event.type === 'tool_execution_start') { + const labels = { bash: 'Running bash…', read: 'Reading file…', write: 'Writing file…', edit: 'Editing file…' }; + show('tool', labels[data.event.toolName] ?? 'Running tool…'); + } + }, + }; +} diff --git a/app/src/sampling.mjs b/app/src/sampling.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dacfcfd2df0bc64b22a7f072752a89e4b28bfe6c --- /dev/null +++ b/app/src/sampling.mjs @@ -0,0 +1,49 @@ +// Transformers.js 4.2.0 exposes top_p but does not apply it in generate(). +// Apply nucleus filtering after its temperature/repetition processors and +// before its normal multinomial sampler. No min-p or top-k filter is added. +export function nucleusProcessor(topP = 0.95) { + if (!(topP > 0 && topP <= 1)) throw Error('topP must be in (0, 1].'); + let sorted; + return (_inputIds, logits) => { + if (topP === 1) return logits; + const size = logits.dims.at(-1); + sorted ??= new Float32Array(size); + if (sorted.length !== size) sorted = new Float32Array(size); + for (let offset = 0; offset < logits.data.length; offset += size) { + const scores = logits.data.subarray(offset, offset + size); + let max = -Infinity; + for (let i = 0; i < size; i++) max = Math.max(max, scores[i]); + if (!Number.isFinite(max)) throw Error('The model produced invalid sampling scores.'); + let total = 0; + for (let i = 0; i < size; i++) total += Math.exp(scores[i] - max); + const tailMass = (1 - topP) * total; + // Most vocabulary entries have negligible mass. Exclude a tail only + // after measuring its entire mass; this is exact, not a top-k shortcut. + let floor = max - 8, count, mass; + do { + count = 0; mass = 0; + for (let i = 0; i < size; i++) { + if (scores[i] >= floor) sorted[count++] = scores[i]; + else mass += Math.exp(scores[i] - max); + } + if (mass <= tailMass) break; + floor -= 8; + } while (true); + sorted.subarray(0, count).sort(); + let removed = 0; + // Always retain at least one token, including when logits have ties. + while (removed < count - 1) { + const next = mass + Math.exp(sorted[removed] - max); + if (next > tailMass) break; + mass = next; removed++; + } + const cutoff = removed ? sorted[removed - 1] : floor; + let tied = 0; + for (let i = removed - 1; i >= 0 && sorted[i] === cutoff; i--) tied++; + for (let i = 0; i < size; i++) { + if (scores[i] < cutoff || (scores[i] === cutoff && tied-- > 0)) scores[i] = -Infinity; + } + } + return logits; + }; +} diff --git a/app/src/shell-ui.mjs b/app/src/shell-ui.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6a6bc154f266b82408ed7a4b0e2e01c9679400f0 --- /dev/null +++ b/app/src/shell-ui.mjs @@ -0,0 +1,114 @@ +import Prism from 'prismjs/components/prism-core.js'; +import 'prismjs/components/prism-bash.js'; +import { stripTerminalSequences } from '@earendil-works/pi-tui/dist/utils.js'; + +Prism.manual = true; +const plain = value => stripTerminalSequences(String(value ?? '')).replace(/\r\n?/g, '\n').replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, ''); +const outputLimit = 24_000; +function displayText(text) { + text = plain(text); + return text.length > outputLimit ? text.slice(0, outputLimit) + '\n… output truncated; use head or grep to narrow it down.' : text; +} + +// Tokens become DOM text nodes, never HTML supplied by a command or file. +function syntax(text) { + const fragment = document.createDocumentFragment(); + function append(parent, token) { + if (typeof token === 'string') { parent.append(document.createTextNode(token)); return; } + if (Array.isArray(token)) { token.forEach(item => append(parent, item)); return; } + const span = document.createElement('span'); + span.className = ['token', token.type, ...[token.alias ?? []].flat()].join(' '); + append(span, token.content); parent.append(span); + } + // Very large pastes remain editable without synchronous grammar work. + append(fragment, text.length > 8192 ? text : Prism.tokenize(text, Prism.languages.bash)); + return fragment; +} + +export function createShellUI(element, { run }) { + const find = selector => element.querySelector(selector); + const input = find('#command'), highlight = find('#command-highlight'); + const output = find('#terminal-output'), form = find('#shell-form'); + const runButton = find('#shell-run'), clearButton = find('#shell-clear'); + const empty = output.firstElementChild.cloneNode(true); + const history = [], entries = []; + let historyIndex = 0, draft = '', running = false, busy = false; + const atBottom = () => output.scrollHeight - output.scrollTop - output.clientHeight < 24; + const scrollEnd = () => { output.scrollTop = output.scrollHeight; }; + function controls() { + runButton.disabled = running || busy || !input.value.trim(); + runButton.textContent = running ? 'Running…' : 'Run'; + clearButton.disabled = running || entries.length === 0; + } + function renderInput() { + highlight.replaceChildren(syntax(input.value), document.createTextNode('\n')); + input.style.height = 'auto'; input.style.height = Math.min(104, Math.max(32, input.scrollHeight)) + 'px'; + highlight.scrollTop = input.scrollTop; highlight.scrollLeft = input.scrollLeft; + controls(); + } + function setInput(value) { input.value = value; renderInput(); input.setSelectionRange(value.length, value.length); } + function clear() { + if (running) return; + entries.length = 0; output.replaceChildren(empty.cloneNode(true)); controls(); + } + function appendOutput(entry, value, className) { + if (!value) return; + const pre = document.createElement('pre'); pre.className = className; + pre.textContent = displayText(value); entry.append(pre); + } + form.onsubmit = async event => { + event.preventDefault(); + const command = input.value; + if (running || busy || !command.trim()) return; + running = true; + if (history.at(-1) !== command) history.push(command); + if (history.length > 50) history.shift(); + historyIndex = history.length; draft = ''; setInput(''); input.focus(); + if (!entries.length) output.replaceChildren(); + const entry = document.createElement('section'); entry.className = 'shell-entry'; + const header = document.createElement('div'); header.className = 'shell-entry-heading'; + const prompt = document.createElement('span'); prompt.className = 'shell-prompt'; prompt.textContent = '$'; + const code = document.createElement('pre'); code.className = 'shell-code'; code.append(syntax(displayText(command))); + const status = document.createElement('span'); status.className = 'shell-status'; status.textContent = 'Running…'; + header.append(prompt, code, status); entry.append(header); output.append(entry); entries.push(entry); scrollEnd(); + try { + const result = await run(command); + const follow = atBottom(); + appendOutput(entry, result.stdout, 'shell-stdout'); + appendOutput(entry, result.stderr, 'shell-stderr'); + status.classList.add(result.exitCode === 0 ? 'success' : 'error'); status.textContent = `[exit ${result.exitCode}]`; + if (follow) scrollEnd(); + } catch (error) { + const follow = atBottom(); + appendOutput(entry, error.message, 'shell-stderr'); status.classList.add('error'); status.textContent = '[error]'; + if (!input.value) setInput(command); + if (follow) scrollEnd(); + } finally { + // Keep complete recent command blocks, bounded independently of the FS. + while (entries.length > 1 && (entries.length > 40 || output.textContent.length > 48_000)) entries.shift().remove(); + running = false; controls(); + } + }; + input.addEventListener('input', () => { historyIndex = history.length; draft = input.value; renderInput(); }); + input.addEventListener('scroll', () => { highlight.scrollTop = input.scrollTop; highlight.scrollLeft = input.scrollLeft; }); + input.addEventListener('keydown', event => { + if (event.isComposing || event.keyCode === 229) return; + if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); form.requestSubmit(); return; } + if (event.ctrlKey && event.key.toLowerCase() === 'l') { event.preventDefault(); clear(); return; } + if (event.ctrlKey || event.altKey || event.metaKey || event.shiftKey || input.selectionStart !== input.selectionEnd) return; + const firstLine = !input.value.slice(0, input.selectionStart).includes('\n'); + const lastLine = !input.value.slice(input.selectionEnd).includes('\n'); + if (event.key === 'ArrowUp' && firstLine && historyIndex > 0) { + event.preventDefault(); if (historyIndex === history.length) draft = input.value; + setInput(history[--historyIndex]); + } else if (event.key === 'ArrowDown' && lastLine && historyIndex < history.length) { + event.preventDefault(); setInput(++historyIndex === history.length ? draft : history[historyIndex]); + } + }); + clearButton.onclick = () => { clear(); input.focus(); }; + // Wrapping and textarea height change with the workspace width. + let width = 0; + new ResizeObserver(([entry]) => { if (entry.contentRect.width !== width) { width = entry.contentRect.width; renderInput(); } }).observe(input.parentElement); + renderInput(); + return { setBusy(value) { busy = value; controls(); } }; +} diff --git a/app/src/storage.mjs b/app/src/storage.mjs new file mode 100644 index 0000000000000000000000000000000000000000..05e6e2c565517bf3f68f41c6060e4240dda41d3c --- /dev/null +++ b/app/src/storage.mjs @@ -0,0 +1,21 @@ +export async function openStorage() { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open('minicpm5-pi-workspace', 1); + request.onupgradeneeded = () => request.result.createObjectStore('state'); + request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); + }); + return { + async load() { + return new Promise((resolve, reject) => { + const request = db.transaction('state').objectStore('state').get('current'); + request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); + }); + }, + async save(value) { + return new Promise((resolve, reject) => { + const tx = db.transaction('state', 'readwrite'); tx.objectStore('state').put(value, 'current'); + tx.oncomplete = resolve; tx.onerror = () => reject(tx.error); tx.onabort = () => reject(tx.error); + }); + }, + }; +} diff --git a/app/src/style.css b/app/src/style.css new file mode 100644 index 0000000000000000000000000000000000000000..0a85c82a3ccf8ed31585c07c38e167274f444341 --- /dev/null +++ b/app/src/style.css @@ -0,0 +1,384 @@ +:root { + font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + font-size: 13px; + font-synthesis: none; + color-scheme: dark; + color: var(--text); + background: var(--background); + --background: #18181e; + --surface: #1e1e24; + --panel: #22222b; + --control: #282832; + --hover: #343541; + --selected: #3a3a4a; + --line: #393942; + --line-strong: #50505c; + --text: #d4d4d4; + --muted: #b0b0bd; + --accent: #8abeb7; + --surface-inset: 8px; + --radius-small: 8px; + --radius: calc(var(--radius-small) + var(--surface-inset)); + --radius-large: calc(var(--radius) + var(--surface-inset)); + --content-width: 1800px; + --content-gutter: 14px; + --header-inset: 12px; + --header-control-height: 32px; + --header-height: calc(var(--header-control-height) + 2 * var(--surface-inset)); + scrollbar-color: var(--line-strong) var(--background); +} + +* { box-sizing: border-box; } +body { margin: 0; } +button, input, textarea { font: inherit; color: inherit; } +::selection { background: var(--selected); color: var(--text); } +input::placeholder, textarea::placeholder { color: var(--muted); opacity: 1; } +button, .button { + cursor: pointer; + min-height: 28px; + padding: 5px 9px; + border: 1px solid transparent; + border-radius: var(--radius-small); + background: var(--control); + color: inherit; + font-size: 12px; + line-height: 1.4; + white-space: nowrap; +} +button:hover, .button:hover { background: var(--hover); } +button:disabled { opacity: .45; cursor: default; } +.primary { background: var(--hover); color: var(--text); } +.primary:hover { background: var(--selected); } +#send.has-input:not(:disabled) { background: #fff; color: #18181e; } +#send.has-input:not(:disabled):hover { background: #e8e8ed; } +.quiet { border-color: transparent; background: transparent; font-size: 11px; } +textarea, input { outline: none; } +textarea:focus, input:focus { box-shadow: inset 0 0 0 1px var(--accent); } +button:focus-visible, .button:focus-visible, summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +[hidden] { display: none !important; } + +header { + width: calc(100% - 2 * var(--content-gutter)); + max-width: calc(var(--content-width) - 2 * var(--content-gutter)); + height: var(--header-height); + margin: var(--header-inset) auto 0; + position: relative; + display: grid; + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); + align-items: center; + justify-content: space-between; + padding: var(--surface-inset); + gap: var(--surface-inset) 16px; + background: var(--surface); + border-radius: var(--radius); + overflow: hidden; +} +.brand { display: flex; gap: 8px; align-items: center; text-decoration: none; color: inherit; font-size: 15px; font-weight: 600; } +.pi-logo { display: block; width: 18px; height: 18px; flex: none; } +.brand { justify-self: start; padding: 0 4px; } +.runtime-meter { --runtime-padding: 10px; display: flex; align-items: center; justify-self: center; width: max-content; max-width: 100%; height: var(--header-control-height); padding: 5px var(--runtime-padding); border-radius: var(--radius-small); background: var(--control); font-size: 11px; white-space: nowrap; overflow: clip; transition: width 220ms cubic-bezier(.2, .8, .2, 1); } +.runtime-content { display: flex; align-items: center; gap: 8px; width: max-content; height: 100%; flex: none; } +.runtime-location { display: flex; align-items: center; gap: 6px; flex: none; } +.runtime-dot { width: 5px; height: 5px; border-radius: 50%; background: var(--muted); } +.runtime-meter[data-state="generating"] .runtime-dot, .runtime-meter[data-state="tool"] .runtime-dot { background: var(--accent); } +.runtime-meter[data-state="error"] .runtime-dot { background: #d98c8c; } +.runtime-divider { align-self: stretch; flex: 0 0 1px; background: var(--line); margin: 2px 0; } +.runtime-sparkline { flex: none; color: var(--accent); } +.runtime-value { flex: none; color: var(--muted); font-variant-numeric: tabular-nums; } +.runtime-meter[data-state="generating"] .runtime-value { color: var(--accent); } +@media (prefers-reduced-motion: reduce) { .runtime-meter { transition: none; } } + +main { --conversation-min: 420px; --workspace-min: 370px; display: grid; grid-template-columns: minmax(var(--conversation-min), var(--conversation-width, 1.20482fr)) 0 minmax(var(--workspace-min), 1fr); height: calc(100dvh - var(--header-height) - var(--header-inset)); max-width: var(--content-width); margin: auto; } +.column-resizer { position: relative; left: calc(-1 * var(--content-gutter)); z-index: 2; display: flex; align-items: center; justify-content: center; width: var(--content-gutter); margin: 12px 0 8px; cursor: col-resize; touch-action: none; user-select: none; -webkit-tap-highlight-color: transparent; outline: none; } +.column-resizer::after { content: ''; width: 3px; height: 44px; flex: none; border-radius: 999px; background: var(--line-strong); transition: background-color 120ms; } +.column-resizer:hover::after { background: var(--text); } +.column-resizer:focus-visible::after { background: var(--accent); outline: 2px solid var(--accent); outline-offset: 4px; } +.is-resizing-columns, .is-resizing-columns * { cursor: col-resize !important; user-select: none !important; } +.is-resizing-columns .column-resizer::after { background: var(--accent); } +@media (prefers-reduced-motion: reduce) { .column-resizer::after { transition: none; } } +@media (forced-colors: active) { .column-resizer::after { background: ButtonText; } } +.conversation { display: flex; flex-direction: column; min-height: 0; min-width: 0; padding: 12px var(--content-gutter) 8px; } +.model-panel { margin-left: auto; background: var(--surface); } +.model-heading { display: flex; justify-content: space-between; align-items: center; gap: 8px; } +.model-heading > div { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.model-heading strong { font-size: 12px; font-weight: 600; } +.header-model-source { display: inline-flex; align-items: center; gap: 6px; flex: none; color: inherit; text-decoration: none; white-space: nowrap; border-radius: 3px; } +.header-model-source img { display: block; width: 16px; height: 16px; flex: none; border-radius: 50%; } +.header-model-source:hover { color: var(--accent); } +.header-model-source:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } +.badge { padding: 3px 7px; border-radius: var(--radius-small); background: var(--control); color: var(--muted); font-size: 10px; } +#load { min-width: 90px; height: var(--header-control-height); flex-shrink: 0; } +#load.is-loaded { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-width: 0; min-height: 28px; height: 28px; padding: 4px 8px; border-radius: 6px; opacity: 1; color: var(--accent); background: #25312f; } +#load.is-loaded::before { content: ''; width: 5px; height: 5px; flex: none; border-radius: 50%; background: currentColor; } +progress { width: 100%; height: 5px; margin-top: 8px; accent-color: var(--accent); } +header #progress { position: absolute; bottom: 3px; left: var(--radius); width: calc(100% - 2 * var(--radius)); margin: 0; height: 2px; border: 0; border-radius: 999px; overflow: hidden; appearance: none; background: var(--line); } +header #progress { --progress-fade: clamp(24px, 5vw, 72px); --progress-mask: linear-gradient(90deg, transparent 2px, #000 var(--progress-fade), #000 calc(100% - var(--progress-fade)), transparent calc(100% - 2px)); mask-image: var(--progress-mask); -webkit-mask-image: var(--progress-mask); } +header #progress::-webkit-progress-bar { border-radius: 999px; background: var(--line); } +header #progress::-webkit-progress-value { border-radius: 999px; background: var(--accent); } +header #progress::-moz-progress-bar { border-radius: 999px; background: var(--accent); } +header #progress:indeterminate { background: linear-gradient(90deg, transparent, var(--accent), transparent) 0 0 / 35% 100% no-repeat var(--line); animation: header-progress 1.4s ease-in-out infinite alternate; } +header #progress:indeterminate::-webkit-progress-bar { background: transparent; } +header #progress:indeterminate::-webkit-progress-value { background: transparent; } +header #progress:indeterminate::-moz-progress-bar { background: transparent; } +@keyframes header-progress { from { background-position: 0 0; } to { background-position: 100% 0; } } +@media (prefers-reduced-motion: reduce) { header #progress:indeterminate { animation: none; background-position: 50% 0; } } +.muted { margin-top: 4px; color: var(--muted); font-size: 11px; } +.muted:empty { display: none; } + +.terminal-panel { display: flex; flex-direction: column; flex: 1; min-height: 0; padding: 8px; border: 1px solid transparent; background: var(--background); border-radius: var(--radius-large); } +@media (min-width: 851px) { .terminal-panel { padding-right: 0; } } +#pi-terminal { position: relative; isolation: isolate; flex: 1; min-height: 120px; min-width: 0; overflow: hidden; background: var(--background); } +#pi-terminal .pi-terminal-mount, #pi-terminal .xterm { height: 100%; } +#pi-terminal .xterm-viewport { background-color: var(--background) !important; } +#pi-terminal textarea:focus { box-shadow: none; } +.terminal-paws { position: absolute; overflow: hidden; pointer-events: none; user-select: none; } +.terminal-paws i { position: absolute; width: 24px; height: 24px; background: var(--muted); mask: url('../public/paw-print.svg') center / contain no-repeat; opacity: 0; transform: rotate(28deg); } +.terminal-paws:not([hidden]) i { animation: terminal-paw 3.2s ease-in-out both; animation-delay: var(--delay); } +.terminal-paws i:nth-child(1) { left: calc(18% + var(--trail-shift)); top: 85%; --delay: 0s; } +.terminal-paws i:nth-child(2) { left: calc(26% + var(--trail-shift)); top: 78%; --delay: .65s; } +.terminal-paws i:nth-child(3) { left: calc(27% + var(--trail-shift)); top: 68%; --delay: 1.3s; } +.terminal-paws i:nth-child(4) { left: calc(35% + var(--trail-shift)); top: 61%; --delay: 1.95s; } +.terminal-paws i:nth-child(5) { left: calc(36% + var(--trail-shift)); top: 51%; --delay: 2.6s; } +.terminal-paws i:nth-child(6) { left: calc(44% + var(--trail-shift)); top: 44%; --delay: 3.25s; } +@keyframes terminal-paw { 0%, 100% { opacity: 0; } 15%, 40% { opacity: .14; } } +@media (max-width: 600px) { .terminal-paws i { width: 18px; height: 18px; } } +@media (prefers-reduced-motion: reduce) { .terminal-paws { display: none; } } +.empty-mascot { position: absolute; right: 12px; display: flex; flex-direction: column; align-items: flex-end; gap: 10px; width: 196px; max-width: calc(100% - 24px); pointer-events: none; } +/* Keep blending on a composited layer between hops, including in WebKit. */ +.mascot-cat { position: relative; display: block; flex: none; min-height: 0; padding: 0; border: 0; border-radius: 0; background: transparent; line-height: 0; pointer-events: auto; cursor: pointer; mix-blend-mode: lighten; transform: translate3d(0, 0, 0); } +.mascot-cat:hover { background: transparent; } +.mascot-cat, .setup-cat { outline: none; -webkit-tap-highlight-color: transparent; -webkit-touch-callout: none; } +.mascot-cat, .mascot-cat *, .setup-cat, .setup-cat * { -webkit-user-select: none; user-select: none; -webkit-user-drag: none; } +.mascot-cat > *, .setup-cat > * { pointer-events: none; } +.empty-mascot img { display: block; width: 100%; height: 100%; object-fit: contain; image-rendering: pixelated; user-select: none; } +.mascot-eyelids { position: absolute; inset: 0; opacity: 0; } +/* Pixel eyelids align with the eyes in empty-cat-v1.png; the image stays intact. */ +.mascot-eyelids::before, .mascot-eyelids::after { content: ''; position: absolute; top: 39.3%; width: 7%; height: 7.4%; background: linear-gradient(to bottom, #f6f0e1 70%, var(--background) 70%, var(--background) 86%, #f6f0e1 86%); } +.mascot-eyelids::before { left: 28.5%; } +.mascot-eyelids::after { left: 54%; } +.mascot-suggestion { position: relative; pointer-events: auto; padding: 10px 12px; border: 0; border-radius: 8px; background: #f5efdf; color: #24242c; font: 12px/1.45 ui-monospace, SFMono-Regular, Consolas, monospace; text-align: left; white-space: normal; box-shadow: 0 3px 0 #0c0c10; } +.mascot-suggestion::after { content: ''; position: absolute; right: 52px; bottom: -8px; width: 12px; height: 8px; background: inherit; clip-path: polygon(0 0, 100% 0, 100% 50%, 50% 50%, 50% 100%, 0 100%); } +.mascot-suggestion:hover { background: #fffaf0; } +.terminal-controls { display: flex; justify-content: flex-end; align-items: center; gap: 8px; padding-top: 4px; } +.terminal-controls, .terminal-panel > footer { cursor: text; } +#new-chat { margin-right: auto; } +#newline:not(:hover) { background: transparent; } +#notice { margin: 6px 0; padding: 8px 10px; border-radius: var(--radius-small); background: var(--control); font-size: 12px; } + +footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding-top: 8px; color: var(--muted); font-size: 10px; } + +.workspace { display: flex; flex-direction: column; min-width: 0; min-height: 0; margin: 12px var(--content-gutter) 8px 0; border-radius: 20px; overflow: hidden; background: var(--panel); } +.workspace-heading { display: flex; align-items: center; justify-content: space-between; min-height: 40px; padding: 5px 10px; } +.workspace-heading h2 { margin: 0; font-size: 12px; font-weight: 600; } +.workspace-heading > div { display: flex; gap: 0; } +.button { display: inline-block; } +.file-area { display: grid; grid-template-columns: 140px minmax(0, 1fr); flex: 1; min-height: 180px; } +#files { overflow: auto; padding: 5px 4px; } +#files button { display: flex; align-items: center; gap: 6px; width: 100%; padding: 5px 7px; border: none; border-radius: var(--radius-small); background: transparent; text-align: left; white-space: normal; overflow-wrap: anywhere; font-family: ui-monospace, monospace; font-size: 11px; line-height: 1.45; } +.file-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.file-icon { display: inline-block; flex: 0 0 16px; width: 16px; height: 16px; background-color: var(--file-color); mask: var(--file-icon) center / 90% 90% no-repeat; -webkit-mask: var(--file-icon) center / 90% 90% no-repeat; } +.editor-file { display: flex; align-items: center; gap: 6px; min-width: 0; } +#filetype { display: flex; flex: none; } +#filetype:empty { display: none; } +@media (forced-colors: active) { .file-icon { background-color: CanvasText; } } +#files button:hover { background: var(--hover); } +#files button.selected { background: var(--selected); color: var(--text); } +.editor-area { display: flex; flex-direction: column; min-width: 0; min-height: 0; margin: 0 8px 8px 0; border-radius: var(--radius); overflow: hidden; background: var(--surface); } +.editor-heading { display: flex; align-items: center; justify-content: space-between; height: 32px; padding: 0 6px 0 10px; gap: 6px; background: #282832; transition: background-color 140ms, box-shadow 140ms; } +.editor-area:focus-within .editor-heading { background: #30323a; box-shadow: inset 0 -1px 0 #8abeb74d; } +@media (prefers-reduced-motion: reduce) { .editor-heading { transition: none; } } +@media (forced-colors: active) { .editor-area:focus-within .editor-heading { outline: 1px solid Highlight; outline-offset: -1px; } } +#filename { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, monospace; font-size: 11px; } +.editor-heading { flex-shrink: 0; } +.editor-input { flex: 1; position: relative; min-height: 140px; min-width: 0; overflow: hidden; } +#editor, #editor-highlight { position: absolute; top: 0; left: 0; width: 100%; height: 100%; margin: 0; padding: 10px 12px; border: 0; border-radius: 0; color: var(--text); font: 12px/1.6 ui-monospace, SFMono-Regular, Consolas, monospace; font-variant-ligatures: none; letter-spacing: normal; tab-size: 2; white-space: pre; overflow-wrap: normal; } +#editor { resize: none; background: transparent; overflow: auto; caret-color: var(--text); } +#editor-highlight { visibility: hidden; overflow: hidden; pointer-events: none; } +.is-highlighted #editor-highlight { visibility: visible; } +.is-highlighted #editor, .is-highlighted #editor::selection { color: transparent; } +#editor::selection { background: #8abeb740; } +#editor:focus { box-shadow: none; } +#editor-highlight .token { font-style: normal; font-weight: normal; } +#editor-highlight .token.comment, #editor-highlight .token.prolog, #editor-highlight .token.doctype { color: #9292a3; } +#editor-highlight .token.punctuation { color: #b0b0bd; } +#editor-highlight .token.tag, #editor-highlight .token.deleted { color: #e29a9a; } +#editor-highlight .token.keyword, #editor-highlight .token.selector, #editor-highlight .token.important { color: #c4a7d5; } +#editor-highlight .token.string, #editor-highlight .token.attr-value, #editor-highlight .token.inserted { color: #b5bd68; } +#editor-highlight .token.function, #editor-highlight .token.builtin, #editor-highlight .token.class-name { color: #8abeb7; } +#editor-highlight .token.attr-name, #editor-highlight .token.property, #editor-highlight .token.variable { color: #9db9d4; } +#editor-highlight .token.number, #editor-highlight .token.boolean, #editor-highlight .token.constant, #editor-highlight .token.operator, #editor-highlight .token.entity, #editor-highlight .token.url { color: #f0c674; } +@media (forced-colors: active) { .is-highlighted #editor-highlight { visibility: hidden; } .is-highlighted #editor, .is-highlighted #editor::selection { color: CanvasText; } } + +.workspace > .terminal { flex-shrink: 0; margin: 0 8px; padding: 0 8px 8px; border-radius: var(--radius); background: var(--background); } +.terminal summary { padding: 6px 0; cursor: pointer; font-size: 11px; font-weight: 500; } +.terminal summary span { float: right; color: var(--muted); font-size: 10px; font-weight: 400; } +.shell-toolbar { display: flex; align-items: center; justify-content: space-between; color: var(--accent); font: 11px/1.5 ui-monospace, monospace; } +.shell-toolbar button { color: var(--muted); } +#terminal-output { height: 132px; min-height: 84px; max-height: min(480px, 45dvh); margin: 0 0 6px; padding: 2px 0; resize: vertical; overflow: auto; scrollbar-width: thin; font: 12px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace; overflow-wrap: anywhere; } +#terminal-output:focus-visible { outline: 1px solid var(--accent); outline-offset: 2px; border-radius: var(--radius-small); } +.shell-empty { display: flex; flex-direction: column; gap: 4px; padding: 8px 2px; color: var(--muted); } +.shell-empty strong { font-weight: 500; color: var(--text); } +.shell-empty code { color: var(--accent); } +.shell-entry { padding: 8px; margin-bottom: 6px; border-radius: var(--radius-small); background: var(--surface); } +.shell-entry:last-child { margin-bottom: 0; } +.shell-entry-heading { display: flex; gap: 8px; align-items: baseline; } +.shell-entry pre { margin: 0; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } +.shell-code { flex: 1; min-width: 0; } +.shell-status { flex-shrink: 0; font-size: 10px; color: var(--muted); } +.shell-status.success { color: #b5bd68; } +.shell-status.error, .shell-stderr { color: #e29a9a; } +.shell-entry .shell-stdout, .shell-entry .shell-stderr { margin: 6px 0 0 16px; } +#shell-form { display: flex; align-items: flex-start; gap: 8px; padding: 4px; border-radius: var(--radius-small); background: var(--control); font-family: ui-monospace, SFMono-Regular, Consolas, monospace; } +#shell-form:focus-within { box-shadow: 0 0 0 1px var(--accent); } +.shell-prompt { flex-shrink: 0; color: var(--accent); } +#shell-form > .shell-prompt { padding-top: 6px; line-height: 20px; } +.shell-input { flex: 1; position: relative; min-width: 0; } +#command, #command-highlight { width: 100%; margin: 0; padding: 6px 0; border: 0; border-radius: 0; font: 12px/20px ui-monospace, SFMono-Regular, Consolas, monospace; font-variant-ligatures: none; letter-spacing: normal; tab-size: 2; white-space: pre-wrap; overflow-wrap: anywhere; } +#command-highlight { position: absolute; inset: 0; pointer-events: none; overflow: hidden; } +#command { position: relative; display: block; min-height: 32px; max-height: 104px; resize: none; background: transparent; color: transparent; caret-color: var(--text); scrollbar-width: thin; } +#command:focus { box-shadow: none; } +#command::selection { color: transparent; background: #8abeb740; } +#command::placeholder { color: var(--muted); } +#shell-run { min-height: 32px; border-radius: 4px; } +#shell-hint { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 2px 12px; padding-top: 5px; color: var(--muted); font-size: 10px; line-height: 1.5; } +.shell-code .token, #command-highlight .token { font-style: normal; font-weight: normal; } +.shell-code .token.comment, #command-highlight .token.comment { color: #aaaab7; } +.shell-code .token.string, #command-highlight .token.string { color: #b5bd68; } +.shell-code .token.function, .shell-code .token.builtin, #command-highlight .token.function, #command-highlight .token.builtin { color: #8abeb7; } +.shell-code .token.variable, .shell-code .token.assign-left, #command-highlight .token.variable, #command-highlight .token.assign-left { color: #c4a7d5; } +.shell-code .token.keyword, .shell-code .token.operator, .shell-code .token.number, #command-highlight .token.keyword, #command-highlight .token.operator, #command-highlight .token.number { color: #f0c674; } +.shell-code .token.parameter, #command-highlight .token.parameter { color: #9db9d4; } +@media (forced-colors: active) { #command-highlight { display: none; } #command, #command::selection { color: CanvasText; } } +.workspace-note { margin: 6px 10px; color: var(--muted); font-size: 10px; line-height: 1.45; } +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; } + +#open-tab { margin-top: 8px; font-size: 12px; color: var(--accent); text-decoration: none; white-space: normal; } + +#model-dialog { --dialog-inset: 24px; --cat-size: 152px; --cat-rise: calc(var(--cat-size) * .58); width: min(460px, calc(100% - 32px)); max-height: calc(100dvh - 32px - var(--cat-rise)); overflow: visible; padding: var(--dialog-inset); border: 0; border-radius: calc(var(--radius-small) + var(--dialog-inset)); background: var(--surface); color: var(--text); box-shadow: 0 24px 80px #0008; transform: translateY(calc(var(--cat-rise) / 2)); } +#model-dialog[open] { display: flex; flex-direction: column; } +.setup-paws { --modal-half: min(230px, calc(50vw - 16px)); position: absolute; left: 50%; top: calc(50% - var(--cat-rise) / 2); width: 100vw; height: 100dvh; transform: translate(-50%, -50%); overflow: hidden; pointer-events: none; user-select: none; z-index: -1; } +.setup-paws i { position: absolute; width: 28px; height: 28px; background: var(--muted); mask: url('../public/paw-print.svg') center / contain no-repeat; opacity: 0; transform: rotate(var(--angle)); } +#model-dialog[open] .setup-paws i { animation: setup-paw 10s ease-in-out infinite; animation-delay: var(--delay); animation-play-state: var(--cat-play-state, running); } +.setup-paws i:nth-child(1) { left: calc(50% - var(--modal-half) - clamp(48px, 9vw, 136px)); top: 68%; --angle: -34deg; --delay: -1s; } +.setup-paws i:nth-child(2) { left: calc(50% - var(--modal-half) - clamp(30px, 6vw, 88px)); top: 60%; --angle: -24deg; --delay: -.3s; } +.setup-paws i:nth-child(3) { left: calc(50% - var(--modal-half) - clamp(45px, 8vw, 120px)); top: 52%; --angle: -12deg; --delay: .4s; } +.setup-paws i:nth-child(4) { left: calc(50% + var(--modal-half) + clamp(25px, 4vw, 64px)); top: 46%; --angle: 28deg; --delay: 4s; } +.setup-paws i:nth-child(5) { left: calc(50% + var(--modal-half) + clamp(50px, 8vw, 120px)); top: 38%; --angle: 35deg; --delay: 4.7s; } +.setup-paws i:nth-child(6) { left: calc(50% + var(--modal-half) + clamp(35px, 7vw, 100px)); top: 30%; --angle: 25deg; --delay: 5.4s; } +@keyframes setup-paw { 0%, 5%, 38%, 100% { opacity: 0; } 14%, 24% { opacity: .16; } } +@media (max-width: 600px) { + .setup-paws i { width: 18px; height: 18px; } + .setup-paws i:nth-child(1) { left: 8%; top: 22px; --angle: 65deg; } + .setup-paws i:nth-child(2) { left: 19%; top: 14px; --angle: 75deg; } + .setup-paws i:nth-child(3) { left: 30%; top: 22px; --angle: 65deg; } + .setup-paws i:nth-child(n+4) { display: none; } +} +@media (prefers-reduced-motion: reduce) { + #model-dialog[open] .setup-paws i { animation: none; } + .setup-paws i:nth-child(1), .setup-paws i:nth-child(2) { opacity: .1; } +} +.setup-cat { position: absolute; top: calc(-1 * var(--cat-rise)); right: var(--dialog-inset); width: var(--cat-size); height: calc(var(--cat-size) * .66); overflow: hidden; pointer-events: auto; cursor: pointer; touch-action: manipulation; user-select: none; } +.setup-cat img, .setup-cat-tail, .setup-cat-eyelids { display: block; position: absolute; top: calc(var(--cat-size) * -.23); left: 0; width: 100%; height: auto; image-rendering: pixelated; opacity: 0; } +/* Split the existing sprite at the tail, keeping its root behind the right paw. */ +.setup-cat img { clip-path: inset(0 22% 0 0); } +.setup-cat-tail { aspect-ratio: 1; background: var(--cat-sprite) 0 0 / 100% 100% no-repeat; clip-path: polygon(78% 40%, 100% 40%, 100% 82%, 77% 82%, 77% 77%, 78% 77%); transform-origin: 78% 80%; } +.setup-cat.is-ready img, .setup-cat.is-ready .setup-cat-tail { opacity: 1; } +.setup-cat-eyelids { aspect-ratio: 1; } +/* Leave a small margin around the eyes for pixelated image scaling. */ +.setup-cat-eyelids::before, .setup-cat-eyelids::after { content: ''; position: absolute; top: 55.6%; width: 8.4%; height: 8.7%; background: linear-gradient(#080709, #080709) center 80% / 78% 14% no-repeat, #f6efdf; } +.setup-cat-eyelids::before { left: 28%; } +.setup-cat-eyelids::after { left: 54.3%; } +#model-dialog[open] .setup-cat.is-ready .setup-cat-tail { animation: setup-tail-swish 9s ease-in-out infinite; animation-play-state: var(--cat-play-state, running); } +#model-dialog[open] .setup-cat.is-ready .setup-cat-eyelids { animation: setup-cat-blink 7.4s step-end infinite; animation-play-state: var(--cat-play-state, running); } +@keyframes setup-cat-blink { + 0%, 45%, 100% { opacity: 0; } + 43% { opacity: 1; } +} +@keyframes setup-tail-swish { + 0%, 24%, 50%, 100% { transform: rotate(0deg); } + 33% { transform: rotate(-4deg); } + 41% { transform: rotate(2.5deg); } + 46% { transform: rotate(-.6deg); } +} +@media (prefers-reduced-motion: reduce) { #model-dialog[open] .setup-cat.is-ready .setup-cat-tail, #model-dialog[open] .setup-cat.is-ready .setup-cat-eyelids { animation: none; } } +.setup-heading { display: flex; flex-shrink: 0; align-items: flex-start; gap: 8px; } +#model-cancel { display: grid; place-items: center; flex: none; width: 32px; height: 32px; min-height: 32px; padding: 0; background: transparent; color: var(--muted); } +#model-cancel:hover:not(:disabled) { background: var(--control); color: var(--text); } +.setup-body { min-height: 0; overflow: auto; } +#model-dialog::backdrop { background: #08080dbd; backdrop-filter: blur(4px); } +#model-title { flex: 1; min-width: 0; margin: 0 0 8px; font-size: 27px; line-height: 1.2; letter-spacing: -.5px; font-weight: 650; } +#model-description { margin: 0; line-height: 1.6; color: var(--muted); } +.setup-runtime { display: grid; grid-template-columns: minmax(max-content, 1fr) 1fr 1.2fr; gap: 8px; margin: 18px 0; } +.setup-runtime > div { padding: 10px; border-radius: var(--radius-small); background: var(--control); } +.setup-runtime dt { color: var(--accent); font-size: 12px; font-weight: 600; } +.setup-runtime dd { margin: 5px 0 0; font-size: 11px; line-height: 1.5; } +.setup-model { display: flex; align-items: center; gap: 6px; } +.model-org { display: inline-flex; flex: none; border-radius: 50%; } +.model-org img { display: block; width: 18px; height: 18px; border-radius: inherit; } +.model-source { color: inherit; text-decoration-color: var(--muted); text-underline-offset: 3px; white-space: nowrap; } +.model-source:hover { color: var(--accent); } +.setup-model a:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 3px; } +.setup-facts { display: flex; flex-direction: column; gap: 5px; margin: 18px 0; padding: 12px; border-radius: var(--radius-small); background: var(--panel); line-height: 1.45; } +.setup-facts strong { font-size: 12px; font-weight: 600; } +.setup-facts span, .setup-label { font-size: 11px; color: var(--muted); line-height: 1.5; } +.setup-label { margin: 16px 0 6px; } +#model-preview { max-height: 84px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; padding: 10px 12px; border-radius: var(--radius-small); background: var(--control); font-size: 12px; line-height: 1.5; } +#model-error { padding: 10px 12px; background: #3c2828; border-radius: var(--radius-small); line-height: 1.5; overflow-wrap: anywhere; } +#model-open-tab { color: var(--accent); white-space: normal; text-decoration: none; } +.setup-credits { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin: 18px 0; color: var(--muted); font-size: 11px; line-height: 1.6; } +.setup-credits a { display: inline-flex; align-items: center; gap: 4px; color: inherit; white-space: nowrap; text-decoration: none; } +.setup-credits a:hover { color: var(--text); text-decoration: underline; text-underline-offset: 3px; } +.setup-credits a:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 3px; } +.setup-credits img, .setup-credits svg { flex: none; width: 14px; height: 14px; object-fit: contain; } +.setup-credits .credit-pi { padding: 2px; } +.setup-actions { display: flex; flex-shrink: 0; padding-top: 4px; } +.setup-actions button { width: 100%; min-height: 44px; padding: 10px 16px; } +#model-confirm { background: #fff; color: #18181e; font-size: 14px; font-weight: 600; } +#model-confirm:hover { background: #e8e8ed; } +@media (max-width: 420px) { + #model-dialog { --dialog-inset: 16px; --cat-size: 116px; } + #model-title { font-size: 24px; } + .setup-runtime { grid-template-columns: 1fr; gap: 5px; margin: 14px 0; } + .setup-runtime > div { display: flex; align-items: baseline; gap: 12px; padding: 8px 10px; } + .setup-runtime dt { flex: 0 0 64px; } + .setup-runtime dd { margin: 0; } + .setup-facts { margin: 14px 0; } + .setup-credits { margin: 12px 0; } +} +@media (min-width: 851px) and (max-width: 1000px) { + header { grid-template-columns: auto minmax(0, 1fr) auto; } +} +@media (max-height: 620px) { + #model-dialog { --cat-size: 72px; } + .setup-runtime, .setup-facts { margin: 12px 0; } +} +@media (max-width: 420px) and (max-height: 620px) { + .setup-runtime { grid-template-columns: minmax(0, 1fr) max-content; } + .setup-runtime > div:first-child { grid-column: 1 / -1; } + .setup-runtime > div:not(:first-child) { display: block; padding: 6px 10px; } + .setup-runtime > div:not(:first-child) dd { margin-top: 2px; } +} +@media (max-width: 850px) { + :root { --header-height: calc(2 * var(--header-control-height) + 3 * var(--surface-inset)); --header-inset: 10px; --content-gutter: 10px; } + header { grid-template-columns: auto minmax(0, 1fr); grid-template-rows: repeat(2, var(--header-control-height)); grid-template-areas: 'brand runtime' 'model model'; gap: var(--surface-inset); } + .brand { grid-area: brand; justify-self: start; } + .runtime-meter { grid-area: runtime; justify-self: end; } + .model-panel { grid-area: model; margin: 0; } + main { display: flex; flex-direction: column; height: auto; } + .column-resizer { display: none; } + .conversation { height: calc(100dvh - var(--header-height) - var(--header-inset)); min-height: 320px; padding: 10px var(--content-gutter); } + .workspace { min-height: 520px; margin: 0 var(--content-gutter) 10px; } + .file-area { min-height: 280px; grid-template-columns: 115px minmax(0, 1fr); } + h1 { font-size: 20px; } + .badge { font-size: 9px; } + footer { font-size: 9px; } +} + +@media (pointer: coarse) { + :root { --header-control-height: 38px; } + button, .button, #files button { min-height: 38px; } + .editor-heading { min-height: 40px; } + .terminal summary { padding-top: 11px; padding-bottom: 11px; } + #command, #command-highlight { font-size: 16px; } + #pi-terminal .xterm-helper-textarea { font-size: 16px; } +} diff --git a/app/src/token-rate.mjs b/app/src/token-rate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..614ffced0a38a1c28d7859b7e484d7febb06e103 --- /dev/null +++ b/app/src/token-rate.mjs @@ -0,0 +1,28 @@ +// Decode throughput over a rolling second. The first token establishes the +// baseline, so prompt processing and first-token latency are not counted. +export class TokenRateWindow { + constructor(windowMs = 1000, minimumMs = 250) { + this.windowMs = windowMs; + this.minimumMs = minimumMs; + this.total = 0; + this.firstAt = null; + this.points = []; + } + add(count, at) { + if (!(count > 0)) return; + this.firstAt ??= at; + this.total += count; + this.points.push({ at, total: this.total }); + this.prune(at); + } + prune(at) { + const cutoff = at - this.windowMs; + while (this.points.length > 1 && this.points[1].at <= cutoff) this.points.shift(); + } + rate(at) { + if (this.firstAt === null || at - this.firstAt < this.minimumMs) return null; + this.prune(at); + const elapsed = Math.min(this.windowMs, at - this.firstAt); + return (this.total - this.points[0].total) * 1000 / elapsed; + } +} diff --git a/app/src/workspace.mjs b/app/src/workspace.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db2d1f01340228f7c5bbc4d995070cb81bec4524 --- /dev/null +++ b/app/src/workspace.mjs @@ -0,0 +1,108 @@ +import { Bash } from 'just-bash/browser'; +import { Type } from '@earendil-works/pi-ai'; +import { createBrowserFetch, HTTP_ORIGINS } from './browser-http.mjs'; + +// Frozen previous starter data, used only to recognize an unmodified demo. +export const legacyProductsCsv = 'product,unit_cost,stock\nNotebook,2.50,24\nPencil,0.50,120\nFolder,1.20,18\nEraser,0.35,40\nStapler,2.75,9\nRuler,0.80,30\n'; +export const legacyWorkspaceReadme = '# Browser workspace\n\nPi can read, write, edit, and run shell commands here.\nEverything stays in this browser. Explore our sales, product costs, and stock levels.\n'; +export const legacyProductsJson = JSON.stringify([ + { product: 'Notebook', unit_cost: 2.50, stock: 24 }, + { product: 'Pencil', unit_cost: 0.50, stock: 120 }, + { product: 'Folder', unit_cost: 1.20, stock: 18 }, + { product: 'Eraser', unit_cost: 0.35, stock: 40 }, + { product: 'Stapler', unit_cost: 2.75, stock: 9 }, + { product: 'Ruler', unit_cost: 0.80, stock: 30 }, +], null, 2) + '\n'; +export const legacyCostProductsJson = JSON.stringify(JSON.parse(legacyProductsJson).map(({ product, unit_cost }) => ({ product, unit_cost })), null, 2) + '\n'; +export const legacySalesCsv = 'product,units,price\nNotebook,12,5\nPencil,30,2\nFolder,8,3\n'; +export const legacyProfitReadme = '# Browser workspace\n\nSales and product costs for a small shop.\nPrices and unit costs are in USD.\nProfit means revenue minus the cost of units sold,\nbefore tax and other operating expenses.\n\nPi can read, edit, and run shell commands here.\nEverything stays in this browser.\n'; +export const initialFiles = { + '/workspace/README.md': '# Browser workspace\n\nYour files are saved in this browser.\n', + '/workspace/sales.csv': 'product,units\nNotebook,12\nPencil,30\nFolder,8\n', + '/workspace/products.json': JSON.stringify([ + { product: 'Notebook', price: 5 }, + { product: 'Pencil', price: 2 }, + { product: 'Folder', price: 3 }, + { product: 'Eraser', price: 1.5 }, + { product: 'Stapler', price: 4.99 }, + { product: 'Ruler', price: 2.5 }, + ], null, 2) + '\n', +}; +const limitText = text => text.length > 6000 ? text.slice(0, 6000) + '\n[Output truncated at 6,000 characters; use head, grep, or a narrower query.]' : text; +const result = (text, details = {}) => ({ content: [{ type: 'text', text: limitText(text) }], details }); + +export function createWorkspace(files = initialFiles, entries) { + if (entries) files = Object.fromEntries(entries.filter(([, entry]) => entry.type === 'file').map(([path, entry]) => [path, + { mode: entry.mode, content: Uint8Array.from(atob(entry.base64), c => c.charCodeAt(0)) }])); + const bash = new Bash({ files, cwd: '/workspace', executionLimitProfile: 'hardened', fetch: createBrowserFetch(), + executionLimits: { maxExecutionTimeMs: 10_000, maxCommandCount: 3000, + maxFileSystemBytes: 16 * 1024 ** 2, maxOutputSize: 256 * 1024, maxSourceBytes: 128 * 1024 }, + }); + const path = value => bash.fs.resolvePath('/workspace', value); + const ready = (async () => { + for (const [file, entry] of entries ?? []) { + if (entry.type === 'directory') { await bash.fs.mkdir(file, { recursive: true }); await bash.fs.chmod(file, entry.mode); } + else if (entry.type === 'symlink') await bash.fs.symlink(entry.target, file); + } + })(); + async function write(file, content) { + const resolved = path(file); + if (new TextEncoder().encode(content).length > 1024 ** 2) throw Error('The editor accepts files up to 1 MiB.'); + await bash.fs.mkdir(resolved.slice(0, resolved.lastIndexOf('/')) || '/', { recursive: true }); + await bash.fs.writeFile(resolved, content); + } + const tools = [{ + name: 'bash', label: 'Bash', description: `Run a bash command in /workspace. Supports cat, ls, grep, sed, awk, jq, sort, pipes, redirects, shell scripts, and curl/wget. HTTP GET/HEAD/POST is enabled for ${HTTP_ORIGINS.map(x => new URL(x).host).join(', ')}. Use curl -fsS URL; use set -o pipefail before piping HTTP output to jq. Browser CORS applies; redirects require the final URL. HTTP limits: 8 seconds, 1 MiB. No Node.js, Python, npm, or native binaries. Files persist across commands; cd and variables reset each call.`, + parameters: Type.Object({ command: Type.String({ description: 'The shell command to execute.' }) }), + execute: async (_id, { command }, signal) => { + const r = await bash.exec(command, { signal }); + return result(`${r.stdout}${r.stderr ? '\nSTDERR:\n' + r.stderr : ''}\nExit code: ${r.exitCode}`, { exitCode: r.exitCode }); + }, + }, { + name: 'read', label: 'Read file', description: 'Read a UTF-8 text file. Use bash head/grep for large files.', + parameters: Type.Object({ path: Type.String() }), + execute: async (_id, args) => { + const resolved = await bash.fs.realpath(path(args.path)); + return result(await bash.fs.readFile(resolved), { path: resolved }); + }, + }, { + name: 'write', label: 'Write file', description: 'Create or replace a UTF-8 text file. Parent directories are created.', + parameters: Type.Object({ path: Type.String(), content: Type.String() }), + execute: async (_id, args) => { await write(args.path, args.content); return result('Wrote ' + path(args.path)); }, + }, { + name: 'edit', label: 'Edit file', description: 'Replace one exact occurrence of oldText with newText in a UTF-8 file. oldText must match exactly once.', + parameters: Type.Object({ path: Type.String(), oldText: Type.String(), newText: Type.String() }), + execute: async (_id, args) => { + const content = await bash.fs.readFile(path(args.path)); + if (!args.oldText || content.split(args.oldText).length !== 2) throw Error('oldText must match exactly once. Read the file first.'); + await write(args.path, content.replace(args.oldText, () => args.newText)); + return result('Edited ' + path(args.path)); + }, + }]; + async function snapshot() { + const files = {}; + for (const file of bash.fs.getAllPaths().sort()) { + // Persist real files across the virtual FS, excluding built-in executable stubs. + if (file.startsWith('/bin/') || file.startsWith('/usr/bin/') || file.startsWith('/dev/') || file.startsWith('/proc/')) continue; + const stat = await bash.fs.lstat(file); + if (stat.isFile) files[file] = await bash.fs.readFile(file); + } + return files; + } + async function serialize() { + const entries = []; + for (const file of bash.fs.getAllPaths().sort()) { + if (['/bin', '/usr/bin', '/dev', '/proc'].some(root => file === root || file.startsWith(root + '/'))) continue; + const stat = await bash.fs.lstat(file); + if (stat.isSymbolicLink) entries.push([file, { type: 'symlink', target: await bash.fs.readlink(file) }]); + else if (stat.isDirectory) entries.push([file, { type: 'directory', mode: stat.mode }]); + else if (stat.isFile) { + const bytes = await bash.fs.readFileBuffer(file); let binary = ''; + for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768)); + entries.push([file, { type: 'file', base64: btoa(binary), mode: stat.mode }]); + } + } + return entries; + } + return { bash, tools, ready, write, snapshot, serialize, read: file => bash.fs.readFile(path(file)) }; +} diff --git a/app/tests/browser-http.test.mjs b/app/tests/browser-http.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0e755501910f9e1648ec5323208b52e3075fce61 --- /dev/null +++ b/app/tests/browser-http.test.mjs @@ -0,0 +1,57 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createBrowserFetch } from '../src/browser-http.mjs'; + +const endpoint = 'https://httpbin.org/get'; +test('HTTP preserves bytes/status and omits implicit credentials', async () => { + let request; + const fetch = createBrowserFetch({ transport: async (url, init) => { + request = { url, init }; + return new Response(Uint8Array.of(0, 128, 255), { status: 201, headers: { 'x-test': 'ok' } }); + } }); + const result = await fetch(endpoint, { method: 'POST', body: 'hello', headers: { 'Content-Type': 'text/plain' } }); + assert.deepEqual([...result.body], [0, 128, 255]); + assert.equal(result.status, 201); assert.equal(result.headers['x-test'], 'ok'); + assert.equal(request.init.credentials, 'omit'); assert.equal(request.init.redirect, 'manual'); + assert.equal(request.init.body, 'hello'); assert.equal(request.init.mode, 'cors'); +}); +test('Origin/method/URL credential checks happen before any request', async () => { + let calls = 0; + const fetch = createBrowserFetch({ transport: async () => { calls++; return new Response(''); } }); + for (const url of ['http://httpbin.org/get', 'https://httpbin.org.evil.test/', 'https://api.github.com@evil.test/', 'http://127.0.0.1/', 'https://example.com/']) { + await assert.rejects(fetch(url), /not enabled/); + } + await assert.rejects(fetch('https://user:pass@httpbin.org/get'), /Credentials/); + await assert.rejects(fetch(endpoint, { method: 'DELETE' }), /method DELETE/); + assert.equal(calls, 0); +}); +test('Opaque redirects cannot appear as successful empty responses', async () => { + const fetch = createBrowserFetch({ transport: async () => ({ type: 'opaqueredirect', status: 0 }) }); + await assert.rejects(fetch(endpoint, { followRedirects: true }), /final HTTPS URL/); + const opaque = createBrowserFetch({ transport: async () => ({ type: 'opaque', status: 0 }) }); + await assert.rejects(opaque(endpoint), /unreadable/); +}); +test('CORS/network failures are clear; HTTP error status is preserved for curl -f', async () => { + const fetch = createBrowserFetch({ transport: async () => { throw new TypeError('Failed to fetch'); } }); + await assert.rejects(fetch(endpoint), /CORS.*connection failed/); + const notFound = createBrowserFetch({ transport: async () => new Response('missing', { status: 404 }) }); + assert.equal((await notFound(endpoint)).status, 404); +}); +test('Response cap works for content-length and streaming bodies', async () => { + let cancelled = false; + const stream = () => new ReadableStream({ start(c) { c.enqueue(new Uint8Array(11)); }, cancel() { cancelled = true; } }); + const fetch = createBrowserFetch({ maxBytes: 10, transport: async () => new Response(stream()) }); + await assert.rejects(fetch(endpoint), /10-byte limit/); assert(cancelled); + const known = createBrowserFetch({ maxBytes: 10, transport: async () => new Response('abc', { headers: { 'Content-Length': '11' } }) }); + await assert.rejects(known(endpoint), /10-byte limit/); +}); +test('Timeout and explicit cancellation propagate and abort transport', async () => { + const transport = (_url, { signal }) => new Promise((_, reject) => { + signal.throwIfAborted(); signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }); + const fetch = createBrowserFetch({ transport, timeoutMs: 20 }); + await assert.rejects(fetch(endpoint), /timed out after 20 ms/); + const controller = new AbortController(); + const pending = fetch(endpoint, { signal: controller.signal }); controller.abort(); + await assert.rejects(pending, { name: 'AbortError' }); +}); diff --git a/app/tests/browser.mjs b/app/tests/browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b714d068840ab723b4c6574c8cd4d0a372583043 --- /dev/null +++ b/app/tests/browser.mjs @@ -0,0 +1,129 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +const base = process.argv[2] ?? process.env.APP_URL ?? 'http://127.0.0.1:4173/?source=local'; +const label = process.argv[3] ?? process.env.TEST_LABEL ?? 'agent-browser'; +const profile = process.env.BROWSER_PROFILE ?? new URL('../../validation/agent-browser-profile', import.meta.url).pathname; +const output = new URL(`../../validation/${label}.json`, import.meta.url); +const result = { date: new Date().toISOString(), url: base, cases: [], errors: [], requests: [] }; +const context = await chromium.launchPersistentContext(profile, { + executablePath: '/usr/bin/chromium', headless: true, viewport: { width: 1440, height: 1000 }, + args: ['--enable-unsafe-webgpu', '--use-angle=vulkan', '--enable-features=Vulkan', '--disable-vulkan-surface'], +}); +context.setDefaultTimeout(240_000); +try { + const page = await context.newPage(); + page.on('console', msg => { if (msg.type() === 'error') console.log('CONSOLE', msg.text().slice(0, 800)); }); + page.on('pageerror', e => { result.errors.push(e.message); console.log('PAGEERROR', e.message); }); + context.on('request', request => result.requests.push({ method: request.method(), url: request.url().split('?')[0] })); + await page.goto(base); + await page.waitForFunction(() => window.browserPi); + await page.evaluate(() => window.browserPi.ready); + console.log('INITIALIZED'); + await page.screenshot({ path: '../validation/agent-browser-initial.png' }); + const loadStart = Date.now(); + await page.locator('#load').click(); + if (process.env.TEST_CANCEL_LOAD) { + await page.waitForFunction(() => document.querySelector('#progress').value > 1); + await page.locator('#stop').click(); + await page.waitForFunction(() => !window.browserPi.busy); + assert.equal(await page.evaluate(() => window.browserPi.loaded), false); + result.loadCancellation = true; + await page.locator('#load').click(); + } + await page.waitForFunction(() => window.browserPi.loaded || (!window.browserPi.busy && document.querySelector('#notice').textContent)); + assert.equal(await page.evaluate(() => window.browserPi.loaded), true, await page.locator('#load-status').textContent()); + result.coldLoadMs = Date.now() - loadStart; + result.device = await page.evaluate(() => window.browserPi.diagnostics.device); + if (new URL(base).searchParams.has('limit128')) { + assert.equal(result.device.actualLimits.maxStorageBufferBindingSize, 128 * 1024 ** 2); + assert.equal(result.device.actualLimits.maxBufferSize, 256 * 1024 ** 2); + } + console.log('LOADED', result.coldLoadMs, result.device); + // Verify the whole agent/tool/follow-up loop without any network available. + await context.setOffline(true); + const inferenceRequestIndex = result.requests.length; + await page.evaluate(() => window.browserPi.rpc('shell', { command: 'rm -f /workspace/report.md /workspace/hello.sh /workspace/ui-test.txt /workspace/missing.txt' })); + const nonce = 'LOCAL-' + crypto.randomUUID().slice(0, 8); + await page.evaluate(({ nonce }) => window.browserPi.rpc('write', { path: '/workspace/secret.txt', content: nonce }), { nonce }); + const tasks = [ + { name: 'read-unseen-file', prompt: 'Read secret.txt with the read tool and tell me its exact contents.', check: state => { + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'read' && !m.isError)); + assert(state.messages.filter(m => m.role === 'assistant').at(-1).content.some(c => c.type === 'text' && c.text.includes(nonce))); + } }, + { name: 'analyze-and-write', prompt: 'Read sales.csv, calculate total revenue using bash, and save a short report to report.md. Verify the file.', check: state => { + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'bash' && !m.isError)); + assert.match(state.files['/workspace/report.md'] ?? '', /144/); + assert(state.messages.some(m => m.role === 'toolResult' && !m.isError && m.content.some(c => c.text?.includes('144')))); + } }, + { name: 'write-and-run-script', prompt: 'Create a bash script called hello.sh that prints Hello from the browser, run it, and report the output.', check: state => { + assert(state.files['/workspace/hello.sh']); + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'bash' && !m.isError && m.content.some(c => c.text?.includes('Hello from the browser')))); + } }, + { name: 'edit-and-verify', prompt: 'Read hello.sh, use the edit tool to replace Hello from the browser with Hello from Pi, then run the script and report the output.', check: state => { + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'edit' && !m.isError)); + assert.match(state.files['/workspace/hello.sh'], /Hello from Pi/); + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'bash' && !m.isError && m.content.some(c => c.text?.includes('Hello from Pi')))); + } }, + { name: 'recover-tool-error', prompt: 'Read missing.txt using the read tool. If it does not exist, create it with the exact text Recovered and verify it by reading the file.', check: state => { + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'read' && m.isError)); + assert.equal(state.files['/workspace/missing.txt'].trim(), 'Recovered'); + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'read' && !m.isError && m.content.some(c => c.text?.includes('Recovered')))); + } }, + ]; + for (const task of tasks) { + console.log('START', task.name); + await page.locator('#new-chat').click(); + await page.waitForFunction(() => !window.browserPi.busy); + const start = Date.now(); + await page.locator('.xterm-helper-textarea').focus(); + await page.keyboard.type(task.prompt); + console.log('TYPED', await page.evaluate(() => window.browserPi.terminal.text)); + await page.waitForFunction(prompt => window.browserPi.terminal.text === prompt, task.prompt, { timeout: 15_000 }); + await page.locator('#send').click(); + await page.waitForFunction(() => window.browserPi.busy); + await page.waitForFunction(() => !window.browserPi.busy); + const state = await page.evaluate(() => window.browserPi.rpc('snapshot')); + const entry = { name: task.name, elapsedMs: Date.now() - start, ...state }; + result.cases.push(entry); console.log('CASE', JSON.stringify(entry)); + task.check(state); + } + const beforeStop = await page.evaluate(() => window.browserPi.diagnostics.generations.length); + const running = page.evaluate(() => window.browserPi.prompt('Write a very long detailed tutorial about shell scripting. Do not use tools.')); + await page.waitForFunction(() => window.browserPi.busy); + await page.waitForTimeout(900); + await page.locator('.xterm-helper-textarea').focus(); + await page.keyboard.press('Escape'); + const stopped = await running; + assert.equal(stopped.messages.filter(m => m.role === 'assistant').at(-1).stopReason, 'aborted'); + result.cancellation = { passed: true, completedGenerations: await page.evaluate(() => window.browserPi.diagnostics.generations.length) - beforeStop }; + result.diagnostics = await page.evaluate(() => window.browserPi.diagnostics); + await page.locator('#upload').setInputFiles({ name: 'ui-test.txt', mimeType: 'text/plain', buffer: Buffer.from('Imported') }); + await page.waitForFunction(() => document.querySelector('#filename').textContent === '/workspace/ui-test.txt'); + await page.locator('#editor').fill('Edited through the file editor'); + await page.locator('#save').click(); await page.waitForFunction(() => !window.browserPi.busy && document.querySelector('#save').disabled); + await page.locator('#command').fill('cat ui-test.txt'); await page.locator('#shell-run').click(); + await page.waitForFunction(() => document.querySelector('#terminal-output').textContent.includes('Edited through the file editor')); + result.editorAndShell = true; + result.requestsDuringOfflineTasks = result.requests.slice(inferenceRequestIndex); + assert.equal(result.requestsDuringOfflineTasks.length, 0); + await page.screenshot({ path: `../validation/${label}-desktop.png`, fullPage: true }); + await context.setOffline(false); + const beforeReload = result.requests.length; + await page.reload(); await page.waitForFunction(() => window.browserPi); await page.evaluate(() => window.browserPi.ready); + const restored = await page.evaluate(() => window.browserPi.rpc('snapshot')); + assert.equal(restored.files['/workspace/secret.txt'], nonce); + assert.equal(restored.files['/workspace/ui-test.txt'], 'Edited through the file editor'); + assert(restored.files['/workspace/report.md']); assert(restored.messages.length > 0); + const warmStart = Date.now(); await page.evaluate(() => window.browserPi.load()); result.warmLoadMs = Date.now() - warmStart; + result.reloadWeightRequests = result.requests.slice(beforeReload).filter(r => r.url.includes('.onnx_data')); + assert.equal(result.reloadWeightRequests.length, 0); + await page.setViewportSize({ width: 390, height: 844 }); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + await page.screenshot({ path: `../validation/${label}-mobile-layout.png`, fullPage: true }); + result.mobileLayout = '390 × 844; desktop GPU, not a mobile hardware test'; + assert.equal(result.errors.length, 0); + result.passed = true; +} catch (error) { result.failure = error.stack; throw error; } +finally { await fs.writeFile(output, JSON.stringify(result, null, 2)); await context.close(); } diff --git a/app/tests/cached-start.mjs b/app/tests/cached-start.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f573a65eaf03f08bce6e60fdb2a2d51dbdf329e5 --- /dev/null +++ b/app/tests/cached-start.mjs @@ -0,0 +1,120 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/?source=local'; +const label = process.argv[3] ?? 'agent-cached-start'; +const revision = '04a6c49fcba3a65a0351c92644c3a7e9d4343059'; +const profile = new URL('../../validation/agent-browser-profile', import.meta.url).pathname; +const gpuArgs = ['--enable-unsafe-webgpu', '--use-angle=vulkan', '--enable-features=Vulkan', '--disable-vulkan-surface']; +const result = { date: new Date().toISOString(), url, checks: [], errors: [] }; +let context, page, receipts; +const requests = []; +async function open(args = gpuArgs) { + context = await chromium.launchPersistentContext(profile, { executablePath: '/usr/bin/chromium', headless: true, viewport: { width: 1440, height: 1000 }, args }); + context.setDefaultTimeout(180_000); + context.on('request', r => { if (/\/models\/|\/resolve\//.test(r.url())) requests.push(r.url()); }); + page = await context.newPage(); page.on('pageerror', e => result.errors.push(e.stack)); + await page.goto(url); await page.waitForFunction(() => window.browserPi?.terminal); await page.evaluate(() => window.browserPi.ready); + await page.evaluate(() => document.querySelector('#new-chat').onclick()); + await page.evaluate(() => { + window.dialogOpens = 0; + new MutationObserver(() => { if (document.querySelector('#model-dialog').open) window.dialogOpens++; }).observe(document.querySelector('#model-dialog'), { attributes: true, attributeFilter: ['open'] }); + }); +} +async function cacheReceipts(value) { + return page.evaluate(async ({ revision, value }) => { + const root = await (await navigator.storage.getDirectory()).getDirectoryHandle('pi-minicpm5-' + revision); + const handle = await root.getFileHandle('verified.json'); + if (value === undefined) return (await handle.getFile()).text(); + const stream = await handle.createWritable(); await stream.write(value); await stream.close(); + }, { revision, value }); +} +async function holdCacheLock() { + await page.evaluate(revision => { + window.lockHeld = false; + window.cacheLock = navigator.locks.request('pi-minicpm5-download-' + revision, async () => { + window.lockHeld = true; await new Promise(resolve => { window.releaseCacheLock = resolve; }); + }); + }, revision); + await page.waitForFunction(() => window.lockHeld); +} +async function releaseCacheLock() { await page.evaluate(async () => { window.releaseCacheLock?.(); await window.cacheLock; }); } +async function send(text) { + await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.press('Control+e'); await page.keyboard.press('Control+u'); + await page.keyboard.type(text); await page.locator('#send').click(); +} +async function restoredDraft(text) { + await page.waitForFunction(text => !window.browserPi.busy && !document.querySelector('#model-dialog').open && window.browserPi.terminal.text === text, text); +} +try { + await open(); + if (!await page.evaluate(() => window.browserPi.rpc('cache_status'))) { + await page.evaluate(() => window.browserPi.load()); + await context.close(); await open(); + } + receipts = await cacheReceipts(); + assert.equal(await page.evaluate(() => window.browserPi.loaded), false); + const task = 'Read cached-start.txt using the read tool and tell me its exact contents.'; + for (const invalid of ['{}', 'null', '{broken']) { + await cacheReceipts(invalid); + assert.equal(await page.evaluate(() => window.browserPi.rpc('cache_status')), false); + const before = requests.length; + await send(task); await page.locator('#model-dialog[open]').waitFor(); + assert.equal(requests.length, before); await page.locator('#model-cancel').click(); await restoredDraft(task); + } + await cacheReceipts(receipts); + result.checks.push('Incomplete or malformed verification receipts require confirmation without model requests'); + + await holdCacheLock(); + const beforeRace = requests.length; + await send(task); await page.locator('#stop').waitFor({ state: 'visible' }); + assert.equal(await page.locator('#model-dialog').evaluate(el => el.open), false); + await cacheReceipts('{}'); await releaseCacheLock(); + await page.locator('#model-dialog[open]').waitFor(); + assert.equal(requests.length, beforeRace); + await page.locator('#model-cancel').click(); await restoredDraft(task); await cacheReceipts(receipts); + result.checks.push('Cache invalidated after the initial check falls back to confirmation without fetching weights'); + + await holdCacheLock(); + const beforeCancel = await page.evaluate(() => window.dialogOpens); + await send(task); await page.locator('#stop').waitFor({ state: 'visible' }); + await page.locator('#stop').click(); await restoredDraft(task); await releaseCacheLock(); + assert.equal(await page.evaluate(() => window.dialogOpens), beforeCancel); + assert.equal((await page.evaluate(() => window.browserPi.rpc('snapshot'))).messages.length, 0); + result.checks.push('Stop cancels a queued cached restore, keeps the draft and opens no modal'); + + await context.close(); await open(['--disable-gpu', '--disable-software-rasterizer']); + await send(task); await page.locator('#model-dialog[open]').waitFor(); + assert.match(await page.locator('#model-error').textContent(), /WebGPU/); + assert.equal(await page.locator('#model-confirm').textContent(), 'Try again'); + await page.locator('#model-cancel').click(); await restoredDraft(task); + result.checks.push('A real GPU initialization failure offers retry and preserves the message'); + await context.close(); await open(); + + const nonce = 'CACHE-' + crypto.randomUUID().slice(0, 8); + await page.evaluate(nonce => window.browserPi.rpc('write', { path: '/workspace/cached-start.txt', content: nonce }), nonce); + assert.equal(await page.evaluate(() => window.browserPi.rpc('cache_status')), true); + const before = requests.length, start = Date.now(); + // A complete verified cache must suffice even if every model URL is unavailable. + await context.route('**/models/**', route => route.abort()); await context.route('**/resolve/**', route => route.abort()); + await send(task); + await page.waitForFunction(() => window.browserPi.loaded && !window.browserPi.busy && window.browserPi.diagnostics.events.includes('agent_end')); + const state = await page.evaluate(() => window.browserPi.rpc('snapshot')); + assert.equal(await page.evaluate(() => window.dialogOpens), 0); + assert.equal(requests.length, before); + assert.equal(state.messages.filter(m => m.role === 'user').length, 1); + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'read' && !m.isError)); + assert(state.messages.filter(m => m.role === 'assistant').at(-1).content.some(c => c.text?.includes(nonce))); + assert.equal(await page.evaluate(() => window.browserPi.terminal.text), ''); + result.elapsedMs = Date.now() - start; result.messages = state.messages; + result.checks.push('Reloaded app restores the real WebGPU model and sends exactly once, with zero modal openings and zero model requests'); + await page.screenshot({ path: `../validation/${label}.png`, fullPage: true }); + assert.deepEqual(result.errors, []); result.passed = true; + console.log(JSON.stringify({ passed: true, elapsedMs: result.elapsedMs, checks: result.checks })); +} catch (error) { result.failure = error.stack; throw error; } +finally { + if (receipts && page && !page.isClosed()) await cacheReceipts(receipts).catch(() => {}); + await releaseCacheLock().catch(() => {}); + await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result, null, 2)); await context?.close(); +} diff --git a/app/tests/cat-interactions.mjs b/app/tests/cat-interactions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4f8573cd2d7fb3227eaafe75693dfa3438a528b5 --- /dev/null +++ b/app/tests/cat-interactions.mjs @@ -0,0 +1,142 @@ +import { chromium, webkit } from 'playwright'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/'; +const result = { url, checks: [], errors: [] }; +const webkitRoot = process.env.WEBKIT_MINIBROWSER_ROOT; +const cases = [ + { name: 'chromium-desktop', engine: chromium, mobile: false }, + { name: 'chromium-touch', engine: chromium, mobile: true }, + ...(process.env.TEST_WEBKIT ? [{ name: 'webkit-touch', engine: webkit, mobile: true }] : []), +]; +for (const { name, engine, mobile } of cases.filter(item => !process.env.CAT_TEST_CASE || item.name === process.env.CAT_TEST_CASE)) { + console.log(`Checking ${name}`); + const browser = await engine.launch({ headless: true, ...(engine === chromium ? { executablePath: '/usr/bin/chromium' } + : webkitRoot ? { executablePath: webkitRoot + '/bin/MiniBrowser', env: { ...process.env, + WEBKIT_EXEC_PATH: webkitRoot + '/bin', WEBKIT_INJECTED_BUNDLE_PATH: webkitRoot + '/lib', + WEBKIT_INSPECTOR_RESOURCES_PATH: webkitRoot + '/share', + LD_LIBRARY_PATH: webkitRoot + '/lib:' + webkitRoot + '/sys/lib:' + (process.env.WEBKIT_EXTRA_LIBS ?? ''), + } } : {}) }); + const page = await browser.newPage({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, + isMobile: mobile, hasTouch: mobile }); + page.setDefaultTimeout(20000); + page.on('pageerror', error => result.errors.push(`${name}: ${error.message}`)); + // Observe real HTMLAudioElement playback; do not mock play() or decoding. + await page.addInitScript(() => { + const NativeAudio = window.Audio; + window.catAudioInstances = []; + window.Audio = function (...args) { + const audio = new NativeAudio(...args); + if (String(args[0]).includes('cat-meow')) window.catAudioInstances.push(audio); + return audio; + }; + window.Audio.prototype = NativeAudio.prototype; + }); + const activate = selector => mobile ? page.locator(selector).tap() : page.locator(selector).click(); + const heard = () => page.waitForFunction(() => { + const audio = window.catAudioInstances[0]; + return !audio.paused && audio.currentTime > .025 && !audio.muted && audio.volume > 0; + }); + const ended = () => page.waitForFunction(() => window.catAudioInstances[0].ended); + async function unfocusable(selector) { + const states = await page.locator(selector).evaluate(figure => { + const focused = document.activeElement; + const nodes = [figure, ...figure.querySelectorAll('*')]; + const states = nodes.map(node => { + node.focus(); + const style = getComputedStyle(node); + return { keepsFocus: document.activeElement === focused, tabIndex: node.tabIndex, + selection: style.userSelect, drag: style.webkitUserDrag, outline: style.outlineStyle }; + }); + for (const type of ['pointerdown', 'mousedown']) { + const event = type === 'pointerdown' + ? new PointerEvent(type, { bubbles: true, cancelable: true, isPrimary: true }) + : new MouseEvent(type, { bubbles: true, cancelable: true }); + figure.querySelector('img').dispatchEvent(event); + states.push({ type, prevented: event.defaultPrevented }); + } + return states; + }); + for (const state of states) { + if (state.type) assert(state.prevented, `${selector}: ${state.type} must preserve focus`); + else { + assert(state.keepsFocus && state.tabIndex < 0, `${selector}: cat layer took focus`); + assert.equal(state.selection, 'none'); assert.equal(state.drag, 'none'); assert.equal(state.outline, 'none'); + } + } + } + async function tabPastCat(start) { + await page.locator(start).focus(); + for (let i = 0; i < 14; i++) { + await page.keyboard.press('Tab'); + assert(!await page.evaluate(() => document.activeElement.closest('.mascot-cat, .setup-cat'))); + } + await page.locator(start).focus(); + } + try { + console.log(`${name}: opening app`); + await page.goto(url); + await page.waitForFunction(() => window.browserPi?.terminal); + await page.evaluate(() => window.browserPi.ready); + await page.locator('.mascot-cat').waitFor({ state: 'visible' }); + console.log(`${name}: preloading audio`); + await page.waitForFunction(() => window.catAudioInstances[0]?.readyState >= 2); + await page.waitForTimeout(2200); // Includes the automatic greeting hop. + assert.deepEqual(await page.evaluate(() => window.catAudioInstances.map(a => ({ paused: a.paused, time: a.currentTime }))), [{ paused: true, time: 0 }]); + await page.locator('.xterm-helper-textarea').focus(); + await unfocusable('.mascot-cat'); + await tabPastCat('.xterm-helper-textarea'); + console.log(`${name}: playing empty-state meow`); + await activate('.mascot-cat'); await heard(); + assert(await page.locator('.xterm-helper-textarea').evaluate(el => el === document.activeElement)); + await ended(); + await page.emulateMedia({ reducedMotion: 'reduce' }); + await activate('.mascot-cat'); await heard(); + assert.equal(await page.locator('.mascot-cat').evaluate(el => el.getAnimations().length), 0); + await ended(); + await page.emulateMedia({ reducedMotion: 'no-preference' }); + await page.locator('.xterm-helper-textarea').focus(); + await page.keyboard.type('Hello cat'); await page.locator('#send').click(); + await page.locator('#model-dialog[open]').waitFor(); + await page.locator('.setup-cat.is-ready').waitFor(); + await unfocusable('.setup-cat'); + await tabPastCat('#model-confirm'); + console.log(`${name}: playing modal meow and swish`); + await page.locator('.setup-cat').evaluate(el => el.focus()); + assert(await page.locator('#model-confirm').evaluate(el => el === document.activeElement)); + const bodyPose = await page.locator('.setup-cat img').evaluate(el => getComputedStyle(el).transform); + await activate('.setup-cat'); await heard(); + assert(await page.locator('#model-confirm').evaluate(el => el === document.activeElement)); + assert(await page.locator('.setup-cat-tail').evaluate(el => el.getAnimations().some(a => a.id === 'cat-tail-reaction'))); + const pose = await page.locator('.setup-cat-tail').evaluate(el => getComputedStyle(el).transform); + await page.waitForTimeout(250); + assert.notEqual(await page.locator('.setup-cat-tail').evaluate(el => getComputedStyle(el).transform), pose); + assert.equal(await page.locator('.setup-cat img').evaluate(el => getComputedStyle(el).transform), bodyPose); + await activate('.setup-cat'); await activate('.setup-cat'); await heard(); + assert.equal(await page.locator('.setup-cat-tail').evaluate(el => el.getAnimations().filter(a => a.id === 'cat-tail-reaction').length), 1); + assert.equal(await page.evaluate(() => window.catAudioInstances.length), 1); + await ended(); + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.waitForFunction(() => document.querySelector('.setup-cat-tail').getAnimations().length === 0); + await activate('.setup-cat'); await heard(); await ended(); + assert.equal(await page.locator('.setup-cat-tail').evaluate(el => el.getAnimations().length), 0); + await page.emulateMedia({ reducedMotion: 'no-preference' }); + await activate('.setup-cat'); await heard(); + await page.locator('#model-cancel').click(); + assert.equal(await page.locator('.setup-cat-tail').evaluate(el => el.getAnimations().length), 0); + assert.equal(await page.evaluate(() => window.browserPi.terminal.text), 'Hello cat'); + await ended(); + // A blocked playback promise is swallowed; the UI reaction still works. + await page.evaluate(() => { window.catAudioInstances[0].play = () => Promise.reject(new DOMException('Blocked', 'NotAllowedError')); }); + await page.locator('#send').click(); + await activate('.setup-cat'); + assert(await page.locator('.setup-cat-tail').evaluate(el => el.getAnimations().some(a => a.id === 'cat-tail-reaction'))); + await page.screenshot({ path: `../validation/cat-interactions-${name}.png` }); + result.checks.push(`${name}: both cats and their layers reject focus, Tab skips cats, pointer/mouse preserve focus, no selection/drag/outline; real meow playback, repeated taps, silent idle, one shared clip, tail-only motion, reduced motion, close cleanup, blocked-audio fallback`); + } finally { await browser.close(); } +} +assert.deepEqual(result.errors, []); +result.passed = true; +await fs.writeFile('../validation/cat-interactions.json', JSON.stringify(result, null, 2) + '\n'); +console.log(JSON.stringify(result)); diff --git a/app/tests/column-resizer.mjs b/app/tests/column-resizer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a1695207e335c36ddede8ccfebe841c70ad703f3 --- /dev/null +++ b/app/tests/column-resizer.mjs @@ -0,0 +1,108 @@ +import { chromium } from 'playwright'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/'; +const result = { url, checks: [], errors: [] }; +const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.setDefaultTimeout(15000); +page.on('pageerror', error => result.errors.push(error.message)); +const ready = async () => { await page.waitForFunction(() => window.browserPi?.terminal); await page.evaluate(() => window.browserPi.ready); }; +const divider = page.getByRole('separator', { name: 'Resize chat and workspace' }); +const geometry = async () => { + const size = await page.evaluate(() => { + const rect = selector => document.querySelector(selector).getBoundingClientRect().toJSON(); + return { main: rect('main'), chat: rect('.conversation'), workspace: rect('.workspace'), handle: rect('#column-resizer'), + desktop: matchMedia('(min-width: 851px)').matches, + gutter: parseFloat(getComputedStyle(document.querySelector('main')).getPropertyValue('--content-gutter')), + cols: window.browserPi.terminal.cols, overflow: document.documentElement.scrollWidth > innerWidth }; + }); + if (size.desktop) { + closeTo(size.workspace.left, size.chat.right); + closeTo(size.workspace.right + size.gutter, size.main.right); + } + return size; +}; +const frames = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); +async function drag(delta, release = true) { + const r = await divider.boundingBox(); + await page.mouse.move(r.x + r.width / 2, r.y + r.height / 2); await page.mouse.down(); + await page.mouse.move(r.x + r.width / 2 + delta, r.y + r.height / 2, { steps: 12 }); + if (release) await page.mouse.up(); + await frames(); +} +const closeTo = (actual, expected) => assert(Math.abs(actual - expected) < 1, `${actual} vs ${expected}`); +try { + await page.goto(url); await ready(); + assert(await divider.isVisible()); + const initial = await geometry(); + closeTo(initial.chat.width, initial.main.width / 1.83); + assert(initial.handle.x >= initial.chat.right - 14.1 && initial.handle.right <= initial.workspace.left + .1); + await page.locator('.xterm-helper-textarea').focus(); + await page.keyboard.type('Keep this draft'); await page.keyboard.press('Shift+Enter'); await page.keyboard.type('while resizing'); + await page.locator('#files button[title="/workspace/products.json"]').click(); + await page.locator('#editor').fill('{"unsaved": true}'); + await page.locator('#command').fill('echo "unsent command"'); + await drag(240); + assert((await geometry()).chat.width > initial.chat.width + 230); + await page.waitForFunction(cols => window.browserPi.terminal.cols > cols, initial.cols); + assert.equal(await page.evaluate(() => window.browserPi.terminal.text), 'Keep this draft\nwhile resizing'); + assert.equal(await page.locator('#editor').inputValue(), '{"unsaved": true}'); + assert.equal(await page.locator('#command').inputValue(), 'echo "unsent command"'); + assert(await page.locator('#save').isEnabled()); + await page.waitForFunction(() => document.querySelector('#editor-highlight').clientWidth === document.querySelector('#editor').clientWidth); + result.checks.push('Live resizing preserves Pi, file and shell drafts and resizes the terminal and syntax layer'); + + await drag(-2000); closeTo((await geometry()).chat.width, 420); + await divider.press('End'); await frames(); + let size = await geometry(); closeTo(size.main.width - size.chat.width, 370); + assert.equal(await divider.getAttribute('aria-valuenow'), await divider.getAttribute('aria-valuemax')); + await divider.press('ArrowLeft'); await frames(); closeTo((await geometry()).chat.width, size.chat.width - 16); + await divider.press('Shift+ArrowLeft'); await frames(); closeTo((await geometry()).chat.width, size.chat.width - 64); + await divider.press('Home'); await frames(); closeTo((await geometry()).chat.width, 420); + await divider.press('Enter'); await frames(); closeTo((await geometry()).chat.width, initial.chat.width); + result.checks.push('Width limits, keyboard nudges, Shift, Home/End, Enter reset and accessible values work'); + + await drag(150, false); await divider.press('Escape'); await page.mouse.up(); await frames(); + closeTo((await geometry()).chat.width, initial.chat.width); + assert(!await page.locator('html').evaluate(el => el.classList.contains('is-resizing-columns'))); + await drag(100, false); await divider.dispatchEvent('pointercancel', { pointerId: 1 }); await page.mouse.up(); await frames(); + closeTo((await geometry()).chat.width, initial.chat.width); + await drag(170); const saved = (await geometry()).chat.width; + await page.reload(); await ready(); await frames(); closeTo((await geometry()).chat.width, saved); + await page.setViewportSize({ width: 851, height: 800 }); await frames(); + size = await geometry(); assert(size.chat.width >= 420 && size.main.width - size.chat.width >= 369.9 && !size.overflow); + await page.setViewportSize({ width: 1440, height: 1000 }); await frames(); closeTo((await geometry()).chat.width, saved); + result.checks.push('Cancelled drags roll back; saved ratio survives reload and returns after narrow-window clamping'); + + await divider.dblclick(); await frames(); closeTo((await geometry()).chat.width, initial.chat.width); + await page.setViewportSize({ width: 2400, height: 1000 }); await frames(); + size = await geometry(); assert.equal(size.main.width, 1800); assert(size.main.left > 0); + await drag(100); closeTo((await geometry()).chat.width, size.chat.width + 100); + await page.screenshot({ path: '../validation/column-resizer-wide.png', fullPage: true }); + await page.setViewportSize({ width: 1440, height: 1000 }); await frames(); await divider.dblclick(); await frames(); + await page.screenshot({ path: '../validation/column-resizer-desktop.png', fullPage: true }); + await drag(80, false); await page.setViewportSize({ width: 850, height: 800 }); await page.mouse.up(); await frames(); + assert(!await page.locator('html').evaluate(el => el.classList.contains('is-resizing-columns'))); + for (const width of [850,390,320]) { + await page.setViewportSize({ width, height: 844 }); await frames(); + assert(await page.locator('#column-resizer').isHidden()); + size = await geometry(); assert(!size.overflow && size.workspace.top >= size.chat.bottom - 1); + } + await page.screenshot({ path: '../validation/column-resizer-mobile.png', fullPage: true }); + result.checks.push('Double-click resets; centered wide layouts drag accurately; mobile stays stacked and cancels desktop drags'); + + const blocked = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); + await blocked.addInitScript(() => { Storage.prototype.getItem = Storage.prototype.setItem = () => { throw new DOMException('Blocked', 'SecurityError'); }; }); + await blocked.goto(url); await blocked.waitForFunction(() => window.browserPi?.terminal); + await blocked.getByRole('separator', { name: 'Resize chat and workspace' }).press('Home'); + closeTo(await blocked.locator('.conversation').evaluate(el => el.getBoundingClientRect().width), 420); + await blocked.close(); result.checks.push('Resizing works with blocked browser storage'); + assert.deepEqual(result.errors, []); result.passed = true; console.log(JSON.stringify(result)); +} catch (error) { + result.failure = error.stack; + await page.screenshot({ path: '../validation/column-resizer-failure.png', fullPage: true }); throw error; +} finally { + await fs.writeFile('../validation/column-resizer.json', JSON.stringify(result, null, 2)); await browser.close(); +} diff --git a/app/tests/context.mjs b/app/tests/context.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d512ca01e2f1722e8e5220dfc25c4848e8df4004 --- /dev/null +++ b/app/tests/context.mjs @@ -0,0 +1,56 @@ +import {chromium} from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; +import { CONTEXT_LIMIT } from '../src/context-usage.mjs'; +const root=new URL('../..',import.meta.url).pathname.replace(/\/$/,'');const url=process.argv[2]??'http://127.0.0.1:4173/?source=local';const label=process.argv[3]??'agent-context-usage'; +const profile=process.argv[4]??`${root}/validation/agent-browser-profile`; +const result={date:new Date().toISOString(),url,checks:[],errors:[]}; +const context=await chromium.launchPersistentContext(profile,{executablePath:'/usr/bin/chromium',headless:true,viewport:{width:1440,height:1000},args:['--enable-unsafe-webgpu','--use-angle=vulkan','--enable-features=Vulkan','--disable-vulkan-surface']}); +context.setDefaultTimeout(180000);const page=await context.newPage();page.on('pageerror',e=>result.errors.push(e.stack)); +try { +await page.goto(url);await page.waitForFunction(()=>window.browserPi?.terminal);await page.evaluate(()=>window.browserPi.ready); +assert(await page.locator('.xterm-helper-textarea').evaluate(el=>el===document.activeElement)); +await page.keyboard.type('/new');await page.keyboard.press('Enter');await page.waitForFunction(()=>!window.browserPi.busy&&window.browserPi.terminal.text===''&&window.browserPi.diagnostics.contextUsage.inputTokens===0); +assert.deepEqual(await page.evaluate(()=>window.browserPi.diagnostics.contextUsage),{inputTokens:0,outputTokens:0}); +result.checks.push('Input focused on page load; keyboard command works without clicking'); +const nonce='CONTEXT-'+crypto.randomUUID().slice(0,8); +await page.evaluate(nonce=>window.browserPi.rpc('write',{path:'/workspace/context-check.txt',content:nonce}),nonce); +const prompt='Read context-check.txt using the read tool and tell me its exact contents.'; +await page.keyboard.type(prompt);await page.keyboard.press('Enter');await page.waitForFunction(()=>document.querySelector('#model-dialog').open); +assert(await page.locator('#model-confirm').evaluate(el=>el===document.activeElement));assert.equal(await page.locator('#model-cancel').textContent(),'Cancel'); +await page.locator('#model-cancel').click();await page.waitForFunction(()=>window.browserPi.terminal.text.includes('context-check.txt')); +assert(await page.locator('.xterm-helper-textarea').evaluate(el=>el===document.activeElement)); +result.checks.push('Modal takes focus and Cancel restores Pi input and draft'); +await page.evaluate(()=>{window.usageSamples=[];window.usageTimer=setInterval(()=>{const u=window.browserPi.diagnostics.contextUsage;if(JSON.stringify(u)!==JSON.stringify(window.usageSamples.at(-1)))window.usageSamples.push({...u});},40)}); +await page.keyboard.press('Enter');await page.locator('#model-confirm').click(); +await page.waitForFunction(()=>window.browserPi.loaded&&window.browserPi.diagnostics.events.includes('agent_end')&&!window.browserPi.busy); +await page.evaluate(()=>clearInterval(window.usageTimer)); +const snapshot=await page.evaluate(()=>window.browserPi.rpc('snapshot'));const diagnostics=await page.evaluate(()=>window.browserPi.diagnostics); +const final=snapshot.messages.filter(m=>m.role==='assistant').at(-1);const gen=diagnostics.generations.at(-1); +assert(final.content.some(c=>c.text?.includes(nonce)));assert(snapshot.messages.some(m=>m.role==='toolResult'&&m.toolName==='read'&&!m.isError)); +assert.deepEqual(diagnostics.contextUsage,{inputTokens:gen.inputTokens,outputTokens:gen.outputTokens});assert.equal(final.usage.totalTokens,gen.inputTokens+gen.outputTokens); +const samples=await page.evaluate(()=>window.usageSamples);assert(samples.some(u=>u.inputTokens===gen.inputTokens&&u.outputTokens>0&&u.outputTokenswindow.browserPi.terminal.readScreen().includes(text),text); + await page.screenshot({path:`${root}/validation/${label}-${width}.png`,fullPage:true}); +} +result.checks.push('Used/limit and remaining tokens fully visible at desktop and 320px widths'); +await page.setViewportSize({width:1440,height:1000});await page.locator('.xterm-helper-textarea').focus();await page.keyboard.type('Write a numbered list of 100 different animals, with a sentence about each.');await page.keyboard.press('Enter'); +await page.waitForFunction(input=>window.browserPi.busy&&window.browserPi.diagnostics.contextUsage.inputTokens!==input&&window.browserPi.diagnostics.contextUsage.outputTokens>=5,gen.inputTokens); +await page.locator('#stop').click();await page.waitForFunction(()=>!window.browserPi.busy); +const stopped=await page.evaluate(()=>window.browserPi.rpc('snapshot'));const stopUsage=stopped.messages.filter(m=>m.role==='assistant').at(-1).usage; +const beforeReload=await page.evaluate(()=>window.browserPi.diagnostics.contextUsage); +assert.deepEqual(beforeReload,{inputTokens:stopUsage.input,outputTokens:stopUsage.output});assert(stopUsage.output>=5); +await page.reload();await page.waitForFunction(()=>window.browserPi?.terminal);await page.evaluate(()=>window.browserPi.ready); +assert.deepEqual(await page.evaluate(()=>window.browserPi.diagnostics.contextUsage),beforeReload); +assert(await page.locator('.xterm-helper-textarea').evaluate(el=>el===document.activeElement)); +result.stopped=beforeReload;result.checks.push('Stopped generation retains exact counts; reload restores them and focuses input'); +await page.keyboard.type('/new');await page.keyboard.press('Enter');await page.waitForFunction(()=>!window.browserPi.busy&&window.browserPi.diagnostics.contextUsage.inputTokens===0); +assert.deepEqual(await page.evaluate(()=>window.browserPi.diagnostics.contextUsage),{inputTokens:0,outputTokens:0}); +result.checks.push('New chat resets context usage');assert.deepEqual(result.errors,[]);result.passed=true; +console.log(JSON.stringify({passed:true,checks:result.checks,completed:result.completed,stopped:result.stopped})); +} catch(e){result.failure=e.stack;await page.screenshot({path:`${root}/validation/${label}-failure.png`});throw e;} +finally {await fs.writeFile(`${root}/validation/${label}.json`,JSON.stringify(result,null,2));await context.close();} diff --git a/app/tests/conversation.mjs b/app/tests/conversation.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6d0baab902906a9ebbf6ca66221bdeff59e26998 --- /dev/null +++ b/app/tests/conversation.mjs @@ -0,0 +1,64 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/?source=local'; +const label = process.argv[3] ?? 'agent-terminal-dark-conversation'; +const profile = new URL('../../validation/agent-browser-profile', import.meta.url).pathname; +const result = { date: new Date().toISOString(), url, kind: 'actual model; ten consecutive user turns, no chat resets', turns: [], errors: [] }; +const context = await chromium.launchPersistentContext(profile, { + executablePath: '/usr/bin/chromium', headless: true, viewport: { width: 1440, height: 1000 }, + args: ['--enable-unsafe-webgpu', '--use-angle=vulkan', '--enable-features=Vulkan', '--disable-vulkan-surface'], +}); +context.setDefaultTimeout(180_000); +const page = await context.newPage(); +page.on('pageerror', error => result.errors.push(error.stack)); +const hasTool = (messages, name) => messages.some(m => m.role === 'toolResult' && m.toolName === name && !m.isError); +try { + await page.goto(url); await page.waitForFunction(() => window.browserPi?.terminal); + await page.evaluate(() => window.browserPi.ready); + await page.evaluate(() => window.browserPi.load()); + await page.waitForFunction(() => !window.browserPi.busy); + await page.evaluate(() => document.querySelector('#new-chat').onclick()); + await page.evaluate(() => window.browserPi.rpc('shell', { command: 'rm -f /workspace/todo /workspace/numbers.txt /workspace/render-notes.md /workspace/render-missing.txt' })); + await context.setOffline(true); + const tasks = [ + { prompt: 'Hi! Reply with one short sentence.' }, + { prompt: 'Create a file called todo containing exactly "# todo" followed by a newline and "- Check rendering". Use the write tool.', check: (s,m) => { assert(hasTool(m,'write')); assert.match(s.files['/workspace/todo'], /Check rendering/); } }, + { prompt: 'Read todo using the read tool and show its contents.', check: (s,m) => assert(hasTool(m,'read')) }, + { prompt: 'Use the edit tool on todo to replace Check rendering with Check dark mode. Then read it to verify.', check: (s,m) => { assert(hasTool(m,'edit')); assert.match(s.files['/workspace/todo'], /Check dark mode/); } }, + { prompt: 'Run this bash command: seq 1 40 > numbers.txt; wc -l numbers.txt', check: (s,m) => { assert(hasTool(m,'bash')); assert.equal(s.files['/workspace/numbers.txt'].trim().split('\n').length,40); } }, + { prompt: 'Read numbers.txt using the read tool. Tell me only its first and last numbers.', check: (s,m) => assert(hasTool(m,'read')) }, + { prompt: 'Write render-notes.md with a Markdown heading Dark mode, a two-item list about padding and contrast, and a fenced bash code block containing cat todo. Then read the file.', check: (s,m) => { assert(hasTool(m,'write')); assert.match(s.files['/workspace/render-notes.md'], /Dark mode/); } }, + { prompt: 'Read render-missing.txt using the read tool. If missing, write exactly Recovered into it, then read it again.', check: (s,m) => { assert(m.some(m=>m.role==='toolResult' && m.isError)); assert.equal(s.files['/workspace/render-missing.txt'].trim(),'Recovered'); } }, + { prompt: 'Run bash to print todo and render-missing.txt, then count the lines in numbers.txt.', check: (s,m) => assert(hasTool(m,'bash')) }, + { prompt: 'Summarize the files we created in three short Markdown bullets. No tools needed.' }, + ]; + let count = 0; + for (const [index, task] of tasks.entries()) { + const start = Date.now(); + await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.type(task.prompt); + await page.locator('#send').click(); await page.waitForFunction(() => window.browserPi.busy); + await page.waitForFunction(() => !window.browserPi.busy); + const state = await page.evaluate(() => window.browserPi.rpc('snapshot')); + const messages = state.messages.slice(count); count = state.messages.length; + const entry = { turn: index+1, elapsedMs: Date.now()-start, prompt: task.prompt, messages }; + result.turns.push(entry); + assert.equal(state.messages.filter(m=>m.role==='user').length,index+1); + assert(messages.filter(m=>m.role==='assistant').at(-1)?.content.some(c=>c.type==='text' && c.text.trim())); + task.check?.(state,messages); + console.log('PASS turn', index+1, entry.elapsedMs); + } + await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.press('Control+o'); await page.keyboard.press('End'); + await page.screenshot({ path: `../validation/${label}-desktop.png`, fullPage:true }); + await page.keyboard.press('Home'); await page.waitForFunction(()=>window.browserPi.terminal.viewportTop===0); + await page.keyboard.press('End'); + await page.setViewportSize({width:390,height:844}); await page.waitForTimeout(150); + assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)); + await page.screenshot({ path: `../validation/${label}-mobile.png`, fullPage:true }); + result.finalState = await page.evaluate(()=>window.browserPi.rpc('snapshot')); + result.screen = await page.evaluate(()=>window.browserPi.terminal.readScreen()); + result.diagnostics = await page.evaluate(()=>window.browserPi.diagnostics); + assert.equal(result.errors.length,0); result.passed=true; +} catch(error) { result.failure=error.stack; await page.screenshot({path:`../validation/${label}-failure.png`,fullPage:true}); throw error; } +finally { await fs.writeFile(`../validation/${label}.json`,JSON.stringify(result,null,2)); await context.close(); } diff --git a/app/tests/dev-smoke.mjs b/app/tests/dev-smoke.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c471dd06b2aeeba76f260d51682a9548cc542a47 --- /dev/null +++ b/app/tests/dev-smoke.mjs @@ -0,0 +1,21 @@ +import { chromium } from 'playwright'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; + +const context = await chromium.launchPersistentContext('../validation/agent-browser-profile/dev', { + executablePath: '/usr/bin/chromium', headless: true, + args: ['--enable-unsafe-webgpu', '--use-angle=vulkan', '--enable-features=Vulkan', '--disable-vulkan-surface'], +}); +try { + const page = await context.newPage(); + page.on('pageerror', error => console.log('PAGEERROR', error.message)); + await page.goto('http://127.0.0.1:5173/?source=local'); + await page.waitForFunction(() => window.browserPi); await page.evaluate(() => window.browserPi.ready); + await page.evaluate(() => window.browserPi.load()); + await page.evaluate(() => window.browserPi.rpc('new_chat')); + const state = await page.evaluate(() => window.browserPi.prompt('Use bash to calculate 17 * 23. Give the result.')); + console.log(JSON.stringify(state.messages)); + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'bash' && !m.isError && m.content.some(c => c.text?.includes('391')))); + await fs.writeFile('../validation/agent-browser-dev.json', JSON.stringify({ passed: true, messages: state.messages }, null, 2)); + console.log('Development server: real model → Pi → bash → 391 passed.'); +} finally { await context.close(); } diff --git a/app/tests/editor.mjs b/app/tests/editor.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c5ca5e15f7cfbe5ee16bff8c3e9224b12333f750 --- /dev/null +++ b/app/tests/editor.mjs @@ -0,0 +1,110 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/'; +const label = process.argv[3] ?? 'agent-editor'; +const result = { url, checks: [], errors: [] }; +const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.on('pageerror', error => result.errors.push(error.message)); +const editor = page.locator('#editor'), layer = page.locator('#editor-highlight'); +async function write(name, content) { + await page.evaluate(({ name, content }) => window.browserPi.rpc('write', { path: '/workspace/' + name, content }), { name, content }); +} +async function select(name) { + await page.locator(`#files button[title="/workspace/${name}"]`).click(); +} +async function highlighted(text) { + await page.waitForFunction(text => document.querySelector('.editor-input').classList.contains('is-highlighted') && document.querySelector('#editor-highlight').textContent === text + '\n', text); +} +try { + await page.goto(url); await page.waitForFunction(() => window.browserPi); + await page.evaluate(() => window.browserPi.ready); + const html = '\n\n\n \n\n\n \n \n \n\n\n'; + const fixtures = { + 'snake-game.html': [html, '.token.tag, .token.keyword, .token.selector'], + 'app.js': ['// café 🐈\nconst total = items.reduce((sum, item) => sum + item.price, 0);\n', '.token.keyword'], + 'view.tsx': ['const View = (props: { label: string }) => ;\n', '.token.tag'], + 'script.py': ['# Sales\ndef total(rows):\n\treturn sum(row["price"] for row in rows)\n', '.token.keyword'], + 'style.css': ['body { color: #fff; margin: 0; }\n', '.token.property'], + 'data.json': ['{"total": 274.88, "verified": true}\n', '.token.property'], + 'notes.md': ['# Report\n\n**Total:** `274.88`\n', '.token.title'], + 'config.yaml': ['version: 1\nfiles:\n - sales.csv\n', '.token.key'], + 'query.sql': ['SELECT SUM(units * price) AS total FROM sales;\n', '.token.keyword'], + 'run.sh': ['#!/bin/bash\nfor file in *.csv; do echo "$file"; done\n', '.token.keyword'], + }; + for (const [name, [content, token]] of Object.entries(fixtures)) { + await write(name, content); await select(name); await highlighted(content); + assert(await layer.locator(token).count(), name); + assert.equal(await editor.inputValue(), content); + } + result.checks.push('Common language grammars render colors and preserve exact source, including Unicode, tabs and trailing newlines'); + await select('snake-game.html'); await highlighted(html); + for (const token of ['.token.tag', '.token.keyword', '.token.selector']) assert(await layer.locator(token).count()); + assert.equal(await layer.locator('script, style, canvas, img, iframe').count(), 0); + await page.screenshot({ path: `../validation/${label}-html.png`, fullPage: true }); + + // Real keyboard edits must retain selection, undo and the file-saving flow. + await editor.focus(); await page.keyboard.press('Control+End'); + await page.keyboard.insertText(''); await highlighted(html + ''); + await page.keyboard.press('Control+z'); await highlighted(html); + await page.keyboard.type(''); await highlighted(html + ''); + await page.locator('#save').click(); await page.waitForFunction(() => document.querySelector('#save').disabled); + assert.equal(await page.evaluate(() => window.browserPi.rpc('snapshot').then(state => state.files['/workspace/snake-game.html'])), html + ''); + await editor.fill(''); + await highlighted(await editor.inputValue()); + assert.equal(await page.evaluate(() => window.sourceExecuted), undefined); + assert.equal(await layer.locator('img, script').count(), 0); + await editor.fill(html); await highlighted(html); await page.locator('#save').click(); + await page.waitForFunction(() => document.querySelector('#save').disabled); + result.checks.push('Native keyboard editing and undo work; Save persists exact content; HTML source remains inert'); + + const long = Array.from({ length: 500 }, (_, i) => `const row${i} = "${'x'.repeat(120)}";`).join('\n') + '\n'; + await write('long.js', long); await select('long.js'); await highlighted(long); + for (const [width, height] of [[1440,1000], [390,844], [320,568]]) { + await page.setViewportSize({ width, height }); await editor.scrollIntoViewIfNeeded(); + await editor.evaluate(el => { el.scrollTop = el.scrollHeight; el.scrollLeft = el.scrollWidth; }); + await page.waitForFunction(() => { + const input = document.querySelector('#editor'), pre = document.querySelector('#editor-highlight'); + return pre.scrollTop === input.scrollTop && pre.scrollLeft === input.scrollLeft && pre.clientWidth === input.clientWidth && pre.clientHeight === input.clientHeight; + }); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + const fonts = await page.evaluate(() => ['#editor', '#editor-highlight'].map(selector => { + const style = getComputedStyle(document.querySelector(selector)); + return [style.font, style.padding, style.tabSize, style.whiteSpace, style.letterSpacing]; + })); + assert.deepEqual(fonts[0], fonts[1]); + } + await select('snake-game.html'); await highlighted(html); await editor.scrollIntoViewIfNeeded(); + assert.deepEqual(await editor.evaluate(el => [el.scrollTop, el.scrollLeft]), [0, 0]); + await page.screenshot({ path: `../validation/${label}-mobile.png`, fullPage: true }); + result.checks.push('Highlighted text stays aligned with the caret and both scroll axes on desktop and narrow mobile layouts'); + + // Rapid switching cannot let an old worker response overwrite the new file. + await select('long.js'); await select('data.json'); await highlighted(fixtures['data.json'][0]); + await write('plain.txt', 'plain text'); await select('plain.txt'); + assert.equal(await page.locator('.is-highlighted').count(), 0); + const huge = '// large file\n' + 'x'.repeat(250_000); + await write('large.js', huge); await select('large.js'); + assert.equal(await page.locator('.is-highlighted').count(), 0); + const started = Date.now(); + await editor.focus(); await page.keyboard.press('Control+End'); await page.keyboard.type(' edited'); + assert((await editor.inputValue()).endsWith(' edited')); + result.largeFileEditMs = Date.now() - started; + await page.locator('#save').click(); await page.waitForFunction(() => document.querySelector('#save').disabled); + await select('snake-game.html'); await highlighted(html); + await page.emulateMedia({ forcedColors: 'active' }); + assert.equal(await layer.evaluate(el => getComputedStyle(el).visibility), 'hidden'); + assert.notEqual(await editor.evaluate(el => getComputedStyle(el).color), 'rgba(0, 0, 0, 0)'); + result.checks.push('Rapid file switching avoids stale colors; plain/large files remain editable; forced-colors mode shows native text'); + assert.deepEqual(result.errors, []); result.passed = true; + console.log(JSON.stringify(result, null, 2)); +} catch (error) { + result.failure = error.stack; + await page.screenshot({ path: `../validation/${label}-failure.png`, fullPage: true }); + throw error; +} finally { + await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result, null, 2)); + await browser.close(); +} diff --git a/app/tests/first-message.mjs b/app/tests/first-message.mjs new file mode 100644 index 0000000000000000000000000000000000000000..72deefb2a15f04294d1451808f6061d06f92433d --- /dev/null +++ b/app/tests/first-message.mjs @@ -0,0 +1,113 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/?source=local'; +const label = process.argv[3] ?? 'agent-first-message'; +const result = { date: new Date().toISOString(), url, checks: [], errors: [] }; +const gpuArgs = ['--enable-unsafe-webgpu', '--use-angle=vulkan', '--enable-features=Vulkan', '--disable-vulkan-surface']; +let context, browser, page; +async function open() { + page = await context.newPage(); page.on('pageerror', e => result.errors.push(e.stack)); + context.setDefaultTimeout(180_000); + await page.goto(url); await page.waitForFunction(() => window.browserPi?.terminal); + await page.evaluate(() => window.browserPi.ready); + await page.evaluate(() => document.querySelector('#new-chat').onclick()); +} +async function send(text, expectModal = true) { + await page.locator('.xterm-helper-textarea').focus(); + if (text) await page.keyboard.type(text); + await page.locator('#send').click(); + if (expectModal) await page.waitForFunction(() => document.querySelector('#model-dialog').open); + else await page.waitForFunction(() => window.browserPi.busy || window.browserPi.loaded); +} +async function draft(text) { + await page.waitForFunction(text => !document.querySelector('#model-dialog').open && window.browserPi.terminal.text === text, text); +} +try { + // Real unsupported-GPU path: no fake model, worker, progress or failure events. + browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true, args: ['--disable-gpu', '--disable-software-rasterizer'] }); + context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, colorScheme: 'light' }); + const requests = []; context.on('request', r => requests.push(r.url())); + await open(); + const prompt = 'Create a file called hello.txt containing Hello.'; + await send(prompt); + assert.equal(await page.locator('#model-preview').textContent(), prompt); + assert(await page.locator('#model-confirm').evaluate(el => el === document.activeElement)); + assert.equal(await page.evaluate(() => window.browserPi.loaded), false); + assert.equal(requests.filter(u => /\.onnx|manifest\.json|tokenizer/.test(u)).length, 0); + result.checks.push('First Send opens an accessible modal; no model download before confirmation'); + await page.locator('#model-cancel').focus(); + await page.keyboard.press('Tab'); assert(await page.locator('.setup-model .model-org').evaluate(el => el === document.activeElement)); + await page.keyboard.press('Shift+Tab'); assert(await page.locator('#model-cancel').evaluate(el => el === document.activeElement)); + await page.locator('#model-confirm').focus(); + for (const [width,height] of [[1440,1000],[850,640],[390,844],[320,568],[390,420]]) { + await page.setViewportSize({width,height}); + const layout = await page.evaluate(() => { + const rect=document.querySelector('#model-dialog').getBoundingClientRect(); + const actions=document.querySelector('.setup-actions').getBoundingClientRect(); + const selectors=['html','header','.model-panel','.workspace','.editor-area','.workspace > .terminal','#model-dialog','#model-preview']; + return { inBounds:rect.x>=0 && rect.y>=0 && rect.right<=innerWidth && rect.bottom<=innerHeight && actions.top>=rect.top && actions.bottom<=rect.bottom, + overflow:document.documentElement.scrollWidth>innerWidth, + dark:getComputedStyle(document.documentElement).colorScheme==='dark', + surfaces:selectors.map(s=>({selector:s,bg:getComputedStyle(document.querySelector(s)).backgroundColor})) }; + }); + assert(layout.inBounds && !layout.overflow && layout.dark); + for(const surface of layout.surfaces) assert(surface.bg.match(/\d+/g).slice(0,3).every(n=>Number(n)<80),JSON.stringify(surface)); + if([1440,390,320].includes(width)) await page.screenshot({path:`../validation/${label}-modal-${width}x${height}.png`,fullPage:true}); + } + result.checks.push('Focus stays in the modal; entire app remains dark under a light OS preference; five viewport sizes fit'); + await page.keyboard.press('Escape'); await draft(prompt); + assert.equal(await page.locator('#notice').textContent(),''); + await send(); await page.locator('#model-confirm').click(); + await page.waitForFunction(()=>!document.querySelector('#model-error').hidden); + assert.match(await page.locator('#model-error').textContent(),/WebGPU/); + assert.equal(await page.locator('#model-confirm').textContent(),'Try again'); + await page.locator('#model-confirm').click(); + await page.waitForFunction(()=>!document.querySelector('#model-error').hidden && !document.querySelector('#model-confirm').disabled); + await page.screenshot({path:`../validation/${label}-error.png`,fullPage:true}); + await page.locator('#model-cancel').click(); await draft(prompt); + assert.equal((await page.evaluate(()=>window.browserPi.rpc('snapshot'))).messages.length,0); + result.checks.push('Escape and Cancel restore the draft; real unsupported-GPU error supports retry without sending'); + await context.close(); await browser.close(); context=undefined; browser=undefined; + + context = await chromium.launchPersistentContext(new URL('../../validation/agent-browser-profile',import.meta.url).pathname, + { executablePath:'/usr/bin/chromium', headless:true, viewport:{width:1440,height:1000}, args:gpuArgs }); + await open(); + const nonce='FIRST-'+crypto.randomUUID().slice(0,8); + await page.evaluate(nonce=>window.browserPi.rpc('write',{path:'/workspace/first-message.txt',content:nonce}),nonce); + const task='Read first-message.txt using the read tool and tell me its exact contents.'; + const cached = await page.evaluate(()=>window.browserPi.rpc('cache_status')); + await send(task, !cached); + if (cached) await page.locator('#stop').click(); + else { + await page.locator('#model-confirm').click(); + await page.waitForFunction(()=>window.browserPi.busy && !document.querySelector('#model-dialog').open && !document.querySelector('#progress').hidden); + await page.locator('#stop').click(); + } + await draft(task); + await page.waitForFunction(()=>!window.browserPi.busy); + assert.equal((await page.evaluate(()=>window.browserPi.rpc('snapshot'))).messages.length,0); + result.checks.push('Cancelling real model setup waits for cleanup and restores the unsent message'); + const start=Date.now(); + const cachedOnRetry = await page.evaluate(()=>window.browserPi.rpc('cache_status')); + await send(undefined, !cachedOnRetry); + if (!cachedOnRetry) await page.locator('#model-confirm').click(); + await page.waitForFunction(()=>window.browserPi.loaded && window.browserPi.diagnostics.events.includes('agent_end') && !window.browserPi.busy); + result.elapsedMs=Date.now()-start; + const state=await page.evaluate(()=>window.browserPi.rpc('snapshot')); + assert.equal(state.messages.filter(m=>m.role==='user').length,1); + assert.equal(state.messages.find(m=>m.role==='user').content[0].text,task); + assert(state.messages.some(m=>m.role==='toolResult' && m.toolName==='read' && !m.isError)); + assert(state.messages.filter(m=>m.role==='assistant').at(-1).content.some(c=>c.text?.includes(nonce))); + assert.equal(await page.evaluate(()=>window.browserPi.terminal.text),''); + assert.equal(await page.locator('#model-dialog').evaluate(el=>el.open),false); + result.messages=state.messages; + result.checks.push('Cached auto-start or download confirmation loads the actual model, sends exactly once and answers with an unseen file value'); + await page.screenshot({path:`../validation/${label}-desktop.png`,fullPage:true}); + await page.setViewportSize({width:390,height:844}); + await page.screenshot({path:`../validation/${label}-mobile.png`,fullPage:true}); + assert.equal(result.errors.length,0); result.passed=true; + console.log(JSON.stringify({passed:true,checks:result.checks,elapsedMs:result.elapsedMs})); +} catch(error) { result.failure=error.stack; await page?.screenshot({path:`../validation/${label}-failure.png`,fullPage:true}); throw error; } +finally { await fs.writeFile(`../validation/${label}.json`,JSON.stringify(result,null,2)); await context?.close(); await browser?.close(); } diff --git a/app/tests/follow-read.mjs b/app/tests/follow-read.mjs new file mode 100644 index 0000000000000000000000000000000000000000..62e3074ea35e0d1917317e22eeea3ef4fb3b257f --- /dev/null +++ b/app/tests/follow-read.mjs @@ -0,0 +1,69 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; +const url = process.argv[2] ?? 'http://127.0.0.1:4173/'; +const label = process.argv[3] ?? 'agent-follow-read'; +const result = { url, date: new Date().toISOString(), checks: [], errors: [] }; +const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.on('pageerror', error => result.errors.push(error.message)); +// Presentation fixtures enter the real worker-message handler. Actual model +// reads are checked separately by runtime-meter.mjs, and path resolution by +// the real just-bash tool unit test. +await page.addInitScript(() => { + const NativeWorker = Worker; + window.Worker = class extends NativeWorker { constructor(...args) { super(...args); if (String(args[0]).includes('agent.worker')) window.fixtureWorker = this; } }; +}); +const emit = data => page.evaluate(data => window.fixtureWorker.dispatchEvent(new MessageEvent('message', { data })), data); +const read = (path, isError = false) => emit({ type: 'agent_event', event: { type: 'tool_execution_end', toolName: 'read', isError, result: { details: { path } } } }); +try { + await page.goto(url); await page.waitForFunction(() => window.browserPi); await page.evaluate(() => window.browserPi.ready); + assert.equal(await page.locator('.brand').innerText(), ''); + assert.equal(await page.locator('.runtime-engine').innerText(), 'WebGPU'); + await page.evaluate(() => window.browserPi.rpc('write', { path: '/workspace/empty.txt', content: '' })); + await page.locator('.xterm-helper-textarea').focus(); + await read('/workspace/sales.csv'); + assert.equal(await page.locator('#filename').textContent(), '/workspace/sales.csv'); + assert.equal(await page.locator('#files .selected .file-name').textContent(), 'sales.csv'); + assert.equal(await page.locator('#filetype .file-icon').getAttribute('data-kind'), 'csv'); + assert(await page.locator('.xterm-helper-textarea').evaluate(el => el === document.activeElement)); + await read('/workspace/empty.txt'); assert.equal(await page.locator('#editor').inputValue(), ''); + await read('/workspace/missing.txt', true); assert.equal(await page.locator('#filename').textContent(), '/workspace/empty.txt'); + result.checks.push('Successful reads select and highlight the file without stealing focus; empty files work and failed reads keep the current selection'); + await page.locator('#editor').fill('Unsaved text'); + await read('/workspace/sales.csv'); + assert.equal(await page.locator('#filename').textContent(), '/workspace/empty.txt'); + assert.equal(await page.locator('#editor').inputValue(), 'Unsaved text'); + await page.locator('#save').click(); await page.waitForFunction(() => document.querySelector('#save').disabled); + result.checks.push('Automatic selection preserves unsaved editor text'); + const state = await page.evaluate(() => window.browserPi.rpc('snapshot')); + await read('/workspace/fresh.md'); + await emit({ type: 'workspace', files: { ...state.files, '/workspace/fresh.md': 'New file' } }); + assert.equal(await page.locator('#filename').textContent(), '/workspace/fresh.md'); + assert.equal(await page.locator('#editor').inputValue(), 'New file'); + await read('/workspace/later.md'); + await page.getByRole('button', { name: 'README.md', exact: true }).click(); + await emit({ type: 'workspace', files: { ...state.files, '/workspace/later.md': 'Later' } }); + assert.equal(await page.locator('#filename').textContent(), '/workspace/README.md'); + result.checks.push('Reads wait for newly created files to arrive; a manual file selection cancels delayed following'); + const gallery = { ...state.files, '/workspace/app.js': '', '/workspace/types.ts': '', '/workspace/component.tsx': '', '/workspace/index.html': '', '/workspace/style.css': '', '/workspace/data.json': '', '/workspace/config.yaml': '', '/workspace/script.py': '', '/workspace/run.sh': '', '/workspace/icon.svg': '', '/workspace/image.png': '', '/workspace/.gitignore': '', '/workspace/archive.zip': '', '/workspace/query.sql': '', '/workspace/document.pdf': '', '/workspace/very-long-file-name-with-many-characters.txt': '' }; + await emit({ type: 'workspace', files: gallery }); + for (const [width,height] of [[1440,1000],[390,844],[320,568]]) { + await page.setViewportSize({ width, height }); + const before = await page.evaluate(() => scrollY); + await read('/workspace/very-long-file-name-with-many-characters.txt'); + assert.equal(await page.evaluate(() => scrollY), before); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + const aligned = await page.evaluate(() => [...document.querySelectorAll('#files button')].every(button => { + const icon = button.querySelector('.file-icon').getBoundingClientRect(), name = button.querySelector('.file-name').getBoundingClientRect(); + return Math.abs(icon.width - 16) < .1 && icon.right <= name.left && name.right <= button.getBoundingClientRect().right; + })); + assert(aligned); + await page.screenshot({ path: `../validation/${label}-${width}.png`, fullPage: true }); + } + const icons = await page.evaluate(() => Promise.all([...new Set([...document.querySelectorAll('.file-icon')].map(icon => icon.style.getPropertyValue('--file-icon').slice(5,-2)))].map(async url => ({ url, status: (await fetch(url)).status })))); + assert(icons.every(icon => icon.status === 200)); + result.checks.push('Common Seti icons load; long filenames fit desktop/mobile; auto-follow scrolls only the file list'); + assert.deepEqual(result.errors, []); result.passed = true; console.log(JSON.stringify({ passed: true, checks: result.checks })); +} catch (error) { result.failure = error.stack; await page.screenshot({ path: `../validation/${label}-failure.png`, fullPage: true }); throw error; } +finally { await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result,null,2)); await browser.close(); } diff --git a/app/tests/load-flow.mjs b/app/tests/load-flow.mjs new file mode 100644 index 0000000000000000000000000000000000000000..35befb90a1aca2d89a0c7f6931fcfefa65d2ea8a --- /dev/null +++ b/app/tests/load-flow.mjs @@ -0,0 +1,167 @@ +import { chromium } from 'playwright'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/'; +const result = { url, fixture: 'Real app and workspace worker; controlled model load and prompt replies. GPU failure also tested without fixtures.', checks: [], errors: [] }; +const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true, args: ['--disable-gpu', '--disable-software-rasterizer'] }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.setDefaultTimeout(15000); +page.on('pageerror', error => result.errors.push(error.message)); +// Control only the model boundary; initialization, files and the terminal are real. +await page.addInitScript(() => { + const NativeWorker = Worker; + const fixture = window.loadFixture = { loads: [], prompts: [], cached: false }; + window.Worker = class extends NativeWorker { + constructor(...args) { super(...args); this.isAgent = String(args[0]).includes('agent.worker'); if (this.isAgent) fixture.worker = this; } + postMessage(message, ...rest) { + if (!this.isAgent) return super.postMessage(message, ...rest); + const { id, action, args } = message; + if (action === 'cache_status' && fixture.cached) { fixture.emit({ type: 'reply', id, value: true }); return; } + if (action === 'load') { + fixture.loads.push(args); fixture.pending = id; fixture.stopped = false; + fixture.emit({ type: 'busy', action, cachedOnly: args.cachedOnly }); return; + } + if (action === 'stop' && fixture.pending) { + fixture.stopped = true; fixture.emit({ type: 'reply', id, value: true }); return; + } + if (action === 'prompt') { + fixture.prompts.push(args.text); + const message = { role: 'user', content: [{ type: 'text', text: args.text }], timestamp: Date.now() }; + fixture.emit({ type: 'busy', action }); + fixture.emit({ type: 'agent_event', event: { type: 'message_start', message } }); + fixture.emit({ type: 'reply', id, value: { messages: [message] } }); + fixture.emit({ type: 'idle' }); return; + } + return super.postMessage(message, ...rest); + } + }; + fixture.emit = data => fixture.worker.dispatchEvent(new MessageEvent('message', { data })); + fixture.finish = (error, name = 'Error') => { + const id = fixture.pending; fixture.pending = undefined; + if (!error) fixture.emit({ type: 'loaded', device: { vendor: 'test fixture' } }); + // Match the worker's error ordering: cleanup/idle before a rejected reply. + if (error) fixture.emit({ type: 'idle' }); + fixture.emit({ type: 'reply', id, value: {}, error, errorName: name }); + if (!error) fixture.emit({ type: 'idle' }); + }; +}); +const ready = async () => { await page.waitForFunction(() => window.browserPi?.terminal); await page.evaluate(() => window.browserPi.ready); }; +const emit = data => page.evaluate(data => window.loadFixture.emit(data), data); +const finish = (error, name) => page.evaluate(([error, name]) => window.loadFixture.finish(error, name), [error, name]); +const draft = text => page.waitForFunction(text => !window.browserPi.busy && !document.querySelector('#model-dialog').open && window.browserPi.terminal.text === text, text); +const send = async (text = '') => { + await page.locator('.xterm-helper-textarea').focus(); + if (text) await page.keyboard.type(text); + await page.locator('#send').click(); + await page.locator('#model-dialog[open]').waitFor(); +}; +const confirm = async () => { + await page.locator('#model-confirm').click(); + await page.waitForFunction(() => window.browserPi.busy && !document.querySelector('#model-dialog').open); +}; +try { + await page.goto(url); await ready(); + const text = "What's our total sales revenue?"; + await send(text); await page.locator('#model-cancel').click(); await draft(text); + assert.equal(await page.evaluate(() => window.loadFixture.loads.length), 0); + await send(); await confirm(); + assert(await page.locator('#progress').isVisible()); + assert.equal(await page.locator('#progress').getAttribute('value'), null); + assert.equal(await page.locator('#runtime-meter').getAttribute('data-state'), 'loading'); + assert(await page.locator('#stop').isVisible()); + for (const id of ['#send', '#new-chat', '#load']) assert(await page.locator(id).isDisabled()); + await page.waitForFunction(text => window.browserPi.terminal.readScreen().includes(text) && window.browserPi.terminal.readScreen().includes('Queued'), text); + assert(await page.locator('.xterm-helper-textarea').evaluate(el => el === document.activeElement)); + await page.evaluate(() => { document.querySelector('#model-confirm').click(); window.browserPi.terminal.submit(); document.querySelector('#send').click(); }); + assert.equal(await page.evaluate(() => window.loadFixture.loads.length), 1); + assert.equal(await page.evaluate(() => window.loadFixture.prompts.length), 0); + await emit({ type: 'load_progress', phase: 'download', loaded: 736000000, total: 1840000000 }); + assert.equal(await page.locator('#progress').getAttribute('value'), '40'); + assert.match(await page.locator('#load').getAttribute('title'), /Hugging Face/); + for (const [width, height] of [[1440,1000],[851,800],[850,800],[390,844],[320,568]]) { + await page.setViewportSize({ width, height }); + await page.waitForTimeout(250); // Header capsule width transition. + assert(await page.evaluate(() => { + const header = document.querySelector('header').getBoundingClientRect(); + return document.documentElement.scrollWidth <= innerWidth && [...document.querySelectorAll('#runtime-meter, .model-panel, #progress')].every(el => { + const r = el.getBoundingClientRect(); return r.left >= header.left && r.right <= header.right && r.top >= header.top && r.bottom <= header.bottom; + }); + }), `Header overflow at ${width}`); + if ([1440,390,320].includes(width)) await page.screenshot({ path: `../validation/load-flow-${width}.png`, fullPage: true }); + } + await emit({ type: 'load_progress', phase: 'compile' }); + assert(await page.locator('#progress').isVisible()); assert.equal(await page.locator('#progress').getAttribute('value'), null); + await emit({ type: 'load_progress', phase: 'warmup' }); + assert.equal(await page.locator('#load').textContent(), 'Almost ready…'); + await page.locator('#stop').click(); + assert(await page.evaluate(() => window.loadFixture.stopped && window.browserPi.busy)); + assert(await page.locator('#send').isDisabled()); + await finish('Stopped.', 'AbortError'); await draft(text); + assert(await page.locator('#progress').isHidden()); + assert.equal(await page.evaluate(() => window.loadFixture.prompts.length), 0); + result.checks.push('Confirmation closes immediately, queues the visible message, shows all header phases at five widths, rejects duplicate clicks; Stop waits for cleanup and restores the draft'); + + await page.setViewportSize({ width: 1440, height: 1000 }); + await send(); await confirm(); await finish('Download interrupted. Please try again.'); + await page.locator('#model-dialog[open]').waitFor(); + assert.equal(await page.locator('#model-preview').textContent(), text); + assert.match(await page.locator('#model-error').textContent(), /Download interrupted/); + assert.equal(await page.locator('#model-confirm').textContent(), 'Try again'); + assert(await page.locator('#progress').isHidden()); + await page.keyboard.press('Escape'); await draft(text); + await send(); await confirm(); await finish('Temporary connection failure.'); + await page.locator('#model-dialog[open]').waitFor(); + await confirm(); + await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.type('A follow-up draft'); + await page.locator('#files button').first().focus(); + await finish(); + await page.waitForFunction(() => window.loadFixture.prompts.length === 1 && !window.browserPi.busy); + assert.deepEqual(await page.evaluate(() => window.loadFixture.prompts), [text]); + assert.equal(await page.evaluate(() => window.browserPi.terminal.text), 'A follow-up draft'); + assert(await page.locator('#model-dialog').isHidden()); + assert(await page.locator('#progress').isHidden()); + assert(await page.locator('#files button').first().evaluate(el => el === document.activeElement)); + await page.waitForFunction(() => !window.browserPi.terminal.readScreen().includes('Queued')); + result.checks.push('Failure reopens retry with the original message; Escape keeps the draft; successful retry sends exactly once and retains a follow-up draft and the user’s current focus'); + + await page.reload(); await ready(); + await page.evaluate(() => { window.loadFixture.cached = true; }); + await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.type('Cached message'); await page.locator('#send').click(); + await page.waitForFunction(() => window.loadFixture.pending); + assert(await page.locator('#model-dialog').isHidden()); + assert.equal(await page.evaluate(() => window.loadFixture.loads[0].cachedOnly), true); + await emit({ type: 'load_progress', phase: 'compile' }); + assert(await page.locator('#progress').isVisible()); + await page.keyboard.press('Escape'); await finish('Stopped.', 'AbortError'); await draft('Cached message'); + result.checks.push('Cached restoration uses the same top bar without confirmation; Escape stops it without opening a retry dialog'); + + await page.reload(); await ready(); + await page.locator('#load').click(); + assert(await page.locator('#model-dialog').isHidden()); + assert(await page.locator('#progress').isVisible()); + await finish(); await page.waitForFunction(() => window.browserPi.loaded && !window.browserPi.busy); + assert.equal(await page.evaluate(() => window.loadFixture.prompts.length), 0); + result.checks.push('Loading from the header still works without queuing or sending a message'); + + // Real unsupported-GPU load, with no worker interception or fake progress. + const actual = await browser.newPage({ viewport: { width: 390, height: 844 } }); + actual.on('pageerror', error => result.errors.push(error.message)); + await actual.goto(url); await actual.waitForFunction(() => window.browserPi?.terminal); await actual.evaluate(() => window.browserPi.ready); + await actual.locator('.xterm-helper-textarea').focus(); await actual.keyboard.type('Keep my message'); await actual.locator('#send').click(); + await actual.locator('#model-confirm').click(); + await actual.locator('#model-error').waitFor({ state: 'visible' }); + assert.match(await actual.locator('#model-error').textContent(), /WebGPU/); + assert(await actual.locator('#progress').isHidden()); + await actual.locator('#model-confirm').click(); await actual.locator('#model-error').waitFor({ state: 'visible' }); + await actual.locator('#model-cancel').click(); + await actual.waitForFunction(() => window.browserPi.terminal.text === 'Keep my message'); + assert.equal((await actual.evaluate(() => window.browserPi.rpc('snapshot'))).messages.length, 0); + await actual.close(); result.checks.push('Actual unsupported-WebGPU load retries and cancels safely with no message sent'); + assert.deepEqual(result.errors, []); result.passed = true; +} catch (error) { + result.failure = error.stack; await page.screenshot({ path: '../validation/load-flow-failure.png', fullPage: true }); throw error; +} finally { + await fs.writeFile('../validation/load-flow.json', JSON.stringify(result, null, 2)); + await browser.close(); console.log(JSON.stringify(result)); +} diff --git a/app/tests/mascot.mjs b/app/tests/mascot.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5c3ca9d717ebaf51b0f3356713550ee26ac74a0c --- /dev/null +++ b/app/tests/mascot.mjs @@ -0,0 +1,116 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/'; +const label = process.argv[3] ?? 'agent-mascot'; +const result = { url, date: new Date().toISOString(), checks: [], layouts: [], errors: [] }; +const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true }); +const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); +const page = await context.newPage(); +page.on('pageerror', error => result.errors.push(error.message)); +const requests = []; page.on('request', request => requests.push(request.url())); +const ready = async () => { await page.waitForFunction(() => window.browserPi?.terminal); await page.evaluate(() => window.browserPi.ready); }; +const visible = () => page.locator('.empty-mascot').waitFor({ state: 'visible' }); +let releaseImage; +try { + const imageGate = new Promise(resolve => { releaseImage = resolve; }); + await page.route('**/*empty-cat*.png', async route => { await imageGate; await route.continue(); }); + await page.goto(url, { waitUntil: 'domcontentloaded' }); await ready(); + await page.waitForFunction(() => document.querySelector('.empty-mascot img').hasAttribute('src')); + assert(!await page.locator('.empty-mascot').isVisible()); + assert(!await page.locator('.mascot-suggestion').isVisible()); + releaseImage(); await visible(); await page.unroute('**/*empty-cat*.png'); + await page.waitForFunction(() => document.querySelector('.empty-mascot img').naturalWidth > 0); + result.checks.push('Bubble and cat stay hidden during a delayed image download and appear together when ready'); + await page.locator('.mascot-suggestion').focus(); + await page.keyboard.press('Tab'); + assert(!await page.locator('.mascot-cat').evaluate(el => el.contains(document.activeElement))); + await page.locator('.xterm-helper-textarea').focus(); + await page.locator('.mascot-cat').evaluate(el => el.focus()); + assert(await page.locator('.xterm-helper-textarea').evaluate(el => el === document.activeElement)); + await page.locator('.mascot-cat').click(); + assert(await page.locator('.mascot-cat').evaluate(el => el.getAnimations().some(a => a.id === 'mascot-bump'))); + assert(await page.locator('.xterm-helper-textarea').evaluate(el => el === document.activeElement)); + await page.locator('.mascot-cat').click(); + assert.equal(await page.locator('.mascot-cat').evaluate(el => el.getAnimations().filter(a => a.id === 'mascot-bump').length), 1); + assert.equal(await page.evaluate(() => window.browserPi.terminal.text), ''); + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.waitForFunction(() => document.querySelector('.empty-mascot').getAnimations({ subtree: true }).length === 0); + await page.locator('.mascot-cat').click(); + assert.equal(await page.locator('.mascot-cat').evaluate(el => el.getAnimations().length), 0); + await page.emulateMedia({ reducedMotion: 'no-preference' }); + result.checks.push('Cat is not focusable and Tab skips it; clicking preserves input focus and replays one hop; reduced motion remains still'); + await page.locator('.mascot-suggestion').click(); + const prompt = await page.evaluate(() => window.browserPi.terminal.text); + assert.equal(prompt, "What's our total sales revenue?"); + assert(await page.locator('.xterm-helper-textarea').evaluate(el => el === document.activeElement)); + assert.equal((await page.evaluate(() => window.browserPi.rpc('snapshot'))).messages.length, 0); + await page.waitForFunction(() => document.querySelector('.mascot-suggestion').hidden); + await page.locator('#send').click(); await page.locator('#model-dialog').waitFor({ state: 'visible' }); + assert.equal(await page.locator('#model-preview').textContent(), prompt); + await page.locator('#model-cancel').click(); + await page.waitForFunction(prompt => window.browserPi.terminal.text === prompt, prompt); await visible(); + assert(!await page.locator('.mascot-suggestion').isVisible()); + assert(!requests.some(url => /\.onnx|tokenizer|manifest\.json/.test(url))); + result.checks.push('Suggestion fills and focuses Pi without sending; first-message modal and Cancel preserve the draft and zero-user state'); + + await page.reload(); await ready(); await visible(); + for (const [width, height] of [[1440,1000],[1100,800],[851,640],[850,640],[390,844],[320,568],[390,420]]) { + await page.setViewportSize({ width, height }); await page.waitForTimeout(120); + const layout = await page.evaluate(() => { + const mascot = document.querySelector('.empty-mascot'), m = mascot.getBoundingClientRect(); + const cat = document.querySelector('.mascot-cat').getBoundingClientRect(); + const screen = document.querySelector('.xterm-screen').getBoundingClientRect(), t = window.browserPi.terminal; + const lines = t.readScreen().split('\n'), status = lines.findIndex(line => line.includes('Files and chat')); + const rowHeight = screen.height / t.rows; + let lastContent = status - 1; while (lastContent >= 0 && !lines[lastContent].trim()) lastContent--; + return { visible: !mascot.hidden, suggestionVisible: !mascot.hidden && !document.querySelector('.mascot-suggestion').hidden, + top: m.top, bottom: m.bottom, left: m.left, right: m.right, + contentBottom: screen.top + (lastContent + 1) * rowHeight, statusTop: screen.top + status * rowHeight, + pawBottom: cat.top + cat.height * 1156 / 1250, dividerCenter: screen.top + (status + 1.5) * rowHeight, + inputTop: screen.top + (status + 2) * rowHeight, + screenLeft: screen.left, screenRight: screen.right, overflow: document.documentElement.scrollWidth > innerWidth }; + }); + assert(!layout.overflow); + if ((width === 320 && height === 568) || (width === 390 && height === 844)) assert(layout.suggestionVisible, 'The first suggested task must be visible on a small phone'); + if (layout.visible) { + assert(layout.top >= layout.contentBottom && layout.bottom <= layout.inputTop, JSON.stringify(layout)); + assert(Math.abs(layout.pawBottom - layout.dividerCenter) < 3, JSON.stringify(layout)); + assert(layout.left >= layout.screenLeft && layout.right <= layout.screenRight + 1); + } + if ([1440,390,320].includes(width)) await page.screenshot({ path: `../validation/${label}-${width}x${height}.png`, fullPage: true }); + result.layouts.push({ width, height, ...layout }); + } + result.checks.push('Seven viewports keep the cat on the input divider without covering the editor; short viewports prioritize the editor'); + + await page.setViewportSize({ width: 1440, height: 1000 }); await visible(); + await page.evaluate(() => window.browserPi.rpc('shell', { command: 'rm /workspace/products.json' })); + await page.waitForFunction(() => document.querySelector('.mascot-suggestion').textContent.includes('explore')); + await page.evaluate(() => window.browserPi.rpc('shell', { command: 'rm /workspace/sales.csv' })); + await page.waitForFunction(() => document.querySelector('.mascot-suggestion').textContent.includes('explore')); + result.checks.push('Starter prompt follows actual workspace files'); + // Seed history in this test-owned browser to exercise the real restore path. + await page.evaluate(async () => { + const saved = await window.browserPi.rpc('snapshot'); + saved.messages = [{ role: 'user', timestamp: Date.now(), content: [{ type: 'text', text: 'Saved conversation' }] }]; + const db = await new Promise((resolve, reject) => { const r = indexedDB.open('minicpm5-pi-workspace', 1); r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); }); + await new Promise((resolve, reject) => { const tx = db.transaction('state', 'readwrite'); tx.objectStore('state').put(saved, 'current'); tx.oncomplete = resolve; tx.onerror = () => reject(tx.error); }); + db.close(); + }); + await page.reload(); await ready(); + assert(!await page.locator('.empty-mascot').isVisible()); + assert.equal(await page.locator('.empty-mascot img').getAttribute('src'), null); + await page.locator('#new-chat').click(); await visible(); + assert.match(await page.locator('.mascot-suggestion').textContent(), /explore/); + result.checks.push('Restored user history hides the mascot without fetching its image; New chat brings it back'); + await page.locator('.xterm-helper-textarea').focus(); + for (let i = 0; i < 12; i++) { await page.keyboard.type(`Draft line ${i}`); await page.keyboard.press('Shift+Enter'); } + await page.setViewportSize({ width: 390, height: 420 }); + await page.waitForFunction(() => document.querySelector('.empty-mascot').hidden); + assert((await page.evaluate(() => window.browserPi.terminal.readScreen())).includes('Draft line 11')); + result.checks.push('Multiline drafts and keyboard-sized viewports stay unobstructed'); + assert.deepEqual(result.errors, []); result.passed = true; + console.log(JSON.stringify({ passed: true, checks: result.checks })); +} catch (error) { result.failure = error.stack; await page.screenshot({ path: `../validation/${label}-failure.png`, fullPage: true }); throw error; } +finally { releaseImage?.(); await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result, null, 2)); await browser.close(); } diff --git a/app/tests/modal-cat.mjs b/app/tests/modal-cat.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fc47f9f2899937032add8dac3cab6fb12d8e96c5 --- /dev/null +++ b/app/tests/modal-cat.mjs @@ -0,0 +1,134 @@ +import { chromium, webkit } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/'; +const label = process.argv[3] ?? 'agent-modal-cat'; +const result = { url, checks: [], layouts: [], errors: [] }; +const webkitRoot = process.env.WEBKIT_MINIBROWSER_ROOT; +for (const engine of ['chromium', ...(process.env.TEST_WEBKIT ? ['webkit'] : [])]) { + const browser = engine === 'chromium' + ? await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true, args: ['--disable-gpu', '--disable-software-rasterizer'] }) + : await webkit.launch({ headless: true, ...(webkitRoot ? { executablePath: webkitRoot + '/bin/MiniBrowser', env: { ...process.env, + WEBKIT_EXEC_PATH: webkitRoot + '/bin', WEBKIT_INJECTED_BUNDLE_PATH: webkitRoot + '/lib', WEBKIT_INSPECTOR_RESOURCES_PATH: webkitRoot + '/share', + LD_LIBRARY_PATH: webkitRoot + '/lib:' + webkitRoot + '/sys/lib:' + (process.env.WEBKIT_EXTRA_LIBS ?? '') } } : {}) }); + const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); + const requests = []; + const catRequests = []; + page.on('request', r => { + requests.push(r.url()); + if (r.url().includes('modal-cat') && !r.redirectedFrom()) catRequests.push(r.url()); + }); + page.on('pageerror', e => result.errors.push(e.message)); + let releaseImage; + try { + const imageGate = new Promise(resolve => { releaseImage = resolve; }); + await page.route('**/*modal-cat*.png', async route => { await imageGate; await route.continue(); }); + await page.goto(url, { waitUntil: 'domcontentloaded' }); await page.waitForFunction(() => window.browserPi?.terminal); await page.evaluate(() => window.browserPi.ready); + assert(requests.some(u => u.includes('modal-cat')), 'The sprite must start loading before any interaction'); + assert(await page.locator('link[rel="preload"][as="image"]').evaluate(link => link.href === document.querySelector('.setup-cat img').src)); + const prompt = "What's our total sales revenue?"; + await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.type(prompt); await page.locator('#send').click(); + await page.locator('#model-dialog[open]').waitFor(); + assert.equal(await page.locator('.setup-cat img').evaluate(el => getComputedStyle(el).opacity), '0'); + assert(await page.locator('#model-confirm').evaluate(el => document.activeElement === el)); + await page.locator('#model-cancel').focus(); await page.keyboard.press('Enter'); + assert.equal(await page.evaluate(() => window.browserPi.terminal.text), prompt); + releaseImage(); + await page.waitForFunction(() => document.querySelector('.setup-cat').classList.contains('is-ready')); + assert(await page.locator('#model-dialog').isHidden()); + assert.equal(await page.locator('.setup-cat-tail').evaluate(el => el.getAnimations().length), 0); + await page.evaluate(() => { + const dialog = document.querySelector('#model-dialog'); + const observer = new MutationObserver(() => { + if (!dialog.open) return; + const img = dialog.querySelector('.setup-cat img'); + window.catAtModalOpen = img.complete && img.naturalWidth > 0 && getComputedStyle(img).opacity === '1'; + observer.disconnect(); + }); + observer.observe(dialog, { attributes: true, attributeFilter: ['open'] }); + }); + await page.locator('#send').click(); + await page.locator('#model-dialog[open]').waitFor(); + assert.equal(await page.evaluate(() => window.catAtModalOpen), true, 'The decoded cat must be visible at modal opening'); + assert.equal(await page.locator('#model-cancel').getAttribute('aria-label'), 'Close model setup'); + assert.equal(await page.locator('#model-cancel svg').count(), 1); + await page.keyboard.press('Shift+Tab'); + assert(await page.locator('.setup-credits a:last-child').evaluate(el => document.activeElement === el)); + await page.keyboard.press('Tab'); + assert(await page.locator('#model-confirm').evaluate(el => document.activeElement === el)); + assert.equal(catRequests.length, 1, 'Preload and image must reuse the same request'); + assert.equal(await page.locator('.setup-cat img').getAttribute('alt'), ''); + assert.equal(await page.locator('.setup-cat').getAttribute('aria-hidden'), 'true'); + // Spaces may redirect assets to a CDN, which taints a DOM image's canvas. + // Inspect the same response bytes without changing the displayed sprite. + const sprite = await page.request.get(await page.locator('.setup-cat img').evaluate(img => img.currentSrc)); + assert(sprite.ok()); + const alpha = await page.evaluate(async source => { + const img = new Image(); img.src = source; await img.decode(); + const canvas = document.createElement('canvas'); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; + const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); + return [[0,0],[1253,0],[0,1253],[1253,1253]].map(([x,y]) => ctx.getImageData(x,y,1,1).data[3]); + }, 'data:image/png;base64,' + (await sprite.body()).toString('base64')); + assert.deepEqual(alpha, [0,0,0,0]); + result.checks.push(engine + ': sprite preloads once at page startup and decodes while closed; visible at modal opening; slow image does not block Cancel; transparent PNG adds no focus stop'); + const tailFrames = await page.locator('.setup-cat-tail').evaluate(el => { + const animation = el.getAnimations()[0]; animation.pause(); + return [0, 2970, 3690, 4500].map(time => { + animation.currentTime = time; + return { transform: getComputedStyle(el).transform, body: getComputedStyle(el.nextElementSibling).transform }; + }); + }); + assert(tailFrames.every(frame => frame.body === 'none')); + assert.notEqual(tailFrames[0].transform, tailFrames[1].transform); + assert.notEqual(tailFrames[1].transform, tailFrames[2].transform); + assert.equal(tailFrames[0].transform, tailFrames[3].transform); + await page.emulateMedia({ reducedMotion: 'reduce' }); + assert.equal(await page.locator('.setup-cat-tail').evaluate(el => el.getAnimations().length), 0); + await page.emulateMedia({ reducedMotion: 'no-preference' }); + result.checks.push(engine + ': only the tail swishes and settles; animation is absent while closed or with reduced motion'); + for (const [width, height] of [[1440,1000],[1024,768],[850,640],[390,844],[375,667],[320,568],[390,420],[390,320]]) { + await page.setViewportSize({ width, height }); + const layout = await page.evaluate(() => { + const rect = s => document.querySelector(s).getBoundingClientRect().toJSON(); + return { dialog: rect('#model-dialog'), cat: rect('.setup-cat'), title: rect('#model-title'), actions: rect('.setup-actions'), confirm: rect('#model-confirm'), close: rect('#model-cancel'), body: rect('.setup-body'), facts: rect('.setup-facts'), + overflow: document.documentElement.scrollWidth > innerWidth, + blend: getComputedStyle(document.querySelector('.setup-cat img')).mixBlendMode }; + }); + assert(!layout.overflow); + assert(layout.cat.top >= 8 && layout.cat.right <= width - 8, JSON.stringify(layout)); + assert(layout.dialog.bottom <= height - 8 && layout.dialog.left >= 8, JSON.stringify(layout)); + assert(layout.actions.bottom <= height - 8 && layout.actions.top >= layout.dialog.top, JSON.stringify(layout)); + assert(layout.cat.bottom <= layout.title.top + 1, JSON.stringify(layout)); + assert(Math.abs(layout.confirm.width - layout.body.width) < 1, 'Primary action should fill the modal content width'); + assert(layout.close.right <= layout.dialog.right && layout.close.bottom <= layout.body.top && layout.close.left >= layout.title.right, JSON.stringify(layout)); + if (height >= 568) assert(layout.facts.bottom <= layout.body.bottom + 1, 'The full download note should fit: ' + JSON.stringify(layout)); + assert.equal(layout.blend, 'normal'); + await page.screenshot({ path: `../validation/${label}-${engine}-${width}x${height}.png` }); + result.layouts.push({ engine, width, height, ...layout }); + } + await page.setViewportSize({ width: 390, height: 420 }); + await page.locator('#model-confirm').click(); + await page.locator('#model-error').waitFor({ state: 'visible' }); + assert.match(await page.locator('#model-error').textContent(), /WebGPU/); + assert.equal(await page.locator('#model-confirm').textContent(), 'Try again'); + assert.equal(await page.locator('#model-cancel svg').count(), 1); + assert(await page.locator('#model-cancel').isVisible()); + assert(await page.locator('.setup-cat.is-ready').isVisible()); + await page.screenshot({ path: `../validation/${label}-${engine}-error.png` }); + await page.locator('#model-cancel').click(); + assert.equal(await page.locator('.setup-cat-tail').evaluate(el => el.getAnimations().length), 0); + assert.equal(await page.evaluate(() => window.browserPi.terminal.text), prompt); + assert(!requests.some(u => /\/resolve\/|\/models\//.test(u))); + result.checks.push(engine + ': eight viewport sizes keep the cat and actions in bounds; real GPU failure keeps retry and cancel usable'); + } catch (e) { + result.failure = e.stack; process.exitCode = 1; + await page.screenshot({ path: `../validation/${label}-${engine}-failure.png` }).catch(() => {}); + } finally { + releaseImage?.(); await browser.close(); + await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result, null, 2)); + } +} +result.passed = !result.failure && !result.errors.length; +await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result, null, 2)); +console.log(JSON.stringify({ passed: result.passed, checks: result.checks, failure: result.failure })); diff --git a/app/tests/model-probe.mjs b/app/tests/model-probe.mjs new file mode 100644 index 0000000000000000000000000000000000000000..74dc70e80d8ac5cdece1dee85c124f0a05ad6240 --- /dev/null +++ b/app/tests/model-probe.mjs @@ -0,0 +1,36 @@ +// Local audit harness; no UI state or production configuration is changed. +import { AutoTokenizer, AutoModelForCausalLM, env, random } from '@huggingface/transformers'; +import { prepareModelCache } from '../src/download.mjs'; +import { nucleusProcessor } from '../src/sampling.mjs'; +let tokenizer, model; +export async function loadProbe({ name = 'minicpm5-webgpu', limit128 = false } = {}) { + if (!['127.0.0.1', 'localhost'].includes(location.hostname)) throw Error('Local audit only.'); + if (!['minicpm5-webgpu', 'minicpm5-head-fp16'].includes(name)) throw Error('Unknown audit model.'); + if (limit128) { + const requestDevice = GPUAdapter.prototype.requestDevice; + GPUAdapter.prototype.requestDevice = function (descriptor = {}) { + return requestDevice.call(this, { ...descriptor, requiredLimits: { ...descriptor.requiredLimits, + maxStorageBufferBindingSize: 128 * 1024 ** 2, maxBufferSize: 256 * 1024 ** 2 } }); + }; + } + env.allowLocalModels = false; env.allowRemoteModels = true; + env.remoteHost = location.origin + '/'; env.remotePathTemplate = 'models/{model}/'; + if (name === 'minicpm5-webgpu') env.customCache = await prepareModelCache(location.origin + '/models/minicpm5-webgpu/', {signal: new AbortController().signal}); + env.useCustomCache = name === 'minicpm5-webgpu'; env.useBrowserCache = false; + env.backends.onnx.wasm.wasmPaths = location.origin + '/runtime/'; env.backends.onnx.wasm.numThreads = 1; + tokenizer = await AutoTokenizer.from_pretrained(name); + model = await AutoModelForCausalLM.from_pretrained(name, {device:'webgpu',dtype:'q4f16'}); + const limits = env.backends.onnx.webgpu.device.limits; + return {name, maxStorageBufferBindingSize:limits.maxStorageBufferBindingSize, maxBufferSize:limits.maxBufferSize}; +} +export async function runProbe(fixture, {thinking, sample, penalty=1, seed=42, maxTokens=1024}) { + random.seed(seed); + const inputs = tokenizer.apply_chat_template(fixture.messages, {tools:fixture.tools, enable_thinking:thinking, add_generation_prompt:true, return_dict:true}); + const started = performance.now(); + const output = await model.generate({...inputs,max_new_tokens:maxTokens,do_sample:sample,temperature:1,top_k:0,top_p:.95, + repetition_penalty:penalty,logits_processor:sample?[nucleusProcessor(.95)]:[],eos_token_id:[1,130073]}); + const ids=output.tolist()[0].slice(inputs.input_ids.dims[1]).map(Number); + return {case:fixture.name,thinking,sample,penalty,seed,input_tokens:inputs.input_ids.dims[1],output_tokens:ids.length, + elapsed_s:(performance.now()-started)/1000,ended:[1,130073].includes(ids.at(-1)),raw:tokenizer.decode(ids,{skip_special_tokens:false}),ids}; +} +export async function disposeProbe(){await model?.dispose();} diff --git a/app/tests/no-gpu.mjs b/app/tests/no-gpu.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4fa3be8ff8cc7ba690d31bb55a0953098a2480ae --- /dev/null +++ b/app/tests/no-gpu.mjs @@ -0,0 +1,20 @@ +import { chromium } from 'playwright'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true, + args: ['--disable-gpu', '--disable-software-rasterizer'] }); +try { + const page = await browser.newPage(); + const requests = []; page.on('request', request => requests.push(request.url())); + await page.goto('http://127.0.0.1:4173/'); + await page.waitForFunction(() => window.browserPi); await page.evaluate(() => window.browserPi.ready); + await page.locator('#load').click(); + await page.waitForFunction(() => document.querySelector('#notice').textContent.includes('WebGPU')); + assert.equal(await page.evaluate(() => window.browserPi.loaded), false); + await page.locator('#command').fill('echo shell-still-works'); await page.locator('#shell-run').click(); + await page.waitForFunction(() => document.querySelector('#terminal-output').textContent.includes('[exit 0]')); + const message = await page.locator('#notice').textContent(); + assert(!requests.some(url => url.includes('huggingface.co'))); + await fs.writeFile('../validation/agent-browser-no-gpu.json', JSON.stringify({ passed: true, message, shellWorks: true, modelRequests: 0 }, null, 2)); + console.log('Unavailable GPU: actionable error; shell works; no model download.'); +} finally { await browser.close(); } diff --git a/app/tests/protocol.test.mjs b/app/tests/protocol.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c1bde359849e9179698127b1b0c961716c5d5971 --- /dev/null +++ b/app/tests/protocol.test.mjs @@ -0,0 +1,129 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { parseCompletion, splitThinking, toMiniMessages, fitContext } from '../src/protocol.mjs'; +import { createWorkspace } from '../src/workspace.mjs'; +import { renderMarkdown } from '../src/markdown.mjs'; +const { tools } = createWorkspace(); +test('read results identify the real file through relative paths and symlinks', async () => { + const workspace = createWorkspace(); + await workspace.write('nested/name%20#é.txt', ''); + await workspace.bash.exec("ln -s 'nested/name%20#é.txt' link.txt"); + const read = workspace.tools.find(tool => tool.name === 'read'); + const result = await read.execute('read-path', { path: './link.txt' }); + assert.equal(result.details.path, '/workspace/nested/name%20#é.txt'); + assert.equal(result.content[0].text, ''); + await assert.rejects(read.execute('missing', { path: 'missing.txt' })); +}); +test('model Markdown cannot execute HTML or request remote images', () => { + const html = renderMarkdown('\n![secret](https://example.com/track)\n[x](javascript:alert(1))'); + assert(!html.includes(''; + await run("printf '%s\\n' '"+hostile+"'"); + assert.equal(await page.locator('.shell-entry:last-child .shell-stdout').textContent(),hostile+'\n'); + assert.equal(await page.locator('#terminal-output img, #terminal-output script, #command-highlight img').count(),0); + await run("printf 'before\\033[2Jafter\\n'"); + assert.equal(await page.locator('.shell-entry:last-child .shell-stdout').textContent(),'beforeafter\n'); + result.checks.push('Command/file HTML is inert text; terminal escape sequences cannot alter the page'); + + await page.locator('#editor').fill('An unsaved edit'); + await run('printf should-not-run'); + assert.match(await page.locator('.shell-entry:last-child .shell-stderr').textContent(),/Save your file edits/); + assert.equal(await input.inputValue(),'printf should-not-run'); + await page.locator('#save').click(); await page.waitForFunction(()=>!window.browserPi.busy && document.querySelector('#save').disabled); + await page.locator('#shell-clear').click(); assert.equal(await page.locator('.shell-entry').count(),0); + await run('printf "workspace-ready\\n"'); + await input.press('Control+l'); assert.equal(await page.locator('.shell-entry').count(),0); + result.checks.push('Unsaved file edits block execution without losing the command; Clear and Ctrl+L clear only output'); + + await run('ls -la'); + await run('printf "Hello from the browser\\n"'); + const draft='NAME="世界 🦙"\nprintf "%s\\n" "$NAME" | cat -n'; + await input.fill(draft); + for(const [width,height] of [[1440,1000],[851,640],[850,640],[390,844],[320,568]]) { + await page.setViewportSize({width,height}); await page.waitForTimeout(100); + const g=await geometry(); assert(g.sameOrigin && g.sameWidth && g.sameFont && g.samePadding && g.sameScroll && g.sameText && g.fits && !g.overflow,JSON.stringify({width,...g})); + if([1440,390,320].includes(width)) await page.screenshot({path:`../validation/${label}-${width}x${height}.png`,fullPage:true}); + } + const long=Array.from({length:16},(_,i)=>`printf 'line ${i} 世界\\n'`).join('\n'); + await input.fill(long); await input.evaluate(el=>{el.scrollTop=el.scrollHeight;el.dispatchEvent(new Event('scroll'));}); + assert((await geometry()).sameScroll); + await page.locator('.workspace > .terminal summary').click(); await page.locator('.workspace > .terminal summary').click(); + assert.equal(await input.inputValue(),long); + result.checks.push('Five viewport sizes preserve input/highlight alignment, Unicode, scrolling and drafts through collapse/expand'); + const touch = await browser.newContext({ viewport: {width:390,height:844}, isMobile:true, hasTouch:true }); + const phone = await touch.newPage(); phone.on('pageerror', e=>result.errors.push(e.stack)); + await phone.goto(url); await phone.waitForFunction(()=>window.browserPi?.terminal); await phone.evaluate(()=>window.browserPi.ready); + await phone.locator('#command').fill(draft); + const touchLayout = await phone.evaluate(()=>{ + const load=document.querySelector('#load').getBoundingClientRect(), header=document.querySelector('header').getBoundingClientRect(); + const input=getComputedStyle(document.querySelector('#command')), highlight=getComputedStyle(document.querySelector('#command-highlight')); + return { fits:load.bottom<=header.bottom && document.documentElement.scrollWidth<=innerWidth, font:input.fontSize, matches:input.font===highlight.font }; + }); + assert(touchLayout.fits && touchLayout.matches && touchLayout.font==='16px',JSON.stringify(touchLayout)); + await phone.screenshot({path:`../validation/${label}-touch.png`,fullPage:true}); await touch.close(); + result.checks.push('Touch simulation keeps model status within the top bar and uses aligned 16px command text'); + assert.equal(result.errors.length,0); result.passed=true; console.log(JSON.stringify({passed:true,checks:result.checks})); +} catch(error) {result.failure=error.stack; await page.screenshot({path:`../validation/${label}-failure.png`,fullPage:true}); throw error;} +finally {await fs.writeFile(`../validation/${label}.json`,JSON.stringify(result,null,2)); await browser.close();} diff --git a/app/tests/space-diagnose.mjs b/app/tests/space-diagnose.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d8e43fb6eb97b8bd9abe655fed60a9ddc19810ce --- /dev/null +++ b/app/tests/space-diagnose.mjs @@ -0,0 +1,33 @@ +import {chromium} from 'playwright'; +import fs from 'node:fs/promises'; +const context=await chromium.launchPersistentContext('../validation/agent-browser-profile/space',{executablePath:'/usr/bin/chromium',headless:true,args:['--enable-unsafe-webgpu','--use-angle=vulkan','--enable-features=Vulkan','--disable-vulkan-surface']}); +try { + const page=await context.newPage(); + page.on('console',m=>{if(m.type()==='error')console.log(m.text().slice(0,1000));}); + await page.goto('https://huggingface.co/spaces/Mike0021/MiniCPM5-2B-WebGPU-Pi'); + await page.waitForTimeout(2000); + console.log('IFRAMES',await page.locator('iframe').evaluateAll(es=>es.map(e=>({src:e.src,allow:e.allow,sandbox:e.sandbox.value})))); + const app=page.frames().find(f=>f.url().includes('minicpm5-2b-webgpu-pi.')&&f.url().includes('hf.space')); + await app.waitForFunction(()=>window.browserPi);await app.evaluate(()=>window.browserPi.ready); + console.log('NOTICE',await app.locator('#notice').textContent()); + const probes=await app.evaluate(async()=>{ + const probe=async()=>{ + const checks={}; + const check=async(name,fn)=>{try{checks[name]=await fn();}catch(e){checks[name]={name:e.name,message:e.message,stack:e.stack};}}; + await check('opfs',async()=>{const root=await navigator.storage.getDirectory();const h=await root.getFileHandle('probe',{create:true});const w=await h.createWritable();await w.write('probe');await w.close();return (await h.getFile()).size;}); + await check('estimate',()=>navigator.storage.estimate()); + await check('locks',()=>navigator.locks.request('probe',()=>true)); + await check('gpu',async()=>{const a=await navigator.gpu.requestAdapter();return a?{features:[...a.features]}:null;}); + return checks; + }; + const main=await probe(); + const body='('+probe.toString()+')().then(r=>postMessage(r))'; + const worker=await new Promise((resolve,reject)=>{const w=new Worker(URL.createObjectURL(new Blob([body],{type:'text/javascript'})));w.onmessage=e=>{w.terminate();resolve(e.data)};w.onerror=reject;}); + let access;try{access=await document.hasStorageAccess();}catch(e){access=e.message;} + return {main,worker,access,policy:document.permissionsPolicy?.allowedFeatures?.()}; + }); + console.log('PROBES',JSON.stringify(probes,null,2)); + try{await app.evaluate(()=>window.browserPi.load());}catch(e){console.log('LOAD',e.message);} + console.log('DIAGNOSTICS',await app.evaluate(()=>({notice:document.querySelector('#notice').textContent,load:document.querySelector('#load-status').textContent,progress:document.querySelector('#load-detail').textContent,device:window.browserPi.diagnostics.device}))); + await fs.writeFile('../validation/agent-space-diagnose.json',JSON.stringify(probes,null,2)); +}finally{await context.close();} diff --git a/app/tests/space-embedded.mjs b/app/tests/space-embedded.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8c31f22b9052851b0a7d13632d3d2eb61798ca8e --- /dev/null +++ b/app/tests/space-embedded.mjs @@ -0,0 +1,94 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import path from 'node:path'; + +// Playwright 1.58 disables ThirdPartyStoragePartitioning by default. Restore +// Chromium's normal partitioning for a representative cross-site iframe test. +const require = createRequire(import.meta.url); +const { chromiumSwitches } = require(path.join(path.dirname(require.resolve('playwright-core/package.json')), 'lib/server/chromium/chromiumSwitches.js')); +const disabledFeatures = chromiumSwitches(false).find(arg => arg.startsWith('--disable-features=')); + +const url = 'https://huggingface.co/spaces/Mike0021/MiniCPM5-2B-WebGPU-Pi'; +const label = process.argv[2] ?? 'agent-space-embedded'; +const firstMessage = process.argv.includes('--first-message'); +const result = { date: new Date().toISOString(), url, firstMessage }; +const context = await chromium.launchPersistentContext('../validation/agent-browser-profile/space', { + executablePath: '/usr/bin/chromium', headless: true, viewport: { width: 1440, height: 1080 }, + ignoreDefaultArgs: [disabledFeatures], + args: [disabledFeatures.replace('ThirdPartyStoragePartitioning,', ''), '--enable-unsafe-webgpu', '--use-angle=vulkan', '--enable-features=Vulkan', '--disable-vulkan-surface'], +}); +context.setDefaultTimeout(240_000); +try { + const page = await context.newPage(); + await page.goto(url, { waitUntil: 'domcontentloaded' }); + console.log('Hugging Face page opened'); + await page.waitForFunction(() => [...document.querySelectorAll('iframe')].some(frame => frame.src.includes('minicpm5-2b-webgpu-pi'))); + // Hugging Face can replace its initial iframe while the parent initializes. + let app; + for (let attempt = 0; attempt < 4; attempt++) { + const element = await page.waitForSelector('iframe[src*="minicpm5-2b-webgpu-pi"]'); + app = await element.contentFrame(); + assert(app, 'The deployed Hugging Face app frame must exist.'); + try { + await app.waitForFunction(() => window.browserPi?.terminal); + await app.evaluate(() => window.browserPi.ready); + break; + } catch (error) { + if (attempt === 3 || !/detached|context was destroyed/i.test(error.message)) throw error; + } + } + result.frameUrl = app.url(); + result.cachedBeforeSend = await app.evaluate(() => window.browserPi.rpc('cache_status')); + console.log('App initialized'); + const task = 'Read sales.csv, calculate total revenue using bash, and save a short report to report.md. Verify the file.'; + if (firstMessage) { + await app.evaluate(() => document.querySelector('#new-chat').onclick()); + await app.evaluate(() => window.browserPi.rpc('shell', { command: 'rm -f /workspace/report.md' })); + // Activate the iframe with a real click before sending keyboard events. + await app.locator('#pi-terminal').click(); + await app.locator('.xterm-helper-textarea').focus(); await page.keyboard.type(task); + await app.waitForFunction(text => window.browserPi.terminal.text === text, task, { timeout: 15_000 }); + console.log('First message typed'); + await app.locator('#send').click(); + if (!result.cachedBeforeSend) { + await app.waitForFunction(() => document.querySelector('#model-dialog').open); + console.log('First-message modal opened'); + assert.equal(await app.locator('#model-preview').textContent(), task); + await page.screenshot({ path: `../validation/${label}-modal.png`, fullPage: true }); + } + } + const start = Date.now(); + if (!firstMessage || !result.cachedBeforeSend) await app.locator(firstMessage ? '#model-confirm' : '#load').click(); + await app.waitForFunction(() => window.browserPi.loaded || (!window.browserPi.busy && (document.querySelector('#notice').textContent || !document.querySelector('#model-error').hidden))); + assert.equal(await app.evaluate(() => window.browserPi.loaded), true, await app.locator('#load-status').textContent()); + result.loadMs = Date.now() - start; + result.device = await app.evaluate(() => window.browserPi.diagnostics.device); + if (!firstMessage) { + await app.waitForFunction(() => !window.browserPi.busy); + // Await the async UI handler: checking !busy immediately after a click can + // precede the worker's busy event and race the next setup command. + await app.evaluate(() => document.querySelector('#new-chat').onclick()); + await app.evaluate(() => window.browserPi.rpc('shell', { command: 'rm -f /workspace/report.md' })); + await app.locator('.xterm-helper-textarea').focus(); + await page.keyboard.type(task); + await app.locator('#send').click(); + await app.waitForFunction(() => window.browserPi.busy); + await app.waitForFunction(() => !window.browserPi.busy); + } else { + await app.waitForFunction(() => window.browserPi.diagnostics.events.includes('agent_end') && !window.browserPi.busy); + assert.equal(await app.locator('#model-dialog').evaluate(el => el.open), false); + } + const state = await app.evaluate(() => window.browserPi.rpc('snapshot')); + result.messages = state.messages; result.report = state.files['/workspace/report.md']; + result.terminalScreen = await app.evaluate(() => window.browserPi.terminal.readScreen()); + assert.equal(state.messages.filter(m => m.role === 'user').length, 1); + assert.match(result.report ?? '', /144/); + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'bash' && !m.isError)); + assert(state.messages.filter(m => m.role === 'assistant').at(-1).content.some(c => c.type === 'text' && c.text.includes('144'))); + await page.screenshot({ path: `../validation/${label}.png`, fullPage: true }); + result.passed = true; + console.log('Embedded Hugging Face Space: real UI → Pi → WebGPU → bash → verified report passed.'); +} catch (error) { result.failure = error.stack; throw error; } +finally { await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result, null, 2)); await context.close(); } diff --git a/app/tests/space-restricted.mjs b/app/tests/space-restricted.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e90cf65e96ab41d02f9452d09390fb2cbcb26845 --- /dev/null +++ b/app/tests/space-restricted.mjs @@ -0,0 +1,37 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +// Playwright 1.58's default ThirdPartyStoragePartitioning disable flag exposes +// the denied third-party-storage path. Check the actual public Space's escape +// link, then execute the model/tool workflow in the opened top-level app. +const context = await chromium.launchPersistentContext('../validation/agent-browser-profile/space', { + executablePath: '/usr/bin/chromium', headless: true, + args: ['--enable-unsafe-webgpu', '--use-angle=vulkan', '--enable-features=Vulkan', '--disable-vulkan-surface'], +}); +context.setDefaultTimeout(180_000); +const result = { date: new Date().toISOString() }; +try { + const page = await context.newPage(); + await page.goto('https://huggingface.co/spaces/Mike0021/MiniCPM5-2B-WebGPU-Pi', { waitUntil: 'load' }); + const frame = page.frameLocator('iframe[src*="minicpm5-2b-webgpu-pi"]'); + await frame.locator('#open-tab').waitFor({ state: 'visible' }); + result.embeddedNotice = await frame.locator('#notice').textContent(); + assert.match(result.embeddedNotice, /blocked storage/); + const opened = context.waitForEvent('page'); + await frame.locator('#open-tab').click(); + const app = await opened; + await app.waitForLoadState('load'); await app.waitForFunction(() => window.browserPi); + await app.evaluate(() => window.browserPi.ready); + assert.equal(new URL(app.url()).hostname, 'mike0021-minicpm5-2b-webgpu-pi.static.hf.space'); + await app.locator('#load').click(); await app.waitForFunction(() => window.browserPi.loaded); + await app.locator('#new-chat').click(); await app.waitForFunction(() => !window.browserPi.busy); + const token = 'CHECK-' + crypto.randomUUID().slice(0, 8); + await app.evaluate(token => window.browserPi.rpc('write', { path: '/workspace/check.txt', content: token }), token); + const state = await app.evaluate(() => window.browserPi.prompt('Read check.txt with the read tool and tell me the exact contents.')); + assert(state.messages.some(m => m.role === 'toolResult' && m.toolName === 'read' && !m.isError)); + assert(state.messages.filter(m => m.role === 'assistant').at(-1).content.some(c => c.text?.includes(token))); + result.messages = state.messages; result.openedUrl = app.url(); result.passed = true; + console.log('Restricted embed → new-tab link → real Pi/model tool execution passed.'); +} catch (error) { result.failure = error.stack; throw error; } +finally { await fs.writeFile('../validation/agent-space-restricted.json', JSON.stringify(result, null, 2)); await context.close(); } diff --git a/app/tests/starter-products.mjs b/app/tests/starter-products.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4f021b3fc8bf201b8bb08031b9252297cc536ec2 --- /dev/null +++ b/app/tests/starter-products.mjs @@ -0,0 +1,97 @@ +import { chromium } from 'playwright'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import { legacyProductsCsv, legacyProductsJson, legacyCostProductsJson, legacySalesCsv, legacyWorkspaceReadme, legacyProfitReadme } from '../src/workspace.mjs'; + +const url = process.argv[2] ?? 'http://127.0.0.1:4173/'; +const label = process.argv[3] ?? 'agent-starter-products'; +const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +const result = { url, checks: [], errors: [] }; +page.on('pageerror', error => result.errors.push(error.message)); +const ready = async () => { await page.waitForFunction(() => window.browserPi); await page.evaluate(() => window.browserPi.ready); }; +const rpc = (action, args) => page.evaluate(({ action, args }) => window.browserPi.rpc(action, args), { action, args }); +async function restore(state) { + await page.evaluate(async state => { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open('minicpm5-pi-workspace', 1); + request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); + }); + await new Promise((resolve, reject) => { + const tx = db.transaction('state', 'readwrite'); tx.objectStore('state').put(state, 'current'); + tx.oncomplete = resolve; tx.onerror = () => reject(tx.error); + }); + db.close(); + }, state); + await page.reload(); await ready(); + return rpc('snapshot'); +} +const sales = '/workspace/sales.csv', json = '/workspace/products.json', csv = '/workspace/products.csv', readme = '/workspace/README.md'; +const messages = [{ role: 'user', content: [{ type: 'text', text: 'Keep this conversation' }], timestamp: 1 }]; +const legacy = (files, demoVersion = 3) => ({ version: 1, demoVersion, files, messages }); +try { + await page.goto(url); await ready(); + const fresh = await rpc('snapshot'), records = JSON.parse(fresh.files[json]); + assert.equal(fresh.demoVersion, 4); + assert.equal(fresh.files[sales], 'product,units\nNotebook,12\nPencil,30\nFolder,8\n'); + assert.deepEqual(records.map(p => [p.product, p.price]), [['Notebook',5],['Pencil',2],['Folder',3],['Eraser',1.5],['Stapler',4.99],['Ruler',2.5]]); + assert(records.every(p => Object.keys(p).sort().join(',') === 'price,product')); + assert.equal(fresh.files[readme], '# Browser workspace\n\nYour files are saved in this browser.\n'); + assert.equal(fresh.files[csv], undefined); + await page.locator('.mascot-suggestion').waitFor({ state: 'visible' }); + assert.equal(await page.locator('.mascot-suggestion').textContent(), 'Ask me to calculate our total sales.'); + await page.getByRole('button', { name: 'products.json', exact: true }).click(); + assert.equal(await page.locator('#editor').inputValue(), fresh.files[json]); + await page.waitForFunction(() => document.querySelector('.editor-input').classList.contains('is-highlighted')); + assert(await page.locator('#editor-highlight .token.property').count()); + await page.screenshot({ path: `../validation/${label}.png`, fullPage: true }); + const total = await rpc('shell', { command: "awk 'NR==FNR {price[$1]=$2; next} FNR>1 {split($0,row,\",\"); if (!(row[1] in price)) exit 1; total += row[2]*price[row[1]]} END {print total}' <(jq -r '.[] | [.product, .price] | @tsv' products.json) sales.csv" }); + assert.equal(total.exitCode, 0); assert.equal(total.stdout.trim(), '144'); + result.checks.push('Same three sales rows and six products; quantities and prices are separate, JSON is highlighted, README has no calculation guidance; jq and awk join both files for 144'); + + for (const [demoVersion, companion, previousReadme] of [[0, {}, legacyWorkspaceReadme], [1, { [csv]: legacyProductsCsv }, legacyWorkspaceReadme], [2, { [json]: legacyProductsJson }, legacyWorkspaceReadme], [3, { [json]: legacyCostProductsJson }, legacyProfitReadme]]) { + const state = await restore(legacy({ [sales]: legacySalesCsv, ...companion, [readme]: previousReadme, '/workspace/notes.txt': 'My notes\n' }, demoVersion)); + assert.equal(state.demoVersion, 4); + assert.deepEqual(state.files, { ...fresh.files, '/workspace/notes.txt': 'My notes\n' }); + assert.deepEqual(state.messages, messages); + await page.reload(); await ready(); + assert.deepEqual((await rpc('snapshot')).files, state.files); + } + result.checks.push('All four untouched starter versions migrate the pair together, remove old README guidance, retain notes/chat, and persist across reload'); + + const editedCosts = legacyCostProductsJson.replace('"unit_cost": 2.5', '"unit_cost": 4'); + const editedSales = legacySalesCsv + 'Eraser,5,1.5\n'; + for (const files of [ + { [sales]: legacySalesCsv, [json]: editedCosts }, + { [sales]: editedSales, [json]: legacyCostProductsJson }, + { [sales]: legacySalesCsv }, + { [json]: legacyCostProductsJson }, + { [sales]: legacySalesCsv, [csv]: 'Custom product data\n' }, + { '/workspace/custom.txt': 'Custom workspace' }, + ]) { + files[readme] = 'My shop notes\n'; + const state = await restore(legacy(files)); + assert.deepEqual(state.files, files); + assert.deepEqual(state.messages, messages); + } + result.checks.push('Edited prices, sales, README, missing companion files and unrelated workspaces are preserved without mixing schemas'); + + await restore(legacy({ [sales]: legacySalesCsv, [json]: legacyCostProductsJson, [readme]: 'Keep my README\n' })); + await rpc('write', { path: sales, content: legacySalesCsv }); + await rpc('write', { path: json, content: editedCosts }); + await rpc('shell', { command: 'mkdir empty; ln -s products.json products-link.json' }); + const serialized = await rpc('snapshot'); + // A stale text snapshot must not override the authoritative serialized files. + const saved = await restore({ ...serialized, demoVersion: 3, files: { [sales]: legacySalesCsv, [json]: legacyCostProductsJson } }); + assert.deepEqual(saved.entries, serialized.entries); + assert.equal(saved.files[json], editedCosts); + assert.equal(saved.files[sales], legacySalesCsv); + await rpc('shell', { command: 'rm products.json; ln -s products-link.json products.json' }); + const symlinks = await rpc('snapshot'); + const preserved = await restore({ ...symlinks, demoVersion: 3 }); + assert.deepEqual(preserved.entries, symlinks.entries); + result.checks.push('Serialized files take precedence over stale snapshots; directories and symlinks stay intact'); + assert.deepEqual(result.errors, []); result.passed = true; + console.log(JSON.stringify(result, null, 2)); +} catch (error) { result.failure = error.stack; throw error; } +finally { await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result, null, 2)); await browser.close(); } diff --git a/app/tests/terminal.mjs b/app/tests/terminal.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c5dcb997773d51d86c4c512a0d6c9ec61bcaa705 --- /dev/null +++ b/app/tests/terminal.mjs @@ -0,0 +1,104 @@ +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import assert from 'node:assert/strict'; + +const url = process.argv[2] ?? process.env.APP_URL ?? 'http://127.0.0.1:4173/'; +const label = process.argv[3] ?? process.env.TEST_LABEL ?? 'agent-terminal'; +const result = { date: new Date().toISOString(), url, errors: [], requests: [], checks: [] }; +const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', headless: true }); +const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); +context.setDefaultTimeout(15_000); +const page = await context.newPage(); +page.on('pageerror', error => { result.errors.push(error.stack); console.log('PAGEERROR', error.stack); }); +page.on('console', message => { if (message.type() === 'error') console.log('CONSOLE', message.text().slice(0, 500)); }); +context.on('request', request => result.requests.push(request.url())); +const screen = () => page.evaluate(() => window.browserPi.terminal.readScreen()); +const text = () => page.evaluate(() => window.browserPi.terminal.text); +async function type(value) { await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.type(value); } +async function waitScreen(value) { await page.waitForFunction(value => window.browserPi.terminal.readScreen().includes(value), value); } +try { + await page.goto(url); + await page.waitForFunction(() => window.browserPi); + await page.evaluate(() => window.browserPi.ready); + await waitScreen('browser workspace'); + result.initial = await screen(); + assert(result.initial.includes('/load')); + result.checks.push('Original Pi TUI rendered through xterm'); + + await type('/help'); await page.keyboard.press('Enter'); await waitScreen('Ctrl+O'); + result.checks.push('Enter submits /help without loading a model'); + await page.keyboard.press('Control+Shift+f'); await type('browser'); + await page.waitForFunction(() => window.browserPi.terminal.text === '' && /\d+\/\d+/.test(window.browserPi.terminal.readScreen())); + await page.keyboard.press('Escape'); await page.waitForTimeout(30); + result.checks.push('Pi fullscreen transcript search preserves the editor draft'); + await type('one'); await page.keyboard.press('Shift+Enter'); await type('two'); + assert.equal(await text(), 'one\ntwo'); + await page.keyboard.press('Backspace'); await page.keyboard.press('Control+a'); await type('X'); + assert.equal(await text(), 'one\nXtw'); + await page.keyboard.press('Control+u'); await page.keyboard.press('Control+k'); + await page.keyboard.press('Backspace'); await page.keyboard.press('Control+u'); + assert.equal(await text(), ''); + result.checks.push('Pi multiline editor: Shift+Enter, cursor, deletion, Ctrl+U/K'); + await page.keyboard.press('Control+p'); assert.equal(await text(), '/help'); + await page.keyboard.press('Control+n'); assert.equal(await text(), ''); + result.checks.push('Pi prompt history'); + await type('/he'); await page.keyboard.press('Tab'); + await page.waitForFunction(() => window.browserPi.terminal.text === '/help '); + await page.keyboard.press('Enter'); await waitScreen('Ctrl+O'); + result.checks.push('Pi autocomplete: /he → /help'); + + await type("!printf 'terminal-works\\n' > terminal.txt; cat terminal.txt"); + await page.keyboard.press('Escape'); // Dismiss optional workspace completion. + await page.waitForTimeout(30); // A lone ESC is delimited by Pi's 10ms input timer. + await page.keyboard.press('Enter'); await waitScreen('[exit 0]'); + await page.waitForFunction(() => !window.browserPi.busy); + const state = await page.evaluate(() => window.browserPi.rpc('snapshot')); + assert.equal(state.files['/workspace/terminal.txt'], 'terminal-works\n'); + assert((await screen()).includes('[exit 0]')); + result.checks.push('xterm keyboard → Pi editor → real just-bash → workspace file'); + + // Model/file text must not be able to clear the terminal or inject OSC URLs. + await type("!printf 'before\\033[2Jafter\\n'"); + await page.locator('#send').click(); await waitScreen('beforeafter'); + result.checks.push('Shell escape sequences render as inert text'); + + // Paste uses xterm's actual bracketed-paste path through Pi's StdinBuffer. + await context.grantPermissions(['clipboard-read', 'clipboard-write']); + const largePaste = '!cat > pasted.txt <<\'EOF\'\n' + Array.from({ length: 15 }, (_, i) => 'row-' + i).join('\n') + '\nEOF'; + await page.evaluate(text => navigator.clipboard.writeText(text), largePaste); + await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.press('Control+v'); + await page.waitForFunction(text => window.browserPi.terminal.text === text, largePaste); + await page.locator('#send').click(); + await page.waitForFunction(() => document.querySelector('#files').textContent.includes('pasted.txt')); + const pastedState = await page.evaluate(() => window.browserPi.rpc('snapshot')); + assert.equal(pastedState.files['/workspace/pasted.txt'], Array.from({ length: 15 }, (_, i) => 'row-' + i).join('\n') + '\n'); + result.checks.push('Large Pi paste markers expand before Send'); + const pasted = 'hello 世界 🦙\nline two'; + await page.evaluate(text => navigator.clipboard.writeText(text), pasted); + await page.locator('.xterm-helper-textarea').focus(); await page.keyboard.press('Control+v'); + await page.waitForFunction(text => window.browserPi.terminal.text === text, pasted); + result.checks.push('Unicode multiline clipboard paste'); + await page.locator('#newline').click(); assert.equal(await text(), pasted + '\n'); + result.checks.push('Touch-accessible newline button'); + + // Resize while preserving a multiline draft and Pi's own viewport renderer. + const desktop = await page.evaluate(() => ({ cols: window.browserPi.terminal.cols, rows: window.browserPi.terminal.rows })); + await page.screenshot({ path: `../validation/${label}-desktop.png`, fullPage: true }); + await page.setViewportSize({ width: 390, height: 844 }); + await page.waitForFunction(cols => window.browserPi.terminal.cols < cols, desktop.cols); + assert.equal(await text(), pasted + '\n'); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + result.sizes = { desktop, mobile: await page.evaluate(() => ({ cols: window.browserPi.terminal.cols, rows: window.browserPi.terminal.rows })) }; + assert(result.sizes.mobile.cols >= 30); assert(result.sizes.mobile.rows >= 15); + await page.screenshot({ path: `../validation/${label}-mobile.png`, fullPage: true }); + result.checks.push('390px layout and live terminal resize preserve the draft'); + result.mobileLimitation = 'Desktop Chromium viewport simulation; physical mobile keyboards and GPUs not tested.'; + assert.equal(result.errors.length, 0); + assert.equal(result.requests.filter(url => /^https?:/.test(url) && new URL(url).origin !== new URL(result.url).origin).length, 0); + result.passed = true; console.log(JSON.stringify({ passed: true, checks: result.checks, sizes: result.sizes })); +} catch (error) { + result.failure = error.stack; + result.screen = await screen().catch(() => 'App failed before initialization'); + await page.screenshot({ path: `../validation/${label}-failure.png`, fullPage: true }); + throw error; +} finally { await fs.writeFile(`../validation/${label}.json`, JSON.stringify(result, null, 2)); await browser.close(); } diff --git a/app/tests/token-rate.test.mjs b/app/tests/token-rate.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1edb64aea87d5fa236af6aa942e524d7b6cdea79 --- /dev/null +++ b/app/tests/token-rate.test.mjs @@ -0,0 +1,29 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { TokenRateWindow } from '../src/token-rate.mjs'; + +test('token rate excludes prefill and waits for a measurable decode interval', () => { + const meter = new TokenRateWindow(); + assert.equal(meter.rate(5000), null); + meter.add(1, 5000); + assert.equal(meter.rate(5100), null); + meter.add(8, 5250); + assert.equal(meter.rate(5250), 32); + meter.add(8, 5500); + assert.equal(meter.rate(5500), 32); +}); + +test('rolling rate follows recent throughput, decays during stalls and keeps bounded history', () => { + const meter = new TokenRateWindow(); + meter.add(1, 0); + for (let at = 100; at <= 1000; at += 100) meter.add(4, at); + assert.equal(meter.rate(1000), 40); + assert.equal(meter.rate(1500), 20); + assert.equal(meter.rate(2000), 0); + meter.add(5, 2100); + assert.equal(meter.rate(2100), 5); + for (let at = 2200; at <= 100000; at += 100) meter.add(1, at); + assert.equal(meter.rate(100000), 10); + assert(meter.points.length <= 11); + assert.equal(new TokenRateWindow().rate(100000), null); +}); diff --git a/app/vendor/pi-coding-agent/LICENSE b/app/vendor/pi-coding-agent/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0a8e9b81083294360c69b4ec45d3d39a2b28197 --- /dev/null +++ b/app/vendor/pi-coding-agent/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Mario Zechner + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/app/vendor/pi-coding-agent/README.md b/app/vendor/pi-coding-agent/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f48e0a8d506cc3d0c0b0c56225e1649f770ad8e9 --- /dev/null +++ b/app/vendor/pi-coding-agent/README.md @@ -0,0 +1,23 @@ +# Pi CLI presentation components + +These files are **unmodified copies** from the published +`@earendil-works/pi-coding-agent@0.85.1` npm tarball, under `dist/modes/interactive/`. +`provenance.json` records their SHA-256 digests. Pi's MIT license is included. + +- `CustomEditor` is the CLI's actual editor subclass, extending `pi-tui`'s editor. +- `UserMessageComponent` and `AssistantMessageComponent` are its actual message renderers. +- `markdown-transform.js` is their upstream helper. +- `light.json` and `dark.json` are the upstream theme palettes; the app uses dark. + +The build redirects their `@earendil-works/pi-tui` import to a selective export +of the installed **real pi-tui** package. It redirects their Node theme service +to `src/pi/theme.mjs`, which uses the dark palette with brighter secondary text, +without filesystem watchers or Node syntax highlighting. The build also makes +Node-only timer `unref()` calls optional in browsers. See `scripts/pi-browser.mjs` +for all host adaptations. The vendored files themselves remain unmodified. + +The rest of the Node CLI is not vendored. Browser shell tool cards, slash-command +dispatch, worker integration, and workspace controls are app code. They do not +claim to implement the full CLI's sessions, extensions, or provider management. + +Upstream: https://github.com/earendil-works/pi/tree/v0.85.1/packages/coding-agent diff --git a/app/vendor/pi-coding-agent/components/assistant-message.js b/app/vendor/pi-coding-agent/components/assistant-message.js new file mode 100644 index 0000000000000000000000000000000000000000..62800843f775dc32b0008178d2941aab04a34989 --- /dev/null +++ b/app/vendor/pi-coding-agent/components/assistant-message.js @@ -0,0 +1,158 @@ +import { Container, Markdown, MouseRegion, Spacer, Text } from "@earendil-works/pi-tui"; +import { getMarkdownTheme, theme } from "../theme/theme.js"; +import { createMarkdownTransform } from "./markdown-transform.js"; +const OSC133_ZONE_START = "\x1b]133;A\x07"; +const OSC133_ZONE_END = "\x1b]133;B\x07"; +const OSC133_ZONE_FINAL = "\x1b]133;C\x07"; +/** + * Component that renders a complete assistant message + */ +export class AssistantMessageComponent extends Container { + contentContainer; + hideThinkingBlock; + markdownTheme; + hiddenThinkingLabel; + outputPad; + markdownTransformers; + lastMessage; + hasToolCalls = false; + isStreaming = false; + thinkingVisibilityOverrides = new Map(); + constructor(message, hideThinkingBlock = false, markdownTheme = getMarkdownTheme(), hiddenThinkingLabel = "Thinking...", outputPad = 1, markdownTransformers = []) { + super(); + this.hideThinkingBlock = hideThinkingBlock; + this.markdownTheme = markdownTheme; + this.hiddenThinkingLabel = hiddenThinkingLabel; + this.outputPad = outputPad; + this.markdownTransformers = markdownTransformers; + // Container for text/thinking content + this.contentContainer = new Container(); + this.addChild(this.contentContainer); + if (message) { + this.updateContent(message); + } + } + invalidate() { + super.invalidate(); + if (this.lastMessage) { + this.updateContent(this.lastMessage); + } + } + setHideThinkingBlock(hide) { + this.hideThinkingBlock = hide; + this.thinkingVisibilityOverrides.clear(); + if (this.lastMessage) { + this.updateContent(this.lastMessage); + } + } + setHiddenThinkingLabel(label) { + this.hiddenThinkingLabel = label; + if (this.lastMessage) { + this.updateContent(this.lastMessage); + } + } + setOutputPad(padding) { + this.outputPad = padding; + if (this.lastMessage) { + this.updateContent(this.lastMessage); + } + } + render(width) { + const lines = super.render(width); + if (this.hasToolCalls || lines.length === 0) { + return lines; + } + lines[0] = OSC133_ZONE_START + lines[0]; + lines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1]; + return lines; + } + updateContent(message, isStreaming = this.isStreaming) { + this.lastMessage = message; + this.isStreaming = isStreaming; + // Clear content container + this.contentContainer.clear(); + const hasVisibleContent = message.content.some((c) => (c.type === "text" && c.text.trim()) || (c.type === "thinking" && c.thinking.trim())); + if (hasVisibleContent) { + this.contentContainer.addChild(new Spacer(1)); + } + // Render content in order + let thinkingRunIndex = 0; + for (let i = 0; i < message.content.length; i++) { + const content = message.content[i]; + if (content.type === "text" && content.text.trim()) { + // Assistant text messages with no background - trim the text + // Set paddingY=0 to avoid extra spacing before tool executions + this.contentContainer.addChild(new Markdown(content.text.trim(), this.outputPad, 0, this.markdownTheme, undefined, { + transform: createMarkdownTransform("assistant", this.isStreaming, this.markdownTransformers), + })); + } + else if (content.type === "thinking") { + const thinkingBlocks = []; + for (; i < message.content.length; i++) { + const thinkingContent = message.content[i]; + if (thinkingContent.type !== "thinking") { + break; + } + const thinking = thinkingContent.thinking.trim(); + if (thinking) { + thinkingBlocks.push(thinking); + } + } + i--; + if (thinkingBlocks.length === 0) { + continue; + } + // Add spacing only when another visible assistant content block follows. + // This avoids a superfluous blank line before separately-rendered tool execution blocks. + const hasVisibleContentAfter = message.content + .slice(i + 1) + .some((c) => (c.type === "text" && c.text.trim()) || (c.type === "thinking" && c.thinking.trim())); + const runIndex = thinkingRunIndex++; + const hidden = this.thinkingVisibilityOverrides.get(runIndex) ?? this.hideThinkingBlock; + const thinkingComponent = hidden + ? new Text(theme.italic(theme.fg("thinkingText", this.hiddenThinkingLabel)), this.outputPad, 0) + : new Markdown(thinkingBlocks.join("\n\n"), this.outputPad, 0, this.markdownTheme, { + color: (text) => theme.fg("thinkingText", text), + italic: true, + }, { + transform: createMarkdownTransform("assistant-thinking", this.isStreaming, this.markdownTransformers), + }); + this.contentContainer.addChild(new MouseRegion(thinkingComponent, (event) => { + if (event.type !== "click" || event.button !== "left") + return undefined; + this.thinkingVisibilityOverrides.set(runIndex, !hidden); + if (this.lastMessage) + this.updateContent(this.lastMessage); + return { handled: true }; + })); + if (hasVisibleContentAfter) { + this.contentContainer.addChild(new Spacer(1)); + } + } + } + // Check if incomplete/failed - show after partial content. + // For aborted/error tool calls, tool execution components show the error. + // Length stops can happen before a tool call is complete, so surface them here too. + const hasToolCalls = message.content.some((c) => c.type === "toolCall"); + this.hasToolCalls = hasToolCalls; + if (message.stopReason === "length") { + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("error", "Response was truncated before completion."), this.outputPad, 0)); + } + else if (!hasToolCalls) { + if (message.stopReason === "aborted") { + const abortMessage = message.errorMessage && message.errorMessage !== "Request was aborted" + ? message.errorMessage + : "Operation aborted"; + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("error", abortMessage), this.outputPad, 0)); + } + else if (message.stopReason === "error") { + const errorMsg = message.errorMessage || "Unknown error"; + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("error", `Error: ${errorMsg}`), this.outputPad, 0)); + } + } + } +} +//# sourceMappingURL=assistant-message.js.map \ No newline at end of file diff --git a/app/vendor/pi-coding-agent/components/custom-editor.js b/app/vendor/pi-coding-agent/components/custom-editor.js new file mode 100644 index 0000000000000000000000000000000000000000..8af62ee66e21fcfd0549026c7b80446a81da694c --- /dev/null +++ b/app/vendor/pi-coding-agent/components/custom-editor.js @@ -0,0 +1,115 @@ +import { Editor, visibleWidth } from "@earendil-works/pi-tui"; +/** + * Custom editor that handles app-level keybindings for coding-agent. + */ +export class CustomEditor extends Editor { + keybindings; + workingStatusIndicator; + embedWorkingStatus; + actionHandlers = new Map(); + // Special handlers that can be dynamically replaced + onEscape; + onCtrlD; + onPasteImage; + /** Handler for extension-registered shortcuts. Returns true if handled. */ + onExtensionShortcut; + constructor(tui, theme, keybindings, options) { + super(tui, theme, options); + this.keybindings = keybindings; + this.embedWorkingStatus = options?.embedWorkingStatus ?? false; + } + setWorkingStatusIndicator(indicator) { + this.workingStatusIndicator = indicator; + } + renderTopBorder(width, hiddenLineCount) { + if (!this.embedWorkingStatus || !this.workingStatusIndicator || width <= 0) { + return super.renderTopBorder(width, hiddenLineCount); + } + let status = this.workingStatusIndicator.renderInBorder(Math.max(1, width - 5)); + let statusWidth = visibleWidth(status); + if (statusWidth === 0) + return super.renderTopBorder(width, hiddenLineCount); + const overflowLabel = hiddenLineCount > 0 ? ` ↑ ${hiddenLineCount} more ` : undefined; + const overflowLabelWidth = overflowLabel ? visibleWidth(overflowLabel) : 0; + const overflowStart = Math.floor((width - overflowLabelWidth) / 2); + const canFitOverflow = () => overflowLabel !== undefined && overflowLabelWidth + 2 <= width && overflowStart - (3 + statusWidth + 1) >= 1; + if (overflowLabel && !canFitOverflow()) { + status = this.workingStatusIndicator.renderSpinnerInBorder(width); + statusWidth = visibleWidth(status); + } + if (canFitOverflow()) { + const leftBlockWidth = 3 + statusWidth + 1; + return (this.borderColor("── ") + + status + + this.borderColor(` ${"─".repeat(overflowStart - leftBlockWidth)}${overflowLabel}${"─".repeat(width - overflowStart - overflowLabelWidth)}`)); + } + if (width >= statusWidth + 5) { + return this.borderColor("── ") + status + this.borderColor(` ${"─".repeat(width - statusWidth - 4)}`); + } + status = this.workingStatusIndicator.renderSpinnerInBorder(width); + statusWidth = visibleWidth(status); + const prefixWidth = Math.min(3, Math.max(0, width - statusWidth)); + return (this.borderColor("─".repeat(prefixWidth)) + + status + + this.borderColor("─".repeat(Math.max(0, width - prefixWidth - statusWidth)))); + } + /** + * Register a handler for an app action. + */ + onAction(action, handler) { + this.actionHandlers.set(action, handler); + } + handleInput(data) { + // Check extension-registered shortcuts first + if (this.onExtensionShortcut?.(data)) { + return; + } + // Check for clipboard paste keybinding + if (this.keybindings.matches(data, "app.clipboard.pasteImage")) { + this.onPasteImage?.(); + return; + } + // Check app keybindings first + // Escape/interrupt - only if autocomplete is NOT active + if (this.keybindings.matches(data, "app.interrupt")) { + if (!this.isShowingAutocomplete()) { + // Use dynamic onEscape if set, otherwise registered handler + const handler = this.onEscape ?? this.actionHandlers.get("app.interrupt"); + if (handler) { + handler(); + return; + } + } + // Let parent handle escape for autocomplete cancellation + super.handleInput(data); + return; + } + // Exit (Ctrl+D) - only when editor is empty + if (this.keybindings.matches(data, "app.exit")) { + if (this.getText().length === 0) { + const handler = this.onCtrlD ?? this.actionHandlers.get("app.exit"); + if (handler) + handler(); + return; + } + // Fall through to editor handling for delete-char-forward when not empty + } + // Explicit history bindings take precedence over app actions while the editor is focused. + // This lets users bind Ctrl+P even though it cycles models by default. + if (this.keybindings.matches(data, "tui.editor.historyPrevious") || + this.keybindings.matches(data, "tui.editor.historyNext")) { + super.handleInput(data); + return; + } + // Check all other app actions + for (const [action, handler] of this.actionHandlers) { + if (action !== "app.interrupt" && action !== "app.exit" && this.keybindings.matches(data, action)) { + handler(); + return; + } + } + // Pass to parent for editor handling + super.handleInput(data); + } +} +//# sourceMappingURL=custom-editor.js.map \ No newline at end of file diff --git a/app/vendor/pi-coding-agent/components/markdown-transform.js b/app/vendor/pi-coding-agent/components/markdown-transform.js new file mode 100644 index 0000000000000000000000000000000000000000..5ac4c5670ab3bf0365535c3d078016a58babee49 --- /dev/null +++ b/app/vendor/pi-coding-agent/components/markdown-transform.js @@ -0,0 +1,19 @@ +export function createMarkdownTransform(messageType, isStreaming, transformers) { + return (markdown, availableWidth) => applyMarkdownTransformers(markdown, { messageType, isStreaming, availableWidth }, transformers); +} +function applyMarkdownTransformers(markdown, context, transformers) { + let transformedMarkdown = markdown; + for (const transformer of transformers) { + try { + const transformed = transformer(transformedMarkdown, context); + if (typeof transformed === "string") { + transformedMarkdown = transformed; + } + } + catch { + // Keep the current Markdown and continue with the next transformer. + } + } + return transformedMarkdown; +} +//# sourceMappingURL=markdown-transform.js.map \ No newline at end of file diff --git a/app/vendor/pi-coding-agent/components/user-message.js b/app/vendor/pi-coding-agent/components/user-message.js new file mode 100644 index 0000000000000000000000000000000000000000..2e0490362d3396995b587f502ff3e69a7cad9a43 --- /dev/null +++ b/app/vendor/pi-coding-agent/components/user-message.js @@ -0,0 +1,49 @@ +import { Box, Container, Markdown } from "@earendil-works/pi-tui"; +import { getMarkdownTheme, theme } from "../theme/theme.js"; +import { createMarkdownTransform } from "./markdown-transform.js"; +const OSC133_ZONE_START = "\x1b]133;A\x07"; +const OSC133_ZONE_END = "\x1b]133;B\x07"; +const OSC133_ZONE_FINAL = "\x1b]133;C\x07"; +/** + * Component that renders a user message + */ +export class UserMessageComponent extends Container { + text; + markdownTheme; + outputPad; + markdownTransformers; + constructor(text, markdownTheme = getMarkdownTheme(), outputPad = 1, markdownTransformers = []) { + super(); + this.text = text; + this.markdownTheme = markdownTheme; + this.outputPad = outputPad; + this.markdownTransformers = markdownTransformers; + this.rebuild(); + } + setOutputPad(padding) { + this.outputPad = padding; + this.rebuild(); + } + rebuild() { + this.clear(); + const contentBox = new Box(this.outputPad, 1, (content) => theme.bg("userMessageBg", content)); + contentBox.addChild(new Markdown(this.text, 0, 0, this.markdownTheme, { + color: (content) => theme.fg("userMessageText", content), + }, { + preserveOrderedListMarkers: true, + preserveBackslashEscapes: true, + transform: createMarkdownTransform("user", false, this.markdownTransformers), + })); + this.addChild(contentBox); + } + render(width) { + const lines = super.render(width); + if (lines.length === 0) { + return lines; + } + lines[0] = OSC133_ZONE_START + lines[0]; + lines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1]; + return lines; + } +} +//# sourceMappingURL=user-message.js.map \ No newline at end of file diff --git a/app/vendor/pi-coding-agent/provenance.json b/app/vendor/pi-coding-agent/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..948e826e592061fea3f64000e2ab08ef4490c7e5 --- /dev/null +++ b/app/vendor/pi-coding-agent/provenance.json @@ -0,0 +1,13 @@ +{ + "package": "@earendil-works/pi-coding-agent", + "version": "0.85.1", + "source": "https://github.com/earendil-works/pi/tree/v0.85.1/packages/coding-agent", + "files": { + "components/custom-editor.js": "000b0056f2bf645537537468bdd6f6ee0c82e4110f5417c1c70c2e8fefc04f29", + "components/user-message.js": "398a34b8a979daea5614be4cbbe6ff66e7eca97e9fd855508791dcddce994bc8", + "components/assistant-message.js": "edbd1e712234609d2ad1078edcf960e3b6f549669075f1c5d1a7a4481e2b3d19", + "components/markdown-transform.js": "31ad2245189328104a31bb9b12f58b0a12e4af9c7924775a242c9dcd526d2c1a", + "theme/light.json": "14c7172ba7e75eab6f509504de806af0f2d9ff817bfb45d9533bff15c7e6e657", + "theme/dark.json": "103a5aecb74a2dab5cc903c9741845ee6158658ce2ff6e5445948784116eaef8" + } +} diff --git a/app/vendor/pi-coding-agent/theme/dark.json b/app/vendor/pi-coding-agent/theme/dark.json new file mode 100644 index 0000000000000000000000000000000000000000..3f4c698a71dc3dde81df7dff9b0b4a026f6e9a51 --- /dev/null +++ b/app/vendor/pi-coding-agent/theme/dark.json @@ -0,0 +1,91 @@ +{ + "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "name": "dark", + "vars": { + "cyan": "#00d7ff", + "blue": "#5f87ff", + "green": "#b5bd68", + "red": "#cc6666", + "yellow": "#ffff00", + "text": "#d4d4d4", + "gray": "#808080", + "dimGray": "#666666", + "darkGray": "#505050", + "accent": "#8abeb7", + "selectedBg": "#3a3a4a", + "userMsgBg": "#343541", + "toolPendingBg": "#282832", + "toolSuccessBg": "#283228", + "toolErrorBg": "#3c2828", + "customMsgBg": "#2d2838" + }, + "colors": { + "accent": "accent", + "border": "blue", + "borderAccent": "cyan", + "borderMuted": "darkGray", + "success": "green", + "error": "red", + "warning": "yellow", + "muted": "gray", + "dim": "dimGray", + "text": "text", + "thinkingText": "gray", + + "selectedBg": "selectedBg", + "scrollbarTrack": "darkGray", + "scrollbarThumb": "text", + "searchMatchBg": "selectedBg", + "searchMatchText": "text", + "userMessageBg": "userMsgBg", + "userMessageText": "text", + "customMessageBg": "customMsgBg", + "customMessageText": "text", + "customMessageLabel": "#9575cd", + "toolPendingBg": "toolPendingBg", + "toolSuccessBg": "toolSuccessBg", + "toolErrorBg": "toolErrorBg", + "toolTitle": "text", + "toolOutput": "gray", + + "mdHeading": "#f0c674", + "mdLink": "#81a2be", + "mdLinkUrl": "dimGray", + "mdCode": "accent", + "mdCodeBlock": "green", + "mdCodeBlockBorder": "gray", + "mdQuote": "gray", + "mdQuoteBorder": "gray", + "mdHr": "gray", + "mdListBullet": "accent", + + "toolDiffAdded": "green", + "toolDiffRemoved": "red", + "toolDiffContext": "gray", + + "syntaxComment": "#6A9955", + "syntaxKeyword": "#569CD6", + "syntaxFunction": "#DCDCAA", + "syntaxVariable": "#9CDCFE", + "syntaxString": "#CE9178", + "syntaxNumber": "#B5CEA8", + "syntaxType": "#4EC9B0", + "syntaxOperator": "#D4D4D4", + "syntaxPunctuation": "#D4D4D4", + + "thinkingOff": "darkGray", + "thinkingMinimal": "#6e6e6e", + "thinkingLow": "#5f87af", + "thinkingMedium": "#81a2be", + "thinkingHigh": "#b294bb", + "thinkingXhigh": "#d183e8", + "thinkingMax": "#ff5fff", + + "bashMode": "green" + }, + "export": { + "pageBg": "#18181e", + "cardBg": "#1e1e24", + "infoBg": "#3c3728" + } +} diff --git a/app/vendor/pi-coding-agent/theme/light.json b/app/vendor/pi-coding-agent/theme/light.json new file mode 100644 index 0000000000000000000000000000000000000000..20f67835a911af7c33feaab76f8da0657919e085 --- /dev/null +++ b/app/vendor/pi-coding-agent/theme/light.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "name": "light", + "vars": { + "teal": "#5a8080", + "blue": "#547da7", + "green": "#588458", + "red": "#aa5555", + "yellow": "#9a7326", + "text": "#1f2328", + "mediumGray": "#6c6c6c", + "dimGray": "#767676", + "lightGray": "#b0b0b0", + "selectedBg": "#d0d0e0", + "userMsgBg": "#e8e8e8", + "toolPendingBg": "#e8e8f0", + "toolSuccessBg": "#e8f0e8", + "toolErrorBg": "#f0e8e8", + "customMsgBg": "#ede7f6" + }, + "colors": { + "accent": "teal", + "border": "blue", + "borderAccent": "teal", + "borderMuted": "lightGray", + "success": "green", + "error": "red", + "warning": "yellow", + "muted": "mediumGray", + "dim": "dimGray", + "text": "text", + "thinkingText": "mediumGray", + + "selectedBg": "selectedBg", + "scrollbarTrack": "lightGray", + "scrollbarThumb": "text", + "searchMatchBg": "selectedBg", + "searchMatchText": "text", + "userMessageBg": "userMsgBg", + "userMessageText": "text", + "customMessageBg": "customMsgBg", + "customMessageText": "text", + "customMessageLabel": "#7e57c2", + "toolPendingBg": "toolPendingBg", + "toolSuccessBg": "toolSuccessBg", + "toolErrorBg": "toolErrorBg", + "toolTitle": "text", + "toolOutput": "mediumGray", + + "mdHeading": "yellow", + "mdLink": "blue", + "mdLinkUrl": "dimGray", + "mdCode": "teal", + "mdCodeBlock": "green", + "mdCodeBlockBorder": "mediumGray", + "mdQuote": "mediumGray", + "mdQuoteBorder": "mediumGray", + "mdHr": "mediumGray", + "mdListBullet": "green", + + "toolDiffAdded": "green", + "toolDiffRemoved": "red", + "toolDiffContext": "mediumGray", + + "syntaxComment": "#008000", + "syntaxKeyword": "#0000FF", + "syntaxFunction": "#795E26", + "syntaxVariable": "#001080", + "syntaxString": "#A31515", + "syntaxNumber": "#098658", + "syntaxType": "#267F99", + "syntaxOperator": "#000000", + "syntaxPunctuation": "#000000", + + "thinkingOff": "lightGray", + "thinkingMinimal": "#767676", + "thinkingLow": "blue", + "thinkingMedium": "teal", + "thinkingHigh": "#875f87", + "thinkingXhigh": "#8b008b", + "thinkingMax": "#af005f", + + "bashMode": "green" + }, + "export": { + "pageBg": "#f8f8f8", + "cardBg": "#ffffff", + "infoBg": "#fffae6" + } +} diff --git a/app/vite.config.mjs b/app/vite.config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4fba7e815a6f32189b645ddd3b70ecfe2b29df62 --- /dev/null +++ b/app/vite.config.mjs @@ -0,0 +1,36 @@ +import { defineConfig } from 'vite'; +import { cpSync, mkdirSync, readdirSync, createReadStream, statSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { collectLicenses } from './scripts/licenses.mjs'; +import { piBrowser } from './scripts/pi-browser.mjs'; + +export default defineConfig({ + base: './', + worker: { format: 'es' }, + optimizeDeps: { exclude: ['@earendil-works/pi-tui'], include: ['events', 'buffer'] }, + resolve: { alias: { '@huggingface/transformers': resolve('node_modules/@huggingface/transformers/dist/transformers.web.js') } }, + server: { proxy: { '/models': 'http://127.0.0.1:8765' } }, + preview: { proxy: { '/models': 'http://127.0.0.1:8765' } }, + plugins: [piBrowser(), { + name: 'local-ort-runtime', + configureServer(server) { + server.middlewares.use('/runtime', (req, res, next) => { + const name = req.url.split('?')[0]; + if (!/^\/ort-wasm-[\w.-]+\.(wasm|mjs)$/.test(name)) return next(); + const file = resolve('node_modules/onnxruntime-web/dist', name.slice(1)); + try { + res.setHeader('Content-Type', name.endsWith('.wasm') ? 'application/wasm' : 'text/javascript'); + res.setHeader('Content-Length', statSync(file).size); + createReadStream(file).pipe(res); + } catch { res.statusCode = 404; res.end(); } + }); + }, + async closeBundle() { + mkdirSync('dist/runtime', { recursive: true }); + for (const file of readdirSync('node_modules/onnxruntime-web/dist')) { + if (/^ort-wasm-.*\.(wasm|mjs)$/.test(file)) cpSync('node_modules/onnxruntime-web/dist/' + file, 'dist/runtime/' + file); + } + await collectLicenses(); + }, + }], +}); diff --git a/assets/agent.worker-DAy1yjYb.js b/assets/agent.worker-DAy1yjYb.js new file mode 100644 index 0000000000000000000000000000000000000000..c80488330521a55c327deddd6739a74296cd8e48 --- /dev/null +++ b/assets/agent.worker-DAy1yjYb.js @@ -0,0 +1,1803 @@ +var e=Object.defineProperty,t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},r=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});const i={assign:0,create:0,clone:0,discard:0,update:0};function a(e,t){return i.assign+=1,{...e,...t}}function o(e,t,n){return e>=t&&e<=n}function s(e){return e===8205}function c(e){return o(e,55296,56319)}function l(e){return o(e,127462,127487)}function u(e){return o(e,65024,65039)}function d(e){return o(e,768,879)||o(e,6832,6911)||o(e,7616,7679)||o(e,65056,65071)}function f(e){return e>65535?2:1}function p(e,t){for(;t=t)return!0;return!1}function v(e,t){let n=0,r=0;for(;rt)return!1;return!0}function y(e,t){if(t===0)return!0;let n=0;for(;n=t)return!0}return!1}function b(e,t){let n=0;for(;nt)return!1}return!0}var x=n({Entries:()=>_e,EntriesRegExp:()=>ge,Every:()=>fe,EveryAll:()=>pe,GraphemeCount:()=>le,HasPropertyKey:()=>P,IsArray:()=>S,IsBigInt:()=>C,IsBoolean:()=>w,IsClassInstance:()=>se,IsConstructor:()=>T,IsDeepEqual:()=>Se,IsEqual:()=>N,IsFunction:()=>E,IsGreaterEqualThan:()=>ae,IsGreaterThan:()=>ne,IsInteger:()=>D,IsLessEqualThan:()=>ie,IsLessThan:()=>re,IsMaxLength:()=>ue,IsMinLength:()=>de,IsMultipleOf:()=>oe,IsNull:()=>O,IsNumber:()=>k,IsObject:()=>j,IsObjectNotArray:()=>A,IsString:()=>M,IsSymbol:()=>ee,IsUndefined:()=>te,IsUnsafePropertyKey:()=>he,IsValueLike:()=>ce,Keys:()=>F,ShiftLeft:()=>me,Symbols:()=>ve,Values:()=>ye});function S(e){return Array.isArray(e)}function C(e){return N(typeof e,`bigint`)}function w(e){return N(typeof e,`boolean`)}function T(e){if(te(e)||!E(e))return!1;let t=Function.prototype.toString.call(e);return!!(/^class\s/.test(t)||/\[native code\]/.test(t))}function E(e){return N(typeof e,`function`)}function D(e){return Number.isInteger(e)}function O(e){return N(e,null)}function k(e){return Number.isFinite(e)}function A(e){return j(e)&&!S(e)}function j(e){return N(typeof e,`object`)&&!O(e)}function M(e){return N(typeof e,`string`)}function ee(e){return N(typeof e,`symbol`)}function te(e){return N(e,void 0)}function N(e,t){return e===t}function ne(e,t){return e>t}function re(e,t){return e=t}function oe(e,t){if(C(e)||C(t))return BigInt(e)%BigInt(t)===0n;if(!k(e)||D(e)&&1/t%1==0)return!0;let n=e%t;return Math.min(Math.abs(n),Math.abs(n-t),Math.abs(n+t))<1e-10}function se(e){if(!j(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return!O(t)&&N(typeof t.constructor,`function`)&&!(N(t.constructor,globalThis.Object)||N(t.constructor.name,`Object`))}function ce(e){return C(e)||w(e)||O(e)||k(e)||M(e)||te(e)}function le(e){return g(e)}function ue(e,t){return b(e,t)}function de(e,t){return y(e,t)}function fe(e,t,n){for(let r=t;r[RegExp(`^${t}$`),e[t]])}function _e(e){return Object.entries(e)}function F(e){return Object.getOwnPropertyNames(e)}function ve(e){return Object.getOwnPropertySymbols(e)}function ye(e){return Object.values(e)}function be(e,t){if(!j(t))return!1;let n=F(e);return N(n.length,F(t).length)&&n.every(n=>Se(e[n],t[n]))}function xe(e,t){return S(t)&&N(e.length,t.length)&&e.every((n,r)=>Se(e[r],t[r]))}function Se(e,t){return S(e)?xe(e,t):j(e)?be(e,t):N(e,t)}const Ce=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function we(e){return Ce.test(e)}function Te(e,t){return`(${e} && ${t})`}function Ee(e,t){return`(${e} || ${t})`}function De(e){return`!(${e})`}function Oe(e){return`Array.isArray(${e})`}function ke(e){return`typeof ${e} === "bigint"`}function Ae(e){return`typeof ${e} === "boolean"`}function je(e){return`Number.isInteger(${e})`}function Me(e){return`${e} === null`}function Ne(e){return`Number.isFinite(${e})`}function Pe(e){return Te(Fe(e),De(Oe(e)))}function Fe(e){return`typeof ${e} === "object" && ${e} !== null`}function Ie(e){return`typeof ${e} === "string"`}function Le(e){return`typeof ${e} === "symbol"`}function Re(e){return`${e} === undefined`}function ze(e){return`typeof ${e} === "function"`}function Be(e){return`Guard.IsConstructor(${e})`}function Ve(e,t){return`${e} === ${t}`}function He(e,t){return`${e} > ${t}`}function Ue(e,t){return`${e} < ${t}`}function We(e,t){return`${e} <= ${t}`}function Ge(e,t){return`${e} >= ${t}`}function Ke(e,t){return`Guard.IsMinLength(${e}, ${t})`}function qe(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Je(e,t,n,r){return N(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => ${r})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${n[0]}, ${n[1]}) => ${r})`}function Ye(e){return`Object.entries(${e})`}function Xe(e){return`Object.getOwnPropertyNames(${e})`}function Ze(e,t){return N(t,`"__proto__"`)||N(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function Qe(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function $e(e){return`[${e.join(`, `)}]`}function et(e,t){return`((${e.join(`, `)}) => ${t})`}function tt(e,t){return`${e}(${t.join(`, `)})`}function nt(e,t){return`new ${e}(${t.join(`, `)})`}function rt(e,t){return`${e}${we(t)?`.${t}`:`[${it(t)}]`}`}function it(e){return M(e)?JSON.stringify(e):`${e}`}function at(e,t,n){return`(${e} ? ${t} : ${n})`}function ot(e){return`{ ${e.join(`; `)}; }`}function st(e,t){return`const ${e} = ${t}`}function ct(e,t){return`if(${e}) { ${t} }`}function lt(e){return`return ${e}`}function ut(e){return N(e.length,0)?`true`:e.reduce((e,t)=>Te(e,t))}function dt(e){return N(e.length,0)?`false`:e.reduce((e,t)=>Ee(e,t))}function ft(e){return`++${e}`}function pt(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}function mt(e){return e instanceof Boolean}function ht(e){return e instanceof Number}function gt(e){return e instanceof String}function _t(e){return globalThis.ArrayBuffer.isView(e)}function vt(e){return e instanceof globalThis.RegExp}function yt(e){return e instanceof globalThis.Date}function bt(e){return e instanceof globalThis.Set}function xt(e){return e instanceof globalThis.Map}var St=x;function Ct(e){return e}function wt(e){return P(e,`~kind`)||P(e,`~unsafe`)}function Tt(e){let t={},n=Object.getOwnPropertyDescriptors(e);for(let e of Object.keys(n)){if(he(e))continue;let r=n[e];P(r,`value`)&&Object.defineProperty(t,e,{...r,value:Nt(r.value)})}return t}function Et(e){let t={};for(let n of F(e))he(n)||(t[n]=Nt(e[n]));for(let n of ve(e))t[n]=Nt(e[n]);return t}function Dt(e){return se(e)?Ct(e):wt(e)?Tt(e):Et(e)}function Ot(e){return e.map(e=>Nt(e))}function kt(e){return e.slice()}function At(e){return new RegExp(e.source,e.flags)}function jt(e){return new Map(Nt([...e.entries()]))}function Mt(e){return new Set(Nt([...e.values()]))}function Nt(e){return _t(e)?kt(e):vt(e)?At(e):xt(e)?jt(e):bt(e)?Mt(e):S(e)?Ot(e):j(e)?Dt(e):e}function Pt(e){return i.clone+=1,Nt(e)}const Ft={immutableTypes:!1,maxErrors:8,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function It(){return Ft}function Lt(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function Rt(e,t){return{...e,...t}}function zt(e,t,n={}){i.create+=1;let r=It(),a=Rt(t,n),o=r.enumerableKind?Rt(a,e):Lt(a,e);return r.immutableTypes?Object.freeze(o):o}function Bt(e,t){i.discard+=1;let n={},r=Object.getOwnPropertyDescriptors(Pt(e)),a=new Set(t);for(let e of Object.keys(r))a.has(e)||Object.defineProperty(n,e,r[e]);return n}function Vt(e,t,n){i.update+=1;let r=It(),a=Pt(e);for(let e of Object.keys(t))Object.defineProperty(a,e,{configurable:!0,writable:!0,enumerable:r.enumerableKind,value:t[e]});for(let e of Object.keys(n))Object.defineProperty(a,e,{configurable:!0,enumerable:!0,writable:!0,value:n[e]});return a}function Ht(e,t){return j(e)&&P(e,`~kind`)&&N(e[`~kind`],t)}function Ut(e){return j(e)}function Wt(e,t,n){return zt({"~kind":`Deferred`},{type:`deferred`,action:e,parameters:t,options:n},{})}function Gt(e){return Ht(e,`Deferred`)}function Kt(e){return Vt(e,{"~readonly":!0},{})}function qt(e,t){return Vt(Kt(e),{},t)}function Jt(e,t,n,r){return qt(sl(e,t,n),r)}function Yt(e){return Vt(e,{"~optional":!0},{})}function Xt(e,t){return Vt(Yt(e),{},t)}function Zt(e,t,n,r){return Xt(sl(e,t,n),r)}function Qt(e,t){return zt({"~kind":`Array`},{type:`array`,items:e},t)}function $t(e){return Ht(e,`Array`)}function en(e){return Bt(e,[`~kind`,`type`,`items`])}function tn(e,t,n={}){return zt({"~kind":`Constructor`},{type:`constructor`,parameters:e,instanceType:t},n)}function nn(e){return Ht(e,`Constructor`)}function rn(e){return Bt(e,[`~kind`,`type`,`parameters`,`instanceType`])}function an(e,t,n={}){return zt({"~kind":`Function`},{type:`function`,parameters:e,returnType:t},n)}function on(e){return Ht(e,`Function`)}function sn(e){return Bt(e,[`~kind`,`type`,`parameters`,`returnType`])}function cn(e,t){return zt({"~kind":`Ref`},{$ref:e},t)}function ln(e){return Ht(e,`Ref`)}function un(e,t){return zt({"~kind":`Generic`},{type:`generic`,parameters:e,expression:t})}function dn(e){return Ht(e,`Generic`)}function fn(e){return zt({"~kind":`Any`},{},e)}function pn(e){return Ht(e,`Any`)}function mn(e){return zt({"~kind":`Never`},{not:{}},e)}function hn(e){return Ht(e,`Never`)}function gn(e,t={}){return Xt(e,t)}function _n(e){return gn(e)}function vn(e){return Ut(e)&&P(e,`~optional`)}function yn(e){return F(e).filter(t=>!vn(e[t]))}function bn(e){return F(e)}function xn(e){return ye(e)}function Sn(e,t={}){let n=yn(e);return zt({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}function Cn(e){return Ht(e,`Object`)}function wn(e){return Bt(e,[`~kind`,`type`,`properties`,`required`])}function Tn(e){return zt({"~kind":`Unknown`},{},e)}function En(e){return Ht(e,`Unknown`)}function Dn(e,t,n){return zt({"~kind":`Cyclic`},{$defs:F(e).reduce((t,n)=>({...t,[n]:Vt(e[n],{},{$id:n})}),{}),$ref:t},n)}function On(e){return Ht(e,`Cyclic`)}function kn(e){return A(e)&&P(e,`~unsafe`)&&O(e[`~unsafe`])}function An(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}function jn(e){return Ht(e,`Infer`)}function Mn(e,t,n,r={}){return zt({"~kind":`Dependent`},{if:e,then:t,else:n},r)}function Nn(e){return Ht(e,`Dependent`)}function Pn(e){return Bt(e,[`~kind`,`if`,`then`,`else`])}function Fn(e){return Ht(e,`Enum`)}function In(e,t={}){return zt({"~kind":`Intersect`},{allOf:e},t)}function Ln(e){return Ht(e,`Intersect`)}function Rn(e){return Bt(e,[`~kind`,`allOf`])}let zn;function Bn(){try{return Hn(`null`)(),!0}catch{return!1}}function Vn(){return te(zn)&&(zn=Bn()),zn&&It().useAcceleration}function Hn(...e){return new globalThis.Function(...e)}function Un(){throw Error(`Unreachable`)}var Wn=n({Hash:()=>yr,HashCode:()=>vr});function Gn(e){let t=new Set,n=e;for(;n&&n!==Object.prototype;){for(let e of Reflect.ownKeys(n))e!==`constructor`&&typeof e!=`symbol`&&t.add(e);n=Object.getPrototypeOf(n)}return[...t]}function Kn(e){return typeof e==`number`}var qn;(function(e){e[e.Array=0]=`Array`,e[e.BigInt=1]=`BigInt`,e[e.Boolean=2]=`Boolean`,e[e.Date=3]=`Date`,e[e.Constructor=4]=`Constructor`,e[e.Function=5]=`Function`,e[e.Null=6]=`Null`,e[e.Number=7]=`Number`,e[e.Object=8]=`Object`,e[e.RegExp=9]=`RegExp`,e[e.String=10]=`String`,e[e.Symbol=11]=`Symbol`,e[e.TypeArray=12]=`TypeArray`,e[e.Undefined=13]=`Undefined`})(qn||={});let Jn=BigInt(`14695981039346656037`);const[Yn,Xn]=[BigInt(`1099511628211`),BigInt(`18446744073709551616`)],Zn=Array.from({length:256}).map((e,t)=>BigInt(t)),Qn=new Float64Array(1),$n=new DataView(Qn.buffer),er=new Uint8Array(Qn.buffer);function tr(e){Jn^=Zn[e],Jn=Jn*Yn%Xn}function nr(e){tr(qn.Array);for(let t of e)_r(t)}function rr(e){tr(qn.BigInt),$n.setBigInt64(0,e);for(let e of er)tr(e)}function ir(e){tr(qn.Boolean),tr(+!!e)}function ar(e){tr(qn.Constructor),_r(e.toString())}function or(e){tr(qn.Date),_r(e.getTime())}function sr(e){tr(qn.Function),_r(e.toString())}function cr(e){tr(qn.Null)}function lr(e){tr(qn.Number),$n.setFloat64(0,e,!0);for(let e of er)tr(e)}function ur(e){tr(qn.Object);for(let t of Gn(e).sort())_r(t),_r(e[t])}function dr(e){tr(qn.RegExp),pr(e.toString())}const fr=new TextEncoder;function pr(e){tr(qn.String);for(let t of fr.encode(e))tr(t)}function mr(e){tr(qn.Symbol),_r(e.toString())}function hr(e){tr(qn.TypeArray);let t=new Uint8Array(e.buffer);for(let e=0;e{throw new Nr(e)})()}function Fr(e,t){return zt({"~kind":`Literal`},{type:Pr(e),const:e},t)}function Ir(e){return C(e)||w(e)||k(e)||M(e)}function Lr(e){return Vr(e)&&C(e.const)}function Rr(e){return Vr(e)&&w(e.const)}function zr(e){return Vr(e)&&k(e.const)}function Br(e){return Vr(e)&&M(e.const)}function Vr(e){return Ht(e,`Literal`)}function Hr(e){return zt({"~kind":`Null`},{type:`null`},e)}function Ur(e){return Ht(e,`Null`)}const Wr=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function Gr(e){return zt({"~kind":`Number`},{type:`number`},e)}function Kr(e){return Ht(e,`Number`)}function qr(e){return zt({"~kind":`Symbol`},{type:`symbol`},e)}function Jr(e){return Ht(e,`Symbol`)}function Yr(e){return zt({"~kind":`String`},{type:`string`},e)}function Xr(e){return Ht(e,`String`)}function Zr(e,t={}){return zt({"~kind":`Union`},{anyOf:e},t)}function Qr(e){return Ht(e,`Union`)}function $r(e){return Bt(e,[`~kind`,`anyOf`])}function ei(e){let t=Eo(e);return N(t.length,2)?t[0]:[]}function ti(e){return!0}function ni(e){return me(e,(e,t)=>ii(e)?ni(t):!1,()=>!0)}function ri(e){return!N(e.length,0)&&ni(e)}function ii(e){return Qr(e)?ri(e.anyOf):Vr(e)?ti(e.const):!1}function ai(e){return ri(e)}function oi(e){return zt({"~kind":`TemplateLiteral`},{type:`string`,pattern:e},{})}function si(e,t,n=[]){return me(e,(e,r)=>si(r,t,[...n,`${e}${t}`]),()=>n)}function ci(e,t){return N(e.length,0)?[`${t}`]:si(e,t)}function li(e,t,n=[]){return me(t,(t,r)=>li(e,r,[...n,...ui(e,t)]),()=>n)}function ui(e,t){return Qr(t)?li(e,t.anyOf):Vr(t)?ci(e,t.const):Un()}function di(e,t){return me(t,(t,n)=>di(ui(e,t),n),()=>e)}function fi(e){return e.map(e=>Fr(e))}function pi(e){return Zr(fi(di([],e)))}function mi(e){return N(e.length,0)?Un():N(e.length,1)&&Vr(e[0])?e[0]:pi(e)}function hi(e){let t=ei(e);return N(t.length,0)?Yr():ai(t)?mi(t):oi(e)}function gi(e){let t=hi(e);return Ho(t)?Yr():t}function _i(e,t){return zt({"~kind":`Record`},{type:`object`,patternProperties:{[e]:t}})}function vi(e){return _i(Sa,e)}function yi(e){return Sn({true:e,false:e})}function bi(e,t={}){let[n,r,i]=[e,e.length,!1];return zt({"~kind":`Tuple`},{type:`array`,additionalItems:i,items:n,minItems:r},t)}function xi(e){return Ht(e,`Tuple`)}function Si(e){return Bt(e,[`~kind`,`type`,`items`,`minItems`,`additionalItems`])}function Ci(e){return Bt(e,[`~readonly`])}function wi(e,t){return Vt(Ci(e),{},t)}function Ti(e,t,n,r){return wi(sl(e,t,n),r)}function Ei(e,t={}){return wi(e,t)}function Di(e){return Bt(e,[`~optional`])}function Oi(e,t){return Vt(Di(e),{},t)}function ki(e,t,n,r){return Oi(sl(e,t,n),r)}function Ai(e,t={}){return Oi(e,t)}function ji(e){return e.reduceRight((e,t,n)=>({[n]:t,...e}),{})}function Mi(e){return Sn(ji(e.items))}function Ni(e,t){return Er(e)?!!Er(t):!1}function Pi(e,t){return vn(e)?!!vn(t):!1}function Fi(e,t){let n=Ni(e,t),r=Pi(e,t),i=Ei(Ai(Qi([e,t])));return n&&r?Tr(gn(i)):n&&!r?Tr(i):!n&&r?gn(i):i}function Ii(e,t,n){return n in e?n in t?Fi(e[n],t[n]):e[n]:n in t?t[n]:mn()}function Li(e,t){return[...new Set([...F(t),...F(e)])].reduce((n,r)=>({...n,[r]:Ii(e,t,r)}),{})}function Ri(e){return Cn(e)?e.properties:xi(e)?ji(e.items):Un()}function zi(e,t){return Sn(Li(Ri(e),Ri(t)))}function Bi(e,t){let n=qs(e,t);return N(n,`left-inside`)?e:N(n,`right-inside`)||N(n,`equal`)?t:mn()}function Vi(e){return Cn(e)||xi(e)}function Hi(e,t){let n=Qr(e),r=Qr(t);return n||r}function Ui(e,t){let n=ta(e),r=ta(t),i=Hi(n,r),a=Vi(n),o=Vi(r);return i?Qi([n,r]):a&&o?zi(n,r):a&&!o?n:!a&&o?r:Bi(n,r)}function Wi(e,t,n=[]){return me(t,(t,r)=>Wi(e,r,[...n,Ui(e,t)]),()=>N(n.length,0)?[e]:n)}function Gi(e,t,n=[]){return me(e,(e,r)=>Gi(r,t,[...n,...Ki([e],t)]),()=>n)}function Ki(e,t=[]){return me(e,(e,n)=>Qr(e)?Ki(n,Gi(e.anyOf,t)):Ki(n,Wi(e,t)),()=>t)}function qi(e,t){return Jo(Ks({},e,t))?[]:[e]}function Ji(e,t){return e.reduce((e,n)=>[...e,...qi(n,t)],[])}function Yi(e,t){let n=ta(e);return ea(Ji(Qr(n)?n.anyOf:[n],t))}function Xi(e,t,n){return ea([In([e,t]),Yi(n,e)])}function Zi(e){return ea(e.map(e=>Fr(e)))}function Qi(e){return na(Js(Ki(e)))}function $i(e){return ta(gi(e))}function ea(e){return na(Js(e))}function ta(e){return Nn(e)?Xi(e.if,e.then,e.else):Fn(e)?Zi(e.enum):Ln(e)?Qi(e.allOf):Ho(e)?$i(e.pattern):Qr(e)?ea(e.anyOf):e}function na(e){return N(e.length,1)?e[0]:N(e.length,0)?mn():Zr(e)}function ra(e,t){return _a(Zi(e),t)}function ia(e,t){return _i(ba,t)}function aa(e,t){return _a(Qi(e),t)}function oa(e,t){return M(e)||k(e)?Sn({[e]:t}):N(e,!1)?Sn({false:t}):N(e,!0)?Sn({true:t}):Sn({})}function sa(e,t){return _i(xa,t)}function ca(e,t){return P(e,`pattern`)&&(M(e.pattern)||e.pattern instanceof RegExp)?_i(e.pattern.toString(),t):_i(Sa,t)}function la(e,t){return ai(ei(e))?_a($i(e),t):_i(e,t)}function ua(e){return Qr(e)?da(e.anyOf):[e]}function da(e){return e.reduce((e,t)=>[...e,...ua(t)],[])}function fa(e){return e.some(e=>Xr(e)||Kr(e)||Mr(e))}function pa(e,t){return N(fa(e),!0)?_i(Sa,t):void 0}function ma(e,t){return e.reduce((e,n)=>Vr(n)&&(M(n.const)||k(n.const))?{...e,[n.const]:t}:e,{})}function ha(e,t){return Sn(ma(e,t))}function ga(e,t){let n=da(e),r=pa(n,t);return Ut(r)?r:ha(n,t)}function _a(e,t){return pn(e)?vi(t):kr(e)?yi(t):Fn(e)?ra(e.enum,t):Mr(e)?ia(e,t):Ln(e)?aa(e.allOf,t):Vr(e)?oa(e.const,t):Kr(e)?sa(e,t):Qr(e)?ga(e.anyOf,t):Xr(e)?ca(e,t):Ho(e)?la(e.pattern,t):Sn({})}function va(e,t,n){return el([e])?Vt(_a(e,t),{},n):Ca(e,t,n)}function ya(e,t,n,r,i){return va(sl(e,t,n),sl(e,t,r),i)}const ba=`^${Ar}$`,xa=`^${Wr}$`,Sa=`^.*$`;function Ca(e,t,n={}){return Wt(`Record`,[e,t],n)}function wa(e,t,n={}){return va(e,t,n)}function Ta(e,t){return _i(e,t)}function Ea(e){return N(e,Sa)?Yr():N(e,ba)?jr():N(e,xa)?Gr():hi(e)}function Da(e){return F(e.patternProperties)[0]}function Oa(e){return Ea(Da(e))}function ka(e){return e.patternProperties[Da(e)]}function Aa(e){return Ht(e,`Record`)}function ja(e){return zt({"~kind":`Rest`},{type:`rest`,items:e},{})}function Ma(e){return Ht(e,`Rest`)}function Na(e){return Ht(e,`This`)}function Pa(e){return zt({"~kind":`Undefined`},{type:`undefined`},e)}function Fa(e){return Ht(e,`Undefined`)}function Ia(e){return Ht(e,`Void`)}function La(e){return Dr()}function Ra(e){return Yr()}function za(e){return Gr()}function Ba(e){return jr()}function Va(e){return mn()}function Ha(e){return Fr(e)}function Ua(e){return e}function Wa(e){return Zr(e[1])}function Ga(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function Ka(e){return[e[0],...e[1]]}function qa(e){return e}function Ja(e){return e[1]}function Ya(e){return N(e.length,2)}function Xa(e,t,n){return Ya(e)?t(e[0],e[1]):n()}function Za(e,t){return N(t.indexOf(e),0)?[e,t.slice(e.length)]:[]}function Qa(e,t){for(let n=0;nString.fromCharCode(e+n))}const eo=[...$a(97,122),...$a(65,90)],to=[`0`,...$a(49,57)];function no(e){let t=e.indexOf(`*/`);return N(t,-1)?``:e.slice(t+2)}function ro(e){let t=e.indexOf(` +`);return N(t,-1)?``:e.slice(t)}function io(e){return e.replace(/^[ \t\r\f\v]+/,``)}function ao(e){let t=io(e);return t.startsWith(`/*`)?ao(no(t.slice(2))):t.startsWith(`//`)?ao(ro(t.slice(2))):t}function oo(e){let t=e.trimStart();return t.startsWith(`/*`)?oo(no(t.slice(2))):t.startsWith(`//`)?oo(ro(t.slice(2))):t}[...to];function so(e,t){return Qa([e],t)}function co(e,t){return N(e,``)?[``,t]:e.startsWith(` +`)?so(e,ao(t)):e.startsWith(` `)?so(e,t):so(e,oo(t))}[...eo,...to],[...to];function lo(e){return N(e,``)?[]:[e.slice(0,1),e.slice(1)]}function uo(e,t){return me(e,(e,n)=>t.startsWith(e)?!0:uo(n,t),()=>!1)}function fo(e,t,n=``){return Xa(lo(t),(r,i)=>uo(e,t)?[n,t]:fo(e,i,`${n}${r}`),()=>[])}function po(e,t){return Xa(fo(e,t),(e,t)=>N(e,``)?[]:[e,t],()=>[])}const mo=(e,t,n=()=>[])=>e.length===2?t(e):n(),ho=e=>mo(co(`-?(?:0|[1-9][0-9]*)n`,e),([e,t])=>[La(e),t]),go=e=>mo(co(`.*`,e),([e,t])=>[Ra(e),t]),_o=e=>mo(co(`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`,e),([e,t])=>[za(e),t]),vo=e=>mo(co(`-?(?:0|[1-9][0-9]*)`,e),([e,t])=>[Ba(e),t]),yo=e=>mo(co(`(?!)`,e),([e,t])=>[Va(e),t]),bo=e=>mo(po([`-?(?:0|[1-9][0-9]*)n`,`.*`,`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`,`-?(?:0|[1-9][0-9]*)`,`(?!)`,`(`,`)`,`$`,`|`],e),([e,t])=>[Ha(e),t]),xo=e=>mo(mo(ho(e),([e,t])=>[e,t],()=>mo(go(e),([e,t])=>[e,t],()=>mo(_o(e),([e,t])=>[e,t],()=>mo(vo(e),([e,t])=>[e,t],()=>mo(yo(e),([e,t])=>[e,t],()=>mo(So(e),([e,t])=>[e,t],()=>mo(bo(e),([e,t])=>[e,t],()=>[]))))))),([e,t])=>[Ua(e),t]),So=e=>mo(mo(co(`(`,e),([e,t])=>mo(To(t),([t,n])=>mo(co(`)`,n),([n,r])=>[[e,t,n],r]))),([e,t])=>[Wa(e),t]),Co=e=>mo(mo(mo(wo(e),([e,t])=>mo(co(`|`,t),([t,n])=>mo(Co(n),([n,r])=>[[e,t,n],r]))),([e,t])=>[e,t],()=>mo(mo(wo(e),([e,t])=>[[e],t]),([e,t])=>[e,t],()=>mo([[],e],([e,t])=>[e,t],()=>[]))),([e,t])=>[Ga(e),t]),wo=e=>mo(mo(xo(e),([e,t])=>mo(To(t),([t,n])=>[[e,t],n])),([e,t])=>[Ka(e),t]),To=e=>mo(mo(Co(e),([e,t])=>[e,t],()=>mo(wo(e),([e,t])=>[e,t],()=>[])),([e,t])=>[qa(e),t]),Eo=e=>mo(mo(co(`^`,e),([e,t])=>mo(To(t),([t,n])=>mo(co(`$`,n),([n,r])=>[[e,t,n],r]))),([e,t])=>[Ja(e),t]);function Do(e){return e.join(`|`)}function Oo(e){return e.slice(1,e.length-1)}function ko(e,t,n){return Bo(t,`${n}${e}`)}function Ao(e,t){return Bo(e,`${t}-?(?:0|[1-9][0-9]*)n`)}function jo(e,t){return Bo(e,`${t}${Ar}`)}function Mo(e,t){return Bo(e,`${t}${Wr}`)}function No(e,t){return zo(Zr([Fr(`false`),Fr(`true`)]),e,t)}function Po(e,t){return Bo(e,`${t}.*`)}function Fo(e,t,n){return Bo(t,`${n}${Oo(e)}`)}function Io(e,t,n){return zo(Vo(e,{}),t,n)}function Lo(e,t,n){return zo(Zi(e),t,n)}function Ro(e,t,n,r=[]){return me(e,(e,i)=>Ro(i,t,n,[...r,zo(e,[],``)]),()=>Bo(t,`${n}(${Do(r)})`))}function zo(e,t,n){return Fn(e)?Lo(e.enum,t,n):Mr(e)?jo(t,n):Vr(e)?ko(e.const,t,n):Or(e)?Ao(t,n):kr(e)?No(t,n):Kr(e)?Mo(t,n):Xr(e)?Po(t,n):Ho(e)?Fo(e.pattern,t,n):iee(e)?Io(e.parameters[0],t,n):Qr(e)?Ro(e.anyOf,t,n):`(?!)`}function Bo(e,t){return me(e,(e,n)=>zo(e,n,t),()=>t)}function eee(e){return`^${Bo(e,``)}$`}function tee(e){return oi(eee(e))}function Vo(e,t){return el(e)?Vt(tee(e),{},t):ree(e,t)}function nee(e,t,n,r){return Vo(rl(e,t,n),r)}function ree(e,t={}){return Wt(`TemplateLiteral`,[e],t)}function iee(e){return Ut(e)&&P(e,`action`)&&N(e.action,`TemplateLiteral`)}function Ho(e){return Ht(e,`TemplateLiteral`)}function aee(e){return zt({"~kind":`ExtendsUnion`},{inferred:e})}function Uo(e){return j(e)&&P(e,`~kind`)&&P(e,`inferred`)&&N(e[`~kind`],`ExtendsUnion`)&&j(e.inferred)}function Wo(e){return zt({"~kind":`ExtendsTrue`},{inferred:e})}function Go(e){return j(e)&&P(e,`~kind`)&&P(e,`inferred`)&&N(e[`~kind`],`ExtendsTrue`)&&j(e.inferred)}function Ko(){return zt({"~kind":`ExtendsFalse`},{})}function qo(e){return j(e)&&P(e,`~kind`)&&N(e[`~kind`],`ExtendsFalse`)}function Jo(e){return Uo(e)||Go(e)}function Yo(e,t,n){return Jo(e)?t(e.inferred):n()}function oee(e,t,n,r){return Yo(Ns(e,n,r),r=>Wo(a(a(e,r),{[t]:n})),()=>Ko())}function see(e,t){return Wo(e)}function cee(e,t,n,r,i){return Yo(Ns(e,t,n),e=>Yo(Ns(e,t,r),e=>Wo(e),()=>Ko()),()=>Yo(Ns(e,t,i),e=>Wo(e),()=>Ko()))}function lee(e,t,n){return Ns(e,t,Zi(n))}function Xo(e,t,n){return me(n,(n,r)=>Yo(Ns(e,t,n),e=>Xo(e,t,r),()=>Ko()),()=>Wo(e))}function uee(e,t,n){return Ns(e,t,$i(n))}function Zo(e,t,n){return me(n,(n,r)=>Yo(Ns(e,t,n),e=>Wo(e),()=>Zo(e,t,r)),()=>Ko())}function Qo(e,t,n){return pn(n)?see(e,t):Nn(n)?cee(e,t,n.if,n.then,n.else):Fn(n)?lee(e,t,n.enum):jn(n)?oee(e,n.name,t,n.extends):Ln(n)?Xo(e,t,n.allOf):Ho(n)?uee(e,t,n.pattern):Qr(n)?Zo(e,t,n.anyOf):En(n)?Wo(e):Ko()}function dee(e,t,n){return jn(n)?Qo(e,t,n):pn(n)||En(n)?Wo(e):aee(e)}function fee(e,t){let n=wr(e),r=wr(t);return n&&r||!n&&r?!0:!(n&&!r)}function pee(e,t,n,r){return $t(r)?fee(t,r)?Ns(e,n,r.items):Ko():Qo(e,t,r)}function mee(e,t,n){return Or(n)?Wo(e):Qo(e,t,n)}function hee(e,t,n){return kr(n)?Wo(e):Qo(e,t,n)}function gee(e,t,n,r,i){let a=jn(r)?t:r,o=jn(r)?r:t,s=vn(t),c=vn(r);return!s&&c?Ko():Yo(Ns(e,a,o),e=>$o(e,n,i),()=>Ko())}function _ee(e,t,n,r){return me(r,(r,i)=>gee(e,t,n,r,i),()=>vn(t)?Wo(e):Ko())}function vee(e,t,n){return me(t,(t,r)=>_ee(e,t,r,n),()=>Wo(e))}function $o(e,t,n){return vee(e,t,n)}function es(e,t,n){return Ia(n)?Wo(e):Ns(e,t,n)}function yee(e,t,n,r){return pn(r)||En(r)?Wo(e):nn(r)?Yo($o(e,t,r.parameters),e=>es(e,n,r.instanceType),()=>Ko()):Ko()}function bee(e,t,n,r,i){return Yo(Ns(e,t,i),()=>Ns(e,n,i),()=>Ns(e,r,i))}function xee(e,t,n){return Ns(e,Zi(t),n)}function See(e,t,n,r){return pn(r)||En(r)?Wo(e):on(r)?Yo($o(e,t,r.parameters),e=>es(e,n,r.returnType),()=>Ko()):Ko()}function Cee(e,t,n){return Mr(n)||Kr(n)?Wo(e):Qo(e,t,n)}function wee(e,t,n){return Ns(e,Qi(t),n)}function ts(e,t,n){return t===n?Wo(e):Ko()}function Tee(e,t,n){return Vr(n)?ts(e,t,n.const):Or(n)?Wo(e):Qo(e,Fr(t),n)}function Eee(e,t,n){return Vr(n)?ts(e,t,n.const):kr(n)?Wo(e):Qo(e,Fr(t),n)}function Dee(e,t,n){return Vr(n)?ts(e,t,n.const):Kr(n)?Wo(e):Qo(e,Fr(t),n)}function Oee(e,t,n){return Vr(n)?ts(e,t,n.const):Xr(n)?Wo(e):Qo(e,Fr(t),n)}function ns(e,t,n){return C(t.const)?Tee(e,t.const,n):w(t.const)?Eee(e,t.const,n):k(t.const)?Dee(e,t.const,n):M(t.const)?Oee(e,t.const,n):Un()}function rs(e,t,n){return jn(n)?Qo(e,t,n):Wo(e)}function is(e,t,n){return Ur(n)?Wo(e):Qo(e,t,n)}function as(e,t,n){return Kr(n)?Wo(e):Qo(e,t,n)}function os(e,t,n){return vn(t)?vn(n)?Wo(e):Ko():Wo(e)}function ss(e,t,n){return jn(n)&&hn(n.extends)?Ko():Yo(Ns(e,t,n),e=>os(e,t,n),()=>Ko())}function cs(e,t){return e.reduce((e,n)=>n in t&&Jo(t[n])?{...e,...t[n].inferred}:Un(),{})}function ls(e,t,n){let r={};for(let i of F(n))r[i]=i in t?ss({},t[i],n[i]):vn(n[i])?jn(n[i])?Wo(a(e,{[n[i].name]:n[i].extends})):Wo(e):Ko();let i=ye(r).every(e=>Jo(e)),o=i?cs(F(r),r):{};return i?Wo(o):Ko()}function us(e,t,n){let r=ls(e,t,n);return Jo(r)?Wo(a(e,r.inferred)):Ko()}function ds(e,t,n){return us(e,t,n)}function fs(e,t){return F(t).reduce((n,r)=>({...n,[r]:P(e,r)?Qr(n[r])?Zr([...n[r].anyOf,t[r]]):Zr([e[r],t[r]]):t[r]}),e)}function ps(e,t,n,r){return me(t,(t,i)=>Yo(Ns({},e[t],n),t=>ps(e,i,n,fs(r,t)),()=>Ko()),()=>Wo(r))}function ms(e,t,n,r){return ps(t,F(t),r,e)}function hs(e,t,n){return Aa(n)?ms(e,t,Da(n),ka(n)):Cn(n)?ds(e,t,n.properties):Qo(e,Sn(t),n)}function gs(e,t){return N(F(t).length,0)?Wo(e):Ko()}function _s(e,t,n,r,i){return Ns(e,n,i)}function vs(e,t,n,r){return Aa(r)?_s(e,Ea(t),n,Ea(Da(r)),ka(r)):Cn(r)?gs(e,r.properties):pn(r)||En(r)?Wo(e):Ko()}function ys(e,t,n){return Xr(n)?Wo(e):Qo(e,t,n)}function bs(e,t,n){return Jr(n)?Wo(e):Qo(e,t,n)}function xs(e,t,n){return Ns(e,$i(t),n)}function Ss(e,t){return zt({"~kind":`Inferrable`},{name:e,type:t},{})}function Cs(e){return j(e)&&P(e,`~kind`)&&P(e,`name`)&&P(e,`type`)&&N(e[`~kind`],`Inferrable`)&&M(e.name)&&j(e.type)}function ws(e){return Ma(e)?jn(e.items)?$t(e.items.extends)?Ss(e.items.name,e.items.extends.items):En(e.items.extends)?Ss(e.items.name,e.items.extends):void 0:Un():void 0}function Ts(e){return jn(e)?Ss(e.name,e.extends):void 0}function Es(e,t,n=[]){return me(e,(e,r)=>Yo(Ns({},e,t),()=>Es(r,t,[...n,e]),()=>void 0),()=>n)}function kee(e,t,n,r){let i=Es(n,r);return S(i)?Wo(a(e,{[t]:bi(i)})):Ko()}function Ds(e,t,n,r){let i=Es(n,r);return S(i)?Wo(a(e,{[t]:Zr(i)})):Ko()}function Aee(e){return[...e].reverse()}function Os(e,t){return t?Aee(e):e}function jee(e){let t=e.length>0?e[0]:void 0;return Ut(Ut(t)?ws(t):void 0)}function Mee(e,t,n,r,i,a){return Yo(Ns(e,n,i),e=>ks(e,t,r,a),()=>Ko())}function Nee(e,t,n,r,i){let a=ws(r);return Cs(a)?kee(e,a.name,Os(n,t),a.type):me(n,(n,a)=>Mee(e,t,n,a,r,i),()=>Ko())}function Pee(e,t,n,r){return me(r,(r,i)=>Nee(e,t,n,r,i),()=>N(n.length,0)?Wo(e):Ko())}function ks(e,t,n,r){return Pee(e,t,n,r)}function Fee(e,t,n){let r=nl(e,$c([],[]),n),i=jee(r);return ks(e,i,Os(t,i),Os(r,i))}function As(e,t,n){let r=Ts(n);return Cs(r)?Ds(e,r.name,t,r.type):me(t,(t,r)=>Yo(Ns(e,t,n),e=>As(e,r,n),()=>Ko()),()=>Wo(e))}function Iee(e,t,n){let r=nl(e,$c([],[]),t);return xi(n)?Fee(e,r,n.items):$t(n)?As(e,r,n.items):Qo(e,bi(r),n)}function Lee(e,t,n){return Ia(n)||Fa(n)?Wo(e):Qo(e,t,n)}function js(e,t,n){return me(n,(n,r)=>Yo(Ns(e,t,n),e=>Wo(e),()=>js(e,t,r)),()=>Ko())}function Ms(e,t,n){return me(t,(t,r)=>Yo(js(e,t,n),e=>Ms(e,r,n),()=>Ko()),()=>Wo(e))}function Ree(e,t,n){let r=Ts(n);return Cs(r)?Ds(e,r.name,t,r.type):Qr(n)?Ms(e,t,n.anyOf):Ms(e,t,[n])}function zee(e,t,n){return jn(n)?Qo(e,t,n):pn(n)||En(n)?Wo(e):Ko()}function Bee(e,t,n){return Ia(n)?Wo(e):Qo(e,t,n)}function Ns(e,t,n){return pn(t)?dee(e,t,n):$t(t)?pee(e,t,t.items,n):Or(t)?mee(e,t,n):kr(t)?hee(e,t,n):nn(t)?yee(e,t.parameters,t.instanceType,n):Nn(t)?bee(e,t.if,t.then,t.else,n):Fn(t)?xee(e,t.enum,n):on(t)?See(e,t.parameters,t.returnType,n):Mr(t)?Cee(e,t,n):Ln(t)?wee(e,t.allOf,n):Vr(t)?ns(e,t,n):hn(t)?rs(e,t,n):Ur(t)?is(e,t,n):Kr(t)?as(e,t,n):Cn(t)?hs(e,t.properties,n):Aa(t)?vs(e,Da(t),ka(t),n):Xr(t)?ys(e,t,n):Jr(t)?bs(e,t,n):Ho(t)?xs(e,t.pattern,n):xi(t)?Iee(e,t.items,n):Fa(t)?Lee(e,t,n):Qr(t)?Ree(e,t.anyOf,n):En(t)?zee(e,t,n):Ia(t)?Bee(e,t,n):Ko()}function Vee(e,t){return Qi([...e,Sn(t)])}function Hee(e,t,n){return el(e)?Vt(Vee(e,t),{},n):Wee(e,t,n)}function Uee(e,t,n,r,i){return Hee(rl(e,t,n),tl(e,t,r),i)}function Wee(e,t,n={}){return Wt(`Interface`,[e,t],n)}function Ps(e){return Ut(e)&&P(e,`action`)&&N(e.action,`Interface`)}function Gee(e,t,n){return e.includes(n)?!0:Ls([...e,n],t,t[n])}function Fs(e,t,n){return Is(e,t,xn(n))}function Is(e,t,n){return me(n,(n,r)=>Ls(e,t,n)?!0:Is(e,t,r),()=>!1)}function Ls(e,t,n){return ln(n)?Gee(e,t,n.$ref):$t(n)?Ls(e,t,n.items):nn(n)?Is(e,t,[...n.parameters,n.instanceType]):on(n)?Is(e,t,[...n.parameters,n.returnType]):Ps(n)?Fs(e,t,n.parameters[1]):Ln(n)?Is(e,t,n.allOf):Cn(n)?Fs(e,t,n.properties):Qr(n)?Is(e,t,n.anyOf):xi(n)?Is(e,t,n.items):Aa(n)?Ls(e,t,ka(n)):!1}function Kee(e,t,n){return Ls(e,t,n)}function qee(e,t){return t.reduce((t,n)=>Kee([n],e,e[n])?[...t,n]:t,[])}function Jee(e){return qee(e,bn(e))}function Yee(e,t,n){return n.includes(t)?n:t in e?Bs(e,e[t],[...n,t]):Un()}function Rs(e,t,n){return zs(e,xn(t),n)}function zs(e,t,n){return t.reduce((t,n)=>Bs(e,n,t),n)}function Bs(e,t,n){return ln(t)?Yee(e,t.$ref,n):$t(t)?Bs(e,t.items,n):nn(t)?zs(e,[...t.parameters,t.instanceType],n):on(t)?zs(e,[...t.parameters,t.returnType],n):Ps(t)?Rs(e,t.parameters[1],n):Ln(t)?zs(e,t.allOf,n):Cn(t)?Rs(e,t.properties,n):Qr(t)?zs(e,t.anyOf,n):xi(t)?zs(e,t.items,n):Aa(t)?Bs(e,ka(t),n):n}function Xee(e,t,n){return Bs(e,n,[t])}function Zee(e){return fn()}function Qee(e){return F(e).reduce((t,n)=>({...t,[n]:Hs(e[n])}),{})}function Vs(e){return e.reduce((e,t)=>[...e,Hs(t)],[])}function Hs(e){return ln(e)?Zee(e.$ref):$t(e)?Qt(Hs(e.items),en(e)):nn(e)?tn(Vs(e.parameters),Hs(e.instanceType)):on(e)?an(Vs(e.parameters),Hs(e.returnType)):Ln(e)?In(Vs(e.allOf)):Cn(e)?Sn(Qee(e.properties)):Aa(e)?wa(Oa(e),Hs(ka(e))):Qr(e)?Zr(Vs(e.anyOf)):xi(e)?bi(Vs(e.items)):e}function $ee(e,t){return t in e?Hs(e[t]):Tn()}function ete(e){return $ee(e.$defs,e.$ref)}function tte(e,t,n){let r=rl(e,$c([],[]),t),i=tl({},$c([],[]),n);return Qi([...r,Sn(i)])}function nte(e,t){return F(e).filter(e=>t.includes(e)).reduce((t,n)=>{let r=e[n],i=Ps(r)?tte(e,r.parameters[0],r.parameters[1]):r;return{...t,[n]:i}},{})}function rte(e,t,n){return Dn(nte(e,Xee(e,t,n)),t)}function Us(e,t){return t in e?ln(e[t])?Us(e,e[t].$ref):e[t]:mn()}function Ws(e,t){return Us(e,t)}function Gs(e){return On(e)?ete(e):kn(e)?Tn():e}function Ks(e,t,n){return Ns(e,Gs(t),Gs(n))}function qs(e,t){let n=[En(e)?Ko():Ks({},e,t),En(e)?Wo({}):Ks({},t,e)];return Jo(n[0])&&Jo(n[1])?`equal`:Jo(n[0])&&qo(n[1])?`left-inside`:qo(n[0])&&Jo(n[1])?`right-inside`:`disjoint`}function ite(e,t){return t.filter(t=>qs(e,t)!==`right-inside`)}function ate(e,t){return N(t.some(t=>{let n=qs(e,t);return N(n,`left-inside`)||N(n,`equal`)}),!1)}function ote(e,t){let n=ta(e);return pn(n)?[n]:ate(n,t)?[...ite(n,t),n]:t}function ste(e){return e.reduce((e,t)=>Cn(t)?[...e,t]:hn(t)?e:ote(t,e),[])}function Js(e){return da(ste(e))}function Ys(e,t){return Vt(ta(e),{},t)}function cte(e,t,n,r){return Ys(sl(e,t,n),r)}function Xs(e,t=[]){return Gt(e)&&N(e.action,`Conditional`)?ln(e.parameters[0])?Xs(e.parameters[2],Xs(e.parameters[3],[...t,e.parameters[0].$ref])):Xs(e.parameters[2],Xs(e.parameters[3],t)):Gt(e)&&N(e.action,`Mapped`)&&Gt(e.parameters[1])&&N(e.parameters[1].action,`KeyOf`)&&ln(e.parameters[1].parameters[0])?[...t,e.parameters[1].parameters[0].$ref]:t}function lte(e,t){return e.reduce((e,n)=>[...e,t.includes(n.name)],[])}function Zs(e,t,n=[]){return me(e,(e,r)=>me(t,(t,i)=>Zs(r,i,[...n,[t,e]]),()=>n),()=>n)}function ute(e){return Qr(e)?[...e.anyOf]:[e]}function dte(e,t){return e.reduce((e,n)=>[...e,[...n,t]],[])}function Qs(e,t){return t.reduce((t,n)=>[...t,...dte(e,n)],[])}function fte(e){return e.reduce((e,t)=>N(t[0],!0)?Qs(e,ute(t[1])):Qs(e,[t[1]]),[[]])}function pte(e,t,n){let r=Zs(t,lte(e,Xs(n)));return Gt(n)&&N(n.action,`Conditional`)||Gt(n)&&N(n.action,`Mapped`)?fte(r):[t]}function mte(){return[`(not-resolvable)`,mn()]}function hte(){return[`(not-generic)`,mn()]}function gte(e,t,n){return[e,un(t,n)]}function _te(e,t,n){return t in e?$s(e,t,e[t],n):mte()}function $s(e,t,n,r){return dn(n)?gte(t,n.parameters,n.expression):ln(n)?_te(e,n.$ref,r):hte()}function vte(e,t,n){return $s(e,`(anonymous)`,t,n)}function yte(e,t,n){if(jn(t)||rc(t)||Jo(Ks({},t,n)))return;let r={parameter:e,expect:n,actual:t};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:r})}function ec(e,t,n,r,i){let o=sl(e,t,i);return yte(n,o,r),a(e,{[n]:o})}function bte(e,t,n,r,i){let a=sl(e,t,n.extends),o=sl(e,t,n.equals);return me(i,(i,o)=>tc(ec(e,t,n.name,a,i),t,r,o),()=>tc(ec(e,t,n.name,a,o),t,r,[]))}function tc(e,t,n,r){return me(n,(n,i)=>bte(e,t,n,i,r),()=>e)}function xte(e,t,n,r){return tc(e,t,n,r)}function Ste(e){return ne(e.callstack.length,0)?e.callstack[e.callstack.length-1]:``}function Cte(e,t){return N(Ste(e),t)}function wte(e,t,n,r,i,a){let o=xte(e,t,r,a),s=sl(o,$c([...t.callstack,n.$ref],t.visited),i);return sl(o,$c([],[]),s)}function Tte(e,t,n,r,i,a){return a.reduce((a,o)=>[...a,wte(e,t,n,r,i,o)],[])}function Ete(e,t,n,r,i,a){let o=Tte(e,t,n,r,i,pte(r,a,i));return N(o.length,1)?o[0]:ea(o)}function Dte(e,t,n,r){let i=rl(e,t,r),a=vte(e,n,r),o=a[0],s=a[1];return dn(s)?Cte(t,o)?nc(cn(o),i):Ete(e,t,cn(o),s.parameters,s.expression,i):nc(n,i)}function nc(e,t){return zt({"~kind":`Call`},{type:`call`,target:e,arguments:t},{})}function rc(e){return Ht(e,`Call`)}function Ote(e){return Bt(e,[`~immutable`])}function kte(e,t){return Vt(Ote(e),{},t)}function Ate(e,t,n,r){return kte(sl(e,t,n),r)}function jte(e,t){return e(t)}function Mte(e,t){return M(t)?Fr(jte(e,t)):Fr(t)}function Nte(e,t){return ic(e,$i(t))}function Pte(e,t){return Zr(t.map(t=>ic(e,t)))}function ic(e,t){return Vr(t)?Mte(e,t.const):Ho(t)?Nte(e,t.pattern):Qr(t)?Pte(e,t.anyOf):t}function Fte(e,t={}){return Wt(`Capitalize`,[e],t)}function Ite(e,t={}){return Wt(`Lowercase`,[e],t)}function Lte(e,t={}){return Wt(`Uncapitalize`,[e],t)}function Rte(e,t={}){return Wt(`Uppercase`,[e],t)}const zte=e=>e[0].toUpperCase()+e.slice(1),Bte=e=>e.toLowerCase(),Vte=e=>e[0].toLowerCase()+e.slice(1),Hte=e=>e.toUpperCase();function Ute(e,t){return el([e])?Vt(ic(zte,e),{},t):Fte(e,t)}function Wte(e,t){return el([e])?Vt(ic(Bte,e),{},t):Ite(e,t)}function Gte(e,t){return el([e])?Vt(ic(Vte,e),{},t):Lte(e,t)}function Kte(e,t){return el([e])?Vt(ic(Hte,e),{},t):Rte(e,t)}function qte(e,t,n,r){return Ute(sl(e,t,n),r)}function Jte(e,t,n,r){return Wte(sl(e,t,n),r)}function Yte(e,t,n,r){return Gte(sl(e,t,n),r)}function Xte(e,t,n,r){return Kte(sl(e,t,n),r)}function Zte(e,t,n,r,i={}){return Wt(`Conditional`,[e,t,n,r],i)}function Qte(e,t,n,r,i,a){let o=Ks(e,n,r);return Uo(o)?Zr([sl(o.inferred,t,i),sl(e,t,a)]):Go(o)?sl(o.inferred,t,i):sl(e,t,a)}function $te(e,t,n,r,i,a,o){return el([n,r])?Vt(Qte(e,t,n,r,i,a),{},o):Zte(n,r,i,a,o)}function ene(e,t,n,r,i,a,o){return $te(e,t,sl(e,t,n),sl(e,t,r),i,a,o)}function tne(e,t={}){return Wt(`ConstructorParameters`,[e],t)}function nne(e){let t=nn(e)?e.parameters:[];return bi(nl({},$c([],[]),t))}function rne(e,t){return el([e])?Vt(nne(e),{},t):tne(e,t)}function ine(e,t,n,r){return rne(sl(e,t,n),r)}function ane(e,t,n={}){return Wt(`Exclude`,[e,t],n)}function ac(e,t,n){return el([e,t])?Vt(Yi(e,t),{},n):ane(e,t,n)}function one(e,t,n,r,i){return ac(sl(e,t,n),sl(e,t,r),i)}function sne(e,t,n={}){return Wt(`Extract`,[e,t],n)}function cne(e,t){return Jo(Ks({},e,t))?[e]:[]}function lne(e,t){return e.reduce((e,n)=>[...e,...cne(n,t)],[])}function une(e,t){let n=ta(e);return ea(lne(Qr(n)?n.anyOf:[n],t))}function dne(e,t,n){return el([e,t])?Vt(une(e,t),{},n):sne(e,t,n)}function fne(e,t,n,r,i){return dne(sl(e,t,n),sl(e,t,r),i)}function pne(e,t,n={}){return Wt(`Index`,[e,t],n)}function mne(e,t){return sc(Ws(e,t))}function hne(e,t,n){return sc(Xi(e,t,n))}function gne(e,t){let n=F(e).filter(e=>!P(t,e)),r=F(t).filter(t=>!P(e,t)),i=F(e).filter(e=>P(t,e)),o=n.reduce((t,n)=>({...t,[n]:e[n]}),{}),s=r.reduce((e,n)=>({...e,[n]:t[n]}),{}),c=i.reduce((n,r)=>({...n,[r]:Qi([e[r],t[r]])}),{});return a(a(o,s),c)}function _ne(e){return e.reduce((e,t)=>gne(e,sc(t)),{})}function vne(e){return e}function yne(e){return sc(Mi(bi(e)))}function bne(e,t){return F(e).filter(e=>e in t).reduce((n,r)=>({...n,[r]:ea([e[r],t[r]])}),{})}function oc(e,t){return me(e,(e,n)=>oc(n,bne(t,sc(e))),()=>t)}function xne(e){return me(e,(e,t)=>oc(t,sc(e)),()=>Un())}function sc(e){return On(e)?mne(e.$defs,e.$ref):Nn(e)?hne(e.if,e.then,e.else):Ln(e)?_ne(e.allOf):Qr(e)?xne(e.anyOf):xi(e)?yne(e.items):Cn(e)?vne(e.properties):{}}function cc(e){return Sn(sc(e))}const Sne=RegExp(`^(?:0|[1-9][0-9]*)$`);function lc(e){let t=`${e}`;return Sne.test(t)?parseInt(t):e}function Cne(e){return Fr(lc(e))}function uc(e){return e.map(e=>dc(e))}function dc(e){return Ln(e)?In(uc(e.allOf)):Qr(e)?Zr(uc(e.anyOf)):Vr(e)?Cne(e.const):e}function wne(e,t){return Jo(Ks({},dc(t),Gr()))?e:Vr(t)&&N(t.const,`length`)?Gr():mn()}function Tne(e,t){return fc(Ws(e,t))}function Ene(e,t,n){return fc(Xi(e,t,n))}function Dne(e){return fc(Zi(e))}function One(e){return fc(Qi(e))}function kne(e){return[`${e}`]}function Ane(e){return fc($i(e))}function jne(e){return e.reduce((e,t)=>[...e,...fc(t)],[])}function fc(e){return On(e)?Tne(e.$defs,e.$ref):Nn(e)?Ene(e.if,e.then,e.else):Fn(e)?Dne(e.enum):Ln(e)?One(e.allOf):Vr(e)?kne(e.const):Ho(e)?Ane(e.pattern):Qr(e)?jne(e.anyOf):[]}function pc(e){return fc(e)}function mc(e,t){return t.map(t=>hc(e,t))}function hc(e,t){return $t(t)?Qt(hc(e,t.items)):nn(t)?tn(mc(e,t.parameters),hc(e,t.instanceType)):on(t)?an(mc(e,t.parameters),hc(e,t.returnType)):xi(t)?bi(mc(e,t.items)):Qr(t)?Zr(mc(e,t.anyOf)):Ln(t)?In(mc(e,t.allOf)):Na(t)?Sn(e):t}function Mne(e,t){return hc(e,t)}function Nne(e,t){return Mne(e,t in e?e[t]:mn())}function gc(e,t){return t.reduce((t,n)=>[...t,Nne(e,n)],[])}function Pne(e,t){return ea(gc(e,pc(t)))}const Fne=new RegExp(ba);function Ine(e){return e.filter(e=>Fne.test(e))}function Lne(e){return ea(gc(e,Ine(bn(e))))}function Rne(e,t){return Kr(t)?Lne(e):Pne(e,t)}function zne(e){return Fr(lc(e))}function _c(e){return e.map(e=>vc(e))}function vc(e){return Ln(e)?In(_c(e.allOf)):Qr(e)?Zr(_c(e.anyOf)):Vr(e)?zne(e.const):e}function Bne(e,t){return e.reduceRight((e,n,r)=>Jo(Ks({},Fr(r),t))?[n,...e]:e,[])}function Vne(e,t){return na(Bne(e,vc(t)))}function Hne(e){return na(e)}function Une(e,t){return Vr(t)&&N(t.const,`length`)?Fr(e.length):Kr(t)||Mr(t)?Hne(e):Vne(e,t)}function Wne(e,t){return $t(e)?wne(e.items,t):Cn(e)?Rne(e.properties,t):xi(e)?Une(e.items,t):mn()}function Gne(e){return On(e)||Nn(e)||Ln(e)||Qr(e)?cc(e):e}function Kne(e,t,n){return el([e,t])?Vt(Wne(Gne(e),t),{},n):pne(e,t,n)}function qne(e,t,n,r,i){return Kne(sl(e,t,n),sl(e,t,r),i)}function yc(e,t={}){return Wt(`InstanceType`,[e],t)}function Jne(e){return nn(e)?e.instanceType:mn()}function Yne(e,t){return el([e])?Vt(Jne(e),{},t):yc(e,t)}function Xne(e,t,n,r={}){return Yne(sl(e,t,n),r)}function bc(e,t={}){return Wt(`KeyOf`,[e],t)}function xc(){return Zr([Gr(),Yr(),qr()])}function Sc(e){return Gr()}function Cc(e){return e.reduce((e,t)=>Ir(t)?[...e,Fr(lc(t))]:Un(),[])}function Zne(e){return na(Cc(F(e)))}function Qne(e){return Oa(e)}function $ne(e){return na(e.map((e,t)=>Fr(t)))}function ere(e){return pn(e)?xc():$t(e)?Sc(e.items):Cn(e)?Zne(e.properties):Aa(e)?Qne(e):xi(e)?$ne(e.items):mn()}function tre(e){return On(e)||Nn(e)||Ln(e)||Qr(e)?cc(e):e}function nre(e,t){return el([e])?Vt(ere(tre(e)),{},t):bc(e,t)}function rre(e,t,n,r){return nre(sl(e,t,n),r)}function ire(e,t,n,r,i={}){return Wt(`Mapped`,[e,t,n,r],i)}function are(e){return wc($i(e))}function ore(e){return e.reduce((e,t)=>[...e,...wc(t)],[])}function sre(e){return wc(Zi(e))}function cre(e){return k(e)?[Fr(`${e}`)]:[Fr(e)]}function wc(e){return Fn(e)?sre(e.enum):Vr(e)?cre(e.const):Ho(e)?are(e.pattern):Qr(e)?ore(e.anyOf):[e]}function Tc(e){return wc(e)}function Ec(e){return Ho(e)?$i(e.pattern):e}function Dc(e,t,n,r,i,o){let s=a(e,{[n.name]:r}),c=Ec(sl(s,t,i)),l=sl(s,t,o);return zr(c)||Br(c)?{[c.const]:l}:{}}function Oc(e,t,n,r,i,a){return r.reduce((r,o)=>[...r,Dc(e,t,n,o,i,a)],[])}function kc(e){return e.reduce((e,t)=>[...e,Sn(t)],[])}function Ac(e,t,n,r,i,a){return Qi(kc(Oc(e,t,n,Tc(r),i,a)))}function jc(e,t,n,r,i,a,o){return el([r])?Vt(Ac(e,t,n,r,i,a),{},o):ire(n,r,i,a,o)}function Mc(e,t,n,r,i,a,o){return jc(e,t,n,sl(e,t,r),i,a,o)}function Nc(e,t,n){let r=a(e,t);return F(t).filter(e=>n.includes(e)).reduce((e,n)=>({...e,[n]:rte(r,n,t[n])}),{})}function Pc(e,t,n){let r=a(e,t);return F(t).filter(e=>!n.includes(e)).reduce((e,n)=>({...e,[n]:sl(r,$c([],[]),t[n])}),{})}function Fc(e,t,n){let r=Jee(t),i=Nc(e,t,r),a=Pc(e,t,r);return Vt({...i,...a},{},n)}function Ic(e,t,n,r){return Fc(e,n,r)}function Lc(e,t={}){return Wt(`NonNullable`,[e],t)}function Rc(e){return ac(e,Zr([Hr(),Pa()]),{})}function zc(e,t){return el([e])?Vt(Rc(e),{},t):Lc(e,t)}function Bc(e,t,n,r){return zc(sl(e,t,n),r)}function Vc(e,t,n={}){return Wt(`Omit`,[e,t],n)}function Hc(e){let t=cc(e);return Cn(t)?t.properties:Un()}function lre(e,t){return F(e).reduce((n,r)=>t.includes(r)?n:{...n,[r]:e[r]},{})}function ure(e,t){return Sn(lre(Hc(e),pc(t)))}function dre(e,t,n){return el([e,t])?Vt(ure(e,t),{},n):Vc(e,t,n)}function fre(e,t,n,r,i){return dre(sl(e,t,n),sl(e,t,r),i)}function pre(e,t={}){return Wt(`Parameters`,[e],t)}function mre(e){let t=on(e)?e.parameters:[];return bi(nl({},$c([],[]),t))}function hre(e,t){return el([e])?Vt(mre(e),{},t):pre(e,t)}function gre(e,t,n,r){return hre(sl(e,t,n),r)}function _re(e,t={}){return Wt(`Partial`,[e],t)}function vre(e,t){let n=Uc(Ws(e,t));return Dn(a(e,{[t]:n}),t)}function yre(e,t,n){return Uc(Xi(e,t,n))}function bre(e){return Uc(Qi(e))}function xre(e){return Zr(e.map(e=>Uc(e)))}function Sre(e){return Sn(F(e).reduce((t,n)=>({...t,[n]:gn(e[n])}),{}))}function Uc(e){return On(e)?vre(e.$defs,e.$ref):Nn(e)?yre(e.if,e.then,e.else):Ln(e)?bre(e.allOf):Qr(e)?xre(e.anyOf):Cn(e)?Sre(e.properties):Sn({})}function Cre(e,t){return el([e])?Vt(Uc(e),{},t):_re(e,t)}function wre(e,t,n,r){return Cre(sl(e,t,n),r)}function Tre(e,t,n={}){return Wt(`Pick`,[e,t],n)}function Ere(e,t){return F(e).reduce((n,r)=>t.includes(r)?a(n,{[r]:e[r]}):n,{})}function Dre(e,t){return Sn(Ere(Hc(e),pc(t)))}function Ore(e,t,n){return el([e,t])?Vt(Dre(e,t),{},n):Tre(e,t,n)}function kre(e,t,n,r,i){return Ore(sl(e,t,n),sl(e,t,r),i)}function Are(e,t={}){return Wt(`ReadonlyObject`,[e],t)}function jre(e){return fl(Qt(e))}function Mre(e,t){let n=Wc(Ws(e,t));return Dn(a(e,{[t]:n}),t)}function Nre(e,t,n){return Wc(Xi(e,t,n))}function Pre(e){return Wc(Qi(e))}function Fre(e){return Sn(F(e).reduce((t,n)=>({...t,[n]:Tr(e[n])}),{}))}function Ire(e){return fl(bi(e))}function Lre(e){return Zr(e.map(e=>Wc(e)))}function Wc(e){return $t(e)?jre(e.items):On(e)?Mre(e.$defs,e.$ref):Nn(e)?Nre(e.if,e.then,e.else):Ln(e)?Pre(e.allOf):Cn(e)?Fre(e.properties):xi(e)?Ire(e.items):Qr(e)?Lre(e.anyOf):e}function Rre(e,t){return el([e])?Vt(Wc(e),{},t):Are(e)}function zre(e,t,n,r){return Rre(sl(e,t,n),r)}function Bre(e,t,n,r){return t.visited.includes(r)?n:r in e?sl(e,$c(t.callstack,[...t.visited,r]),e[r]):n}function Vre(e,t){let n=Gc(Ws(e,t));return Dn(a(e,{[t]:n}),t)}function Hre(e,t,n){return Gc(Xi(e,t,n))}function Ure(e){return Gc(Qi(e))}function Wre(e){return Zr(e.map(e=>Gc(e)))}function Gre(e){return Sn(F(e).reduce((t,n)=>({...t,[n]:Ai(e[n])}),{}))}function Gc(e){return On(e)?Vre(e.$defs,e.$ref):Nn(e)?Hre(e.if,e.then,e.else):Ln(e)?Ure(e.allOf):Qr(e)?Wre(e.anyOf):Cn(e)?Gre(e.properties):Sn({})}function Kre(e,t={}){return Wt(`Required`,[e],t)}function qre(e,t){return el([e])?Vt(Gc(e),{},t):Kre(e,t)}function Jre(e,t,n,r){return qre(sl(e,t,n),r)}function Yre(e,t={}){return Wt(`ReturnType`,[e],t)}function Xre(e){return on(e)?e.returnType:mn()}function Zre(e,t){return el([e])?Vt(Xre(e),{},t):Yre(e,t)}function Kc(e,t,n,r={}){return Zre(sl(e,t,n),r)}function qc(e,t){return Wt(`With`,[e,t],{})}function Jc(e,t){return Yc(e,t)}function Yc(e,t){return el([e])?Vt(e,{},t):qc(e,t)}function Xc(e,t,n,r){return Yc(sl(e,t,n),r)}function Zc(e){return Ma(e)?xi(e.items)?Qc(e.items.items):jn(e.items)||ln(e.items)?[e]:[mn()]:[e]}function Qc(e){return e.reduce((e,t)=>[...e,...Zc(t)],[])}function $c(e,t){return{callstack:e,visited:t}}function el(e){return me(e,(e,t)=>!ln(e)&&el(t),()=>!0)}function tl(e,t,n){return F(n).reduce((r,i)=>({...r,[i]:sl(e,t,n[i])}),{})}function nl(e,t,n){return Qc(rl(e,t,n))}function rl(e,t,n){return n.map(n=>sl(e,t,n))}function il(e,t){let n=vn(e)?Xt(t,{}):t,r=Er(e)?qt(n,{}):n;return wr(e)?ul(r,{}):r}function al(e,t,n,r,i){return N(n,`AddImmutable`)?dl(e,t,r[0],i):N(n,`RemoveImmutable`)?Ate(e,t,r[0],i):N(n,`AddReadonly`)?Jt(e,t,r[0],i):N(n,`RemoveReadonly`)?Ti(e,t,r[0],i):N(n,`AddOptional`)?Zt(e,t,r[0],i):N(n,`RemoveOptional`)?ki(e,t,r[0],i):N(n,`Capitalize`)?qte(e,t,r[0],i):N(n,`Conditional`)?ene(e,t,r[0],r[1],r[2],r[3],i):N(n,`ConstructorParameters`)?ine(e,t,r[0],i):N(n,`Evaluate`)?cte(e,t,r[0],i):N(n,`Exclude`)?one(e,t,r[0],r[1],i):N(n,`Extract`)?fne(e,t,r[0],r[1],i):N(n,`Index`)?qne(e,t,r[0],r[1],i):N(n,`InstanceType`)?Xne(e,t,r[0],i):N(n,`Interface`)?Uee(e,t,r[0],r[1],i):N(n,`KeyOf`)?rre(e,t,r[0],i):N(n,`Lowercase`)?Jte(e,t,r[0],i):N(n,`Mapped`)?Mc(e,t,r[0],r[1],r[2],r[3],i):N(n,`Module`)?Ic(e,t,r[0],i):N(n,`NonNullable`)?Bc(e,t,r[0],i):N(n,`Pick`)?kre(e,t,r[0],r[1],i):N(n,`Parameters`)?gre(e,t,r[0],i):N(n,`Partial`)?wre(e,t,r[0],i):N(n,`Omit`)?fre(e,t,r[0],r[1],i):N(n,`ReadonlyObject`)?zre(e,t,r[0],i):N(n,`Record`)?ya(e,t,r[0],r[1],i):N(n,`Required`)?Jre(e,t,r[0],i):N(n,`ReturnType`)?Kc(e,t,r[0],i):N(n,`TemplateLiteral`)?nee(e,t,r[0],i):N(n,`Uncapitalize`)?Yte(e,t,r[0],i):N(n,`Uppercase`)?Xte(e,t,r[0],i):N(n,`With`)?Xc(e,t,r[0],r[1]):Wt(n,r,i)}function ol(e,t,n){return il(n,ln(n)?Bre(e,t,n,n.$ref):$t(n)?Qt(sl(e,t,n.items),en(n)):rc(n)?Dte(e,t,n.target,n.arguments):nn(n)?tn(rl(e,t,n.parameters),sl(e,t,n.instanceType),rn(n)):on(n)?an(rl(e,t,n.parameters),sl(e,t,n.returnType),sn(n)):Nn(n)?Mn(sl(e,t,n.if),sl(e,t,n.then),sl(e,t,n.else),Pn(n)):Ln(n)?In(rl(e,t,n.allOf),Rn(n)):Cn(n)?Sn(tl(e,t,n.properties),wn(n)):Aa(n)?Ta(Da(n),sl(e,t,ka(n))):Ma(n)?ja(sl(e,t,n.items)):xi(n)?bi(nl(e,t,n.items),Si(n)):Qr(n)?Zr(rl(e,t,n.anyOf),$r(n)):n)}function sl(e,t,n){return Gt(n)?al(e,t,n.action,n.parameters,n.options):ol(e,t,n)}function cl(e,t){return sl(e,$c([],[]),t)}function ll(e){return Vt(e,{"~immutable":!0},{})}function ul(e,t){return Vt(ll(e),{},t)}function dl(e,t,n,r){return ul(sl(e,t,n),r)}function fl(e,t={}){return ul(e,t)}function pl(e,t={}){return Ys(e,t)}function ml(e,t){let n=qs(e,t);return N(n,`right-inside`)?1:+!!N(n,`disjoint`)}function hl(e,t,n=[]){return me(t,(r,i)=>N(ml(e,r),1)?hl(e,i,[...n,r]):[...n,e,...t],()=>[...n,e])}function gl(e,t=[]){return me(e,(e,n)=>gl(n,hl(e,t)),()=>t)}function _l(e){return gl(e)}var vl=class{queue=[];waiting=[];done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise(e=>{this.resolveFinalResult=e})}push(e){if(this.done)return;this.isComplete(e)&&(this.done=!0,this.resolveFinalResult(this.extractResult(e)));let t=this.waiting.shift();t?t({value:e,done:!1}):this.queue.push(e)}end(e){for(this.done=!0,e!==void 0&&this.resolveFinalResult(e);this.waiting.length>0;)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else{let e=await new Promise(e=>this.waiting.push(e));if(e.done)return;yield e.value}}result(){return this.finalResultPromise}},yl=class extends vl{constructor(){super(e=>e.type===`done`||e.type===`error`,e=>{if(e.type===`done`)return e.message;if(e.type===`error`)return e.error;throw Error(`Unexpected event type for final result`)})}};function bl(e){return P(e,`~refine`)&&S(e[`~refine`])&&fe(e[`~refine`],0,e=>j(e)&&P(e,`check`)&&P(e,`error`)&&E(e.check)&&E(e.error))}function xl(e){return j(e)&&!S(e)}function Sl(e){return w(e)}function Cl(e){return xl(e)||Sl(e)}function wl(e){return P(e,`additionalItems`)&&Cl(e.additionalItems)}function Tl(e){return P(e,`additionalProperties`)&&Cl(e.additionalProperties)}function El(e){return P(e,`allOf`)&&S(e.allOf)&&e.allOf.every(e=>Cl(e))}function Dl(e){return P(e,`$anchor`)&&M(e.$anchor)}function Ol(e){return P(e,`anyOf`)&&S(e.anyOf)&&e.anyOf.every(e=>Cl(e))}function kl(e){return P(e,`const`)}function Al(e){return P(e,`contains`)&&Cl(e.contains)}function jl(e){return P(e,`default`)}function Ml(e){return P(e,`dependencies`)&&j(e.dependencies)&&Object.values(e.dependencies).every(e=>Cl(e)||S(e)&&e.every(e=>M(e)))}function Nl(e){return P(e,`dependentRequired`)&&j(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>S(e)&&e.every(e=>M(e)))}function Pl(e){return P(e,`dependentSchemas`)&&j(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>Cl(e))}function Fl(e){return P(e,`$dynamicAnchor`)&&M(e.$dynamicAnchor)}function Il(e){return P(e,`$dynamicRef`)&&M(e.$dynamicRef)}function Ll(e){return P(e,`else`)&&Cl(e.else)}function Rl(e){return P(e,`enum`)&&S(e.enum)}function zl(e){return P(e,`exclusiveMaximum`)&&(k(e.exclusiveMaximum)||C(e.exclusiveMaximum))}function Bl(e){return P(e,`exclusiveMinimum`)&&(k(e.exclusiveMinimum)||C(e.exclusiveMinimum))}function Vl(e){return P(e,`format`)&&M(e.format)}function Hl(e){return P(e,`$id`)&&M(e.$id)}function Ul(e){return P(e,`if`)&&Cl(e.if)}function Wl(e){return P(e,`items`)&&(Cl(e.items)||S(e.items)&&e.items.every(e=>Cl(e)))}function Gl(e){return Wl(e)&&S(e.items)}function Kl(e){return P(e,`maximum`)&&(k(e.maximum)||C(e.maximum))}function ql(e){return P(e,`maxContains`)&&k(e.maxContains)}function Jl(e){return P(e,`maxItems`)&&k(e.maxItems)}function Yl(e){return P(e,`maxLength`)&&k(e.maxLength)}function Xl(e){return P(e,`maxProperties`)&&k(e.maxProperties)}function Zl(e){return P(e,`minimum`)&&(k(e.minimum)||C(e.minimum))}function Ql(e){return P(e,`minContains`)&&k(e.minContains)}function $l(e){return P(e,`minItems`)&&k(e.minItems)}function eu(e){return P(e,`minLength`)&&k(e.minLength)}function tu(e){return P(e,`minProperties`)&&k(e.minProperties)}function nu(e){return P(e,`multipleOf`)&&(k(e.multipleOf)||C(e.multipleOf))}function ru(e){return P(e,`not`)&&Cl(e.not)}function iu(e){return P(e,`oneOf`)&&S(e.oneOf)&&e.oneOf.every(e=>Cl(e))}function au(e){return P(e,`pattern`)&&(M(e.pattern)||e.pattern instanceof RegExp)}function ou(e){return P(e,`patternProperties`)&&j(e.patternProperties)&&Object.values(e.patternProperties).every(e=>Cl(e))}function su(e){return P(e,`prefixItems`)&&S(e.prefixItems)&&e.prefixItems.every(e=>Cl(e))}function cu(e){return P(e,`properties`)&&j(e.properties)&&Object.values(e.properties).every(e=>Cl(e))}function lu(e){return P(e,`propertyNames`)&&(j(e.propertyNames)||Cl(e.propertyNames))}function Qre(e){return P(e,`$recursiveAnchor`)&&w(e.$recursiveAnchor)}function uu(e){return Qre(e)&&N(e.$recursiveAnchor,!0)}function du(e){return P(e,`$recursiveRef`)&&M(e.$recursiveRef)}function fu(e){return P(e,`$ref`)&&M(e.$ref)}function pu(e){return P(e,`required`)&&S(e.required)&&e.required.every(e=>M(e))}function mu(e){return P(e,`then`)&&Cl(e.then)}function hu(e){return P(e,`type`)&&(M(e.type)||S(e.type)&&e.type.every(e=>M(e)))}function gu(e){return P(e,`uniqueItems`)&&w(e.uniqueItems)}function _u(e){return P(e,`unevaluatedItems`)&&Cl(e.unevaluatedItems)}function vu(e){return P(e,`unevaluatedProperties`)&&Cl(e.unevaluatedProperties)}function $re(e){return _u(e)||vu(e)||F(e).some(t=>yu(e[t]))}function eie(e){return e.some(e=>yu(e))}function yu(e){return S(e)?eie(e):j(e)?$re(e):!1}function tie(e,t){return yu(t)||F(e).some(t=>yu(e[t]))}var nie=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return tt(rt(`context`,`Push`),[])}Pop(){return tt(rt(`context`,`Pop`),[])}AddIndex(e){return tt(rt(`context`,`AddIndex`),[e])}AddKey(e){return tt(rt(`context`,`AddKey`),[e])}Merge(e){return tt(rt(`context`,`Merge`),[e])}},bu=class{constructor(){let e=new Set,t=new Set;this.stack=[{indices:e,keys:t}]}Push(){let e=new Set,t=new Set;return this.stack.push({indices:e,keys:t}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let t of e)t.GetIndices().forEach(e=>this.GetIndices().add(e)),t.GetKeys().forEach(e=>this.GetKeys().add(e));return!0}},xu=class extends bu{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Su=class extends xu{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const Cu={identifier:`External`,variables:[]};function wu(e){let t=`External[${Cu.variables.length}]`;return Cu.variables.push(e),t}function rie(){Cu.variables=[]}function iie(){return{...Cu}}function aie(e,t,n,r){return Je(wu(n[`~refine`].map(e=>e)),it(0),[`refinement`,`_`],tt(rt(`refinement`,`check`),[r]))}function oie(e,t,n,r){return fe(n[`~refine`],0,(e,t)=>e.check(r))}function sie(e,t,n,r,i,a){return pe(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let cie=0;function Tu(){return`var_${cie++}`}function Eu(e){return Wl(e)&&S(e.items)}function lie(e,t,n,r){if(!Eu(n))return it(!0);let[i,a]=[Tu(),Tu()],o=vp(e,t,n.additionalItems,i),s=Ue(a,it(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?Ee(s,Te(o,c)):Ee(s,o);return tt(rt(r,`every`),[et([i,a],l)])}function uie(e,t,n,r){return!Eu(n)||r.every((r,i)=>re(i,n.items.length)||bp(e,t,n.additionalItems,r)&&t.AddIndex(i))}function die(e,t,n,r,i,a){return!Eu(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return re(o,i.items.length)||Sp(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function fie(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function Du(e){let t=[];return ou(e)&&t.push(...F(e.patternProperties)),cu(e)&&t.push(...F(e.properties).map(fie)),N(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function pie(e,t,n){return pu(t)&&cu(t)&&!ou(t)&&N(t.additionalProperties,!1)&&N(F(t.properties).length,t.required.length)}function mie(e,t,n){return Ve(rt(tt(rt(`Object`,`getOwnPropertyNames`),[n]),`length`),it(t.required.length))}function hie(e,t,n,r){let[i,a]=[Tu(),Tu()],o=wu(new RegExp(Du(n))),s=vp(e,t,n.additionalProperties,`${r}[${i}]`),c=tt(rt(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?Ee(c,Te(s,l)):Ee(c,s);return Je(Xe(r),it(0),[i,a],u)}function gie(e,t,n,r){return pie(t,n,r)?mie(t,n,r):hie(e,t,n,r)}function _ie(e,t,n,r){let i=new RegExp(Du(n));return fe(F(r),0,(a,o)=>i.test(a)||bp(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function vie(e,t,n,r,i,a){let o=new RegExp(Du(i)),s=[];return pe(F(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new Su,p=o.test(c)||Sp(e,f,u,d,i.additionalProperties,a[c])&&t.AddKey(c);return p||s.push(c),p})||t.AddError({keyword:`additionalProperties`,schemaPath:n,instancePath:r,params:{additionalProperties:s}})}function Ou(e,t,n,r,i){let a=st(`results`,`[]`),o=n.map((e,t)=>st(`context_${t}`,nt(`CheckContext`,[]))),s=n.map((n,i)=>st(`condition_${i}`,tt(et([`context`],yp(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>ct(`condition_${t}`,tt(rt(`results`,`push`),[`context_${t}`]))),l=lt(Te(i,t.Merge(`results`)));return tt(et([],ot([a,...o,...s,...c,l])),[])}function yie(e,t,n,r){return Ou(e,t,n.allOf,r,Ve(rt(`results`,`length`),it(n.allOf.length)))}function bie(e,t,n,r){return ut(n.allOf.map(n=>yp(e,t,n,r)))}function xie(e,t,n,r){return t.UseUnevaluated()?yie(e,t,n,r):bie(e,t,n,r)}function Sie(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new bu;return xp(e,i,n,r)?[...t,i]:t},[]);return N(i.length,n.allOf.length)&&t.Merge(i)}function Cie(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new Su,u=Cp(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=N(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function wie(e,t,n,r){return Ou(e,t,n.anyOf,r,He(rt(`results`,`length`),it(0)))}function Tie(e,t,n,r){return dt(n.anyOf.map(n=>yp(e,t,n,r)))}function Eie(e,t,n,r){return t.UseUnevaluated()?wie(e,t,n,r):Tie(e,t,n,r)}function Die(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new bu;return xp(e,i,n,r)?[...t,i]:t},[]);return ne(i.length,0)&&t.Merge(i)}function Oie(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new Su,l=Cp(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=ne(s.length,0)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c||t.AddError({keyword:`anyOf`,schemaPath:n,instancePath:r,params:{}})}function kie(e,t,n,r){return it(!!n)}function ku(e,t,n,r){return n}function Aie(e,t,n,r,i,a){return ku(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function jie(e,t,n,r){return ce(n.const)?Ve(r,it(n.const)):Qe(r,wu(n.const))}function Au(e,t,n,r){return ce(n.const)?N(r,n.const):Se(r,n.const)}function Mie(e,t,n,r,i,a){return Au(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function ju(e){return!(Ql(e)&&N(e.minContains,0))}function Nie(e,t,n,r){if(!ju(n))return it(!0);let i=Tu();return Te(De(Ve(rt(r,`length`),it(0))),tt(rt(r,`some`),[et([i],yp(e,t,n.contains,i))]))}function Mu(e,t,n,r){return!ju(n)||!N(r.length,0)&&r.some(r=>xp(e,t,n.contains,r))}function Pie(e,t,n,r,i,a){return Mu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function Fie(e,t,n,r){return Ee(Ve(rt(Xe(r),`length`),it(0)),ut(_e(n.dependencies).map(([n,i])=>{let a=De(Ze(r,it(n))),o=yp(e,t,i,r);return Ee(a,S(i)?(e=>ut(e.map(e=>Ze(r,it(e)))))(i):o)})))}function Iie(e,t,n,r){let i=N(F(r).length,0),a=fe(_e(n.dependencies),0,([n,i])=>!P(r,n)||(S(i)?i.every(e=>P(r,e)):xp(e,t,i,r)));return i||a}function Lie(e,t,n,r,i,a){let o=N(F(a).length,0),s=pe(_e(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!P(a,i)||(S(o)?o.every(e=>P(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):Cp(e,t,s,r,o,a))});return o||s}function Rie(e,t,n,r){return Ee(Ve(rt(Xe(r),`length`),it(0)),ut(_e(n.dependentRequired).map(([e,t])=>Ee(De(Ze(r,it(e))),ut(t.map(e=>Ze(r,it(e))))))))}function zie(e,t,n,r){let i=N(F(r).length,0),a=fe(_e(n.dependentRequired),0,([e,t])=>!P(r,e)||t.every(e=>P(r,e)));return i||a}function Bie(e,t,n,r,i,a){let o=N(F(a).length,0),s=pe(_e(i.dependentRequired),0,([e,i])=>!P(a,e)||pe(i,0,o=>P(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function Vie(e,t,n,r){return Ee(Ve(rt(Xe(r),`length`),it(0)),ut(_e(n.dependentSchemas).map(([n,i])=>Ee(De(Ze(r,it(n))),yp(e,t,i,r)))))}function Hie(e,t,n,r){let i=N(F(r).length,0),a=fe(_e(n.dependentSchemas),0,([n,i])=>!P(r,n)||xp(e,t,i,r));return i||a}function Uie(e,t,n,r,i,a){let o=N(F(a).length,0),s=pe(_e(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!P(a,i)||Cp(e,t,s,r,o,a)});return o||s}function Wie(e,t,n,r){return Np(e,t,e.DynamicRef(n)??!1,r)}function Gie(e,t,n,r){let i=e.DynamicRef(n)??!1;return Cl(i)&&xp(e,t,i,r)}function Kie(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return Cl(o)&&Cp(e,t,`#`,r,o,a)}function qie(e,t,n,r){return dt(n.enum.map(e=>ce(e)?Ve(r,it(e)):Qe(r,wu(e))))}function Nu(e,t,n,r){return n.enum.some(e=>ce(e)?N(r,e):Se(r,e))}function Jie(e,t,n,r,i,a){return Nu(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function Yie(e,t,n,r){return Ue(r,it(n.exclusiveMaximum))}function Pu(e,t,n,r){return re(r,n.exclusiveMaximum)}function Xie(e,t,n,r,i,a){return Pu(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function Zie(e,t,n,r){return He(r,it(n.exclusiveMinimum))}function Fu(e,t,n,r){return ne(r,n.exclusiveMinimum)}function Qie(e,t,n,r,i,a){return Fu(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const $ie=[0,31,28,31,30,31,30,31,31,30,31,30,31],eae=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function tae(e){return e%4==0&&(e%100!=0||e%400==0)}function Iu(e){let t=eae.exec(e);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r===2&&tae(n)?29:$ie[r])}const nae=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function Lu(e,t=!0){let n=nae.exec(e);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4]===`-`?-1:1,s=+(n[5]||0),c=+(n[6]||0);if(s>23||c>59||t&&!n[4]&&e.toLowerCase().indexOf(`z`)===-1)return!1;if(r<=23&&i<=59&&a<60)return!0;let l=i-c*o,u=r-s*o-+(l<0);return(u===23||u===-1)&&(l===59||l===-1)&&a<61}function Ru(e,t=!0){let n=e.split(/T/i);return n.length===2&&Iu(n[0])&&Lu(n[1],t)}const rae=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function zu(e){return rae.test(e)}const iae=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function Bu(e){return iae.test(e)}function aae(e,t,n){e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let r=0;for(;e>455;)e=Math.floor(e/35),r+=36;return r+Math.floor(36*e/(e+38))}function oae(e){let t=[],n=128,r=0,i=72,a=e.lastIndexOf(`-`);if(a>0)for(let n=0;n=128)throw Error(`Invalid punycode: non-basic before delimiter`);t.push(r)}let o=a<0?0:a+1;for(;o=e.length)throw Error(`Invalid punycode: unexpected end of input`);let t=e.charCodeAt(o++),n;if(t>=97&&t<=122)n=t-97;else if(t>=48&&t<=57)n=t-48+26;else if(t>=65&&t<=90)Un();else throw Error(`Invalid punycode: bad digit character`);r+=n*s;let a=c<=i?1:c>=i+26?26:c-i;if(n=1632&&e<=1641}function yae(e){return e>=1776&&e<=1785}function Vu(e){return fae.has(e)}function Hu(e){if(e.length===0)return Un();let t=[...e].map(e=>e.codePointAt(0)),n=t.length;if(t[0]===45||t[n-1]===45||n>=4&&t[2]===45&&t[3]===45||uae(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45))return!1}return!0}function Uu(e){return e.toLowerCase().startsWith(`xn--`)}function Wu(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=oae(t);return n?Hu(n):!1}catch{return!1}}function xae(e){return e.length===0||e.length>63?!1:Uu(e)?Wu(e):Hu(e)}function Sae(e){return e.length===0||e.length>63?!1:Uu(e)?Wu(e):bae(e)}function Gu(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!Sae(t))return!1;return!0}const Cae=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function Ku(e){return Cae.test(e)}function qu(e){if(e.length===0||e.includes(` `))return!1;let t=e.normalize(`NFC`).replace(/[\u002E\u3002\uFF0E\uFF61]/g,`.`);if(t.length>253)return!1;for(let e of t.split(`.`))if(!xae(e))return!1;return!0}function Ju(e,t,n){let r=0,i=0,a=0,o=0;for(let s=t;s255||o===48&&a>1)return!1;r++,i=0,a=0,o=0}else if(t>=48&&t<=57)a===0&&(o=t),i=i*10+(t-48),a++;else return!1}return r===3&&a>0&&i<=255&&!(o===48&&a>1)}function Yu(e){return Ju(e,0,e.length)}function wae(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Xu(e){let t=e.length;if(t===0)return!1;let n=0,r=!1,i=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;r=!0,i=2}for(;i4)return!1;if(n++,i===t)break;if(s!==58)return!1;if(i++,e.charCodeAt(i)===58){if(r||e.charCodeAt(i+1)===58)return!1;if(r=!0,i++,i===t)break}}return r?n<=7:n===8}function Zu(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function Qu(e){if(e.includes(` `)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e===``)return!0;let t=e.indexOf(`:`);return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?Zu(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:Zu(e)}function $u(e){try{return new URL(e),!0}catch{return!1}}const Tae=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function ed(e){return Tae.test(e)}const Eae=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function td(e){return Eae.test(e)}function nd(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const Dae=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function rd(e){return Dae.test(e)}const Oae=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function id(e){return Oae.test(e)}const kae=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function ad(e){return kae.test(e)}function od(e){return e>=97&&e<=122||e>=65&&e<=90}function sd(e){return od(e)||e>=48&&e<=57}function cd(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Aae(e){return sd(e)||e===43||e===45||e===46}function ld(e){return sd(e)||e===45||e===46||e===95||e===126}function ud(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function jae(e){return ld(e)||ud(e)||e===58||e===64}function dd(e){let t=e.length;if(t===0||!od(e.charCodeAt(0)))return!1;let n=1;for(;n=i||!cd(e.charCodeAt(t+1))||!cd(e.charCodeAt(t+2)))return!1;t+=2}else if(!ld(n)&&!ud(n)&&n!==58)return!1}n=i+1}if(e.charCodeAt(n)===91){for(n++;n57)return!1;n++}}for(;n=t||!cd(e.charCodeAt(n+1))||!cd(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(jae(r)||r===47||r===63||r===35))return!1;n++}return!0}const Mae=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function fd(e){return Mae.test(e)}const Nae=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function pd(e){return Nae.test(e)}const md=new Map;function hd(){md.clear()}function Pae(){return[...md.entries()]}function Fae(e,t){md.set(e,t)}function Iae(e){return md.has(e)}function Lae(e){return md.get(e)}function gd(e,t){return md.get(e)?.(t)??!0}function _d(){hd(),md.set(`date-time`,Ru),md.set(`date`,Iu),md.set(`duration`,zu),md.set(`email`,Bu),md.set(`hostname`,Gu),md.set(`idn-email`,Ku),md.set(`idn-hostname`,qu),md.set(`ipv4`,Yu),md.set(`ipv6`,Xu),md.set(`iri-reference`,Qu),md.set(`iri`,$u),md.set(`json-pointer-uri-fragment`,ed),md.set(`json-pointer`,td),md.set(`regex`,nd),md.set(`relative-json-pointer`,rd),md.set(`time`,Lu),md.set(`uri-reference`,id),md.set(`uri-template`,ad),md.set(`uri`,dd),md.set(`url`,fd),md.set(`uuid`,pd)}_d();var Rae=n({Clear:()=>hd,Entries:()=>Pae,Get:()=>Lae,Has:()=>Iae,IsDate:()=>Iu,IsDateTime:()=>Ru,IsDuration:()=>zu,IsEmail:()=>Bu,IsHostname:()=>Gu,IsIPv4:()=>Yu,IsIPv6:()=>Xu,IsIdnEmail:()=>Ku,IsIdnHostname:()=>qu,IsIri:()=>$u,IsIriReference:()=>Qu,IsJsonPointer:()=>td,IsJsonPointerUriFragment:()=>ed,IsRegex:()=>nd,IsRelativeJsonPointer:()=>rd,IsTime:()=>Lu,IsUri:()=>dd,IsUriReference:()=>id,IsUriTemplate:()=>ad,IsUrl:()=>fd,IsUuid:()=>pd,Reset:()=>_d,Set:()=>Fae,Test:()=>gd});function zae(e,t,n,r){return tt(rt(`Format`,`Test`),[it(n.format),r])}function vd(e,t,n,r){return gd(n.format,r)}function Bae(e,t,n,r,i,a){return vd(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function Vae(e,t,n,r){let i=!mu(n)||n.then,a=!Ll(n)||n.else;return at(yp(e,t,n.if,r),yp(e,t,i,r),yp(e,t,a,r))}function Hae(e,t,n,r){let i=!mu(n)||n.then,a=!Ll(n)||n.else;return xp(e,t,n.if,r)?xp(e,t,i,r):xp(e,t,a,r)}function Uae(e,t,n,r,i,a){let o=!mu(i)||i.then,s=!Ll(i)||i.else,c=new Su,l=Cp(e,c,`${n}/if`,r,i.if,a)?Cp(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):Cp(e,t,`${n}/else`,r,s,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`else`}});return l&&t.Merge([c]),l}function Wae(e,t,n,r){return ut(n.items.map((n,i)=>{let a=We(rt(r,`length`),it(i)),o=vp(e,t,n,`${r}[${i}]`),s=t.AddIndex(it(i));return Ee(a,t.UseUnevaluated()?Te(o,s):o)}))}function Gae(e,t,n,r){return fe(n.items,0,(n,i)=>ie(r.length,i)||bp(e,t,n,r[i])&&t.AddIndex(i))}function Kae(e,t,n,r,i,a){return pe(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return ie(a.length,o)||Sp(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function yd(e,t,n,r){let i=su(n)?n.prefixItems.length:0,a=vp(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?Te(a,o):a;return Je(r,it(i),[`element`,`index`],s)}function bd(e,t,n,r){return fe(r,su(n)?n.prefixItems.length:0,(r,i)=>bp(e,t,n.items,r)&&t.AddIndex(i))}function xd(e,t,n,r,i,a){return pe(a,su(i)?i.prefixItems.length:0,(a,o)=>Sp(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function Sd(e,t,n,r){return Gl(n)?Wae(e,t,n,r):yd(e,t,n,r)}function Cd(e,t,n,r){return Gl(n)?Gae(e,t,n,r):bd(e,t,n,r)}function wd(e,t,n,r,i,a){return Gl(i)?Kae(e,t,n,r,i,a):xd(e,t,n,r,i,a)}function Td(e){return Al(e)}function Ed(e,t,n,r){if(!Td(n))return it(!0);let[i,a]=[Tu(),Tu()];return We(tt(rt(r,`reduce`),[et([i,a],at(yp(e,t,n.contains,a),ft(i),i)),it(0)]),it(n.maxContains))}function Dd(e,t,n,r){return!Td(n)||ie(r.reduce((r,i)=>xp(e,t,n.contains,i)?++r:r,0),n.maxContains)}function Od(e,t,n,r,i,a){let o=Ql(i)?i.minContains:1;return Dd(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function kd(e,t,n,r){return We(r,it(n.maximum))}function Ad(e,t,n,r){return ie(r,n.maximum)}function jd(e,t,n,r,i,a){return Ad(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function Md(e,t,n,r){return We(rt(r,`length`),it(n.maxItems))}function Nd(e,t,n,r){return ie(r.length,n.maxItems)}function Pd(e,t,n,r,i,a){return Nd(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function Fd(e,t,n,r){return qe(r,it(n.maxLength))}function Id(e,t,n,r){return ue(r,n.maxLength)}function Ld(e,t,n,r,i,a){return Id(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function Rd(e,t,n,r){return We(rt(Xe(r),`length`),it(n.maxProperties))}function zd(e,t,n,r){return ie(F(r).length,n.maxProperties)}function Bd(e,t,n,r,i,a){return zd(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function Vd(e){return Al(e)}function Hd(e,t,n,r){if(!Vd(n))return it(!0);let[i,a]=[Tu(),Tu()];return Ge(tt(rt(r,`reduce`),[et([i,a],at(yp(e,t,n.contains,a),ft(i),i)),it(0)]),it(n.minContains))}function Ud(e,t,n,r){return!Vd(n)||ae(r.reduce((r,i)=>xp(e,t,n.contains,i)?++r:r,0),n.minContains)}function Wd(e,t,n,r,i,a){return Ud(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function Gd(e,t,n,r){return Ge(r,it(n.minimum))}function Kd(e,t,n,r){return ae(r,n.minimum)}function qd(e,t,n,r,i,a){return Kd(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function Jd(e,t,n,r){return Ge(rt(r,`length`),it(n.minItems))}function Yd(e,t,n,r){return ae(r.length,n.minItems)}function Xd(e,t,n,r,i,a){return Yd(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function Zd(e,t,n,r){return Ke(r,it(n.minLength))}function Qd(e,t,n,r){return de(r,n.minLength)}function $d(e,t,n,r,i,a){return Qd(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function ef(e,t,n,r){return Ge(rt(Xe(r),`length`),it(n.minProperties))}function tf(e,t,n,r){return ae(F(r).length,n.minProperties)}function nf(e,t,n,r,i,a){return tf(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function rf(e,t,n,r){return pt(r,it(n.multipleOf))}function af(e,t,n,r){return oe(r,n.multipleOf)}function of(e,t,n,r,i,a){return af(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function sf(e,t,n,r){return Ou(e,t,[n.not],r,De(Ve(rt(`results`,`length`),it(1))))}function cf(e,t,n,r){return De(yp(e,t,n.not,r))}function lf(e,t,n,r){return t.UseUnevaluated()?sf(e,t,n,r):cf(e,t,n,r)}function uf(e,t,n,r){let i=new bu;return!xp(e,i,n.not,r)&&t.Merge([i])}function df(e,t,n,r,i,a){return uf(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function ff(e,t,n,r){return Ou(e,t,n.oneOf,r,Ve(rt(`results`,`length`),it(1)))}function pf(e,t,n,r){return Ve(tt(rt($e(n.oneOf.map(n=>yp(e,t,n,r))),`reduce`),[et([`count`,`result`],at(Ve(`result`,it(!0)),ft(`count`),`count`)),it(0)]),it(1))}function mf(e,t,n,r){return t.UseUnevaluated()?ff(e,t,n,r):pf(e,t,n,r)}function hf(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new bu;return xp(e,i,n,r)?[...t,i]:t},[]);return N(i.length,1)&&t.Merge(i)}function gf(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new Su,u=Cp(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=N(c.length,1)&&t.Merge(c);return!l&&N(s.length,0)&&o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),l||t.AddError({keyword:`oneOf`,schemaPath:n,instancePath:r,params:{passingSchemas:s}})}function _f(e,t,n,r){return tt(rt(wu(M(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function vf(e,t,n,r){return(M(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function yf(e,t,n,r,i,a){return vf(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function bf(e,t,n,r){return ut(_e(n.patternProperties).map(([n,i])=>{let[a,o]=[Tu(),Tu()],s=De(tt(rt(wu(new RegExp(n,`u`)),`test`),[a])),c=vp(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?Ee(s,Te(c,l)):Ee(s,c);return Je(Ye(r),it(0),[`[${a}, ${o}]`,`_`],u)}))}function xf(e,t,n,r){return fe(_e(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return fe(_e(r),0,([n,r])=>!a.test(n)||bp(e,t,i,r)&&t.AddKey(n))})}function Sf(e,t,n,r,i,a){return pe(_e(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return pe(_e(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||Sp(e,t,s,a,o,i)&&t.AddKey(n)})})}function Cf(e,t,n,r){return ut(n.prefixItems.map((n,i)=>{let a=We(rt(r,`length`),it(i)),o=vp(e,t,n,`${r}[${i}]`),s=t.AddIndex(it(i));return Ee(a,t.UseUnevaluated()?Te(o,s):o)}))}function wf(e,t,n,r){return N(r.length,0)||fe(n.prefixItems,0,(n,i)=>ie(r.length,i)||bp(e,t,n,r[i])&&t.AddIndex(i))}function Tf(e,t,n,r,i,a){return N(a.length,0)||pe(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return ie(a.length,o)||Sp(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function Ef(e,t){return e.includes(t)||It().exactOptionalPropertyTypes}function Df(e,t){return Re(rt(e,t))}function Of(e,t){return te(e[t])}function kf(e,t,n,r){let i=pu(n)?n.required:[];return ut(_e(n.properties).map(([n,a])=>{let o=De(Ze(r,it(n))),s=vp(e,t,a,rt(r,n)),c=t.AddKey(it(n)),l=t.UseUnevaluated()?Te(s,c):s,u=i.includes(n)?l:Ee(o,l);return Ef(i,n)?u:Ee(Df(r,n),u)}))}function Af(e,t,n,r){let i=pu(n)?n.required:[];return fe(_e(n.properties),0,([n,a])=>{let o=!P(r,n)||bp(e,t,a,r[n])&&t.AddKey(n);return Ef(i,n)?o:Of(r,n)||o})}function jf(e,t,n,r,i,a){let o=pu(i)?i.required:[];return pe(_e(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!P(a,i)||Sp(e,t,c,l,s,a[i])&&t.AddKey(i);return Ef(o,i)?u():Of(a,i)||u()})}function Mf(e,t,n,r){let[i,a]=[Tu(),Tu()];return Je(Xe(r),it(0),[i,a],yp(e,t,n.propertyNames,i))}function Nf(e,t,n,r){return fe(F(r),0,(r,i)=>xp(e,t,n.propertyNames,r))}function Pf(e,t,n,r,i,a){let o=[];return pe(F(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=Cp(e,new Su,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Ff(e,t,n,r){return Np(e,t,e.RecursiveRef(n)??!1,r)}function If(e,t,n,r){let i=e.RecursiveRef(n)??!1;return Cl(i)&&xp(e,t,i,r)}function Lf(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return Cl(o)&&Cp(e,t,`#`,r,o,a)}function Rf(e,t,n,r){let i=et([`context`,`value`],Np(e,t,n,`value`));return tt(et([`context`,`value`],ot([st(`nextContext`,nt(`CheckContext`,[])),st(`result`,tt(i,[`nextContext`,`value`])),ct(`result`,t.Merge(`[nextContext]`)),lt(`result`)])),[`context`,r])}function zf(e,t,n,r){return Np(e,t,n,r)}function Bf(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?Rf(e,t,i,r):zf(e,t,i,r)}function Vf(e,t,n,r){let i=e.Ref(n)??!1,a=new bu,o=Cl(i)&&xp(e,a,i,r);return o&&t.Merge([a]),o}function Hf(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new Su,c=Cl(o)&&Cp(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function Uf(e,t,n,r){return ut(n.required.map(e=>Ze(r,it(e))))}function Wf(e,t,n,r){return fe(n.required,0,e=>P(r,e))}function Gf(e,t,n,r,i,a){let o=[];return pe(i.required,0,e=>{let t=P(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function Kf(e,t,n,r){return N(n,`object`)?Pe(r):N(n,`array`)?Oe(r):N(n,`boolean`)?Ae(r):N(n,`integer`)?je(r):N(n,`number`)?Ne(r):N(n,`null`)?Me(r):N(n,`string`)?Ie(r):N(n,`bigint`)?ke(r):N(n,`constructor`)?Be(r):N(n,`function`)?ze(r):N(n,`symbol`)?Le(r):N(n,`undefined`)||N(n,`void`)?Re(r):it(!0)}function qf(e,t,n,r,i){return N(n,`object`)?A(i):N(n,`array`)?S(i):N(n,`boolean`)?w(i):N(n,`integer`)?D(i):N(n,`number`)?k(i):N(n,`null`)?O(i):N(n,`string`)?M(i):N(n,`bigint`)?C(i):N(n,`constructor`)?T(i):N(n,`function`)?E(i):N(n,`symbol`)?ee(i):N(n,`undefined`)?te(i):!N(n,`void`)||te(i)}function Jf(e,t,n,r){return dt(n.map(n=>Kf(e,t,n,r)))}function Yf(e,t,n,r,i){return n.some(n=>qf(e,t,n,r,i))}function Xf(e,t,n,r){return S(n.type)?Jf(e,t,n.type,r):Kf(e,t,n.type,r)}function Zf(e,t,n,r){return S(n.type)?Yf(e,t,n.type,n,r):qf(e,t,n.type,n,r)}function Qf(e,t,n,r,i,a){return(S(i.type)?Yf(e,t,i.type,i,a):qf(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function $f(e,t,n,r){let[i,a]=[Tu(),Tu()],o=tt(rt(`context`,`GetIndices`),[]),s=tt(rt(`indices`,`has`),[i]),c=yp(e,t,n.unevaluatedItems,a),l=tt(rt(`context`,`AddIndex`),[i]),u=Je(r,it(0),[a,i],Te(Ee(s,c),l));return tt(et([`context`],ot([st(`indices`,o),lt(u)])),[`context`])}function ep(e,t,n,r){let i=t.GetIndices();return fe(r,0,(r,a)=>(i.has(a)||xp(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function tp(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return pe(a,0,(a,c)=>{let l=new Su,u=(o.has(c)||Cp(e,l,n,r,i.unevaluatedItems,a))&&t.AddIndex(c);return u||s.push(c),u})||t.AddError({keyword:`unevaluatedItems`,schemaPath:n,instancePath:r,params:{unevaluatedItems:s}})}function np(e,t,n,r){let[i,a]=[Tu(),Tu()],o=tt(rt(`context`,`GetKeys`),[]),s=tt(rt(`keys`,`has`),[i]),c=tt(rt(`context`,`AddKey`),[i]),l=yp(e,t,n.unevaluatedProperties,a),u=Je(Ye(r),it(0),[`[${i}, ${a}]`,`_`],Ee(s,Te(l,c)));return tt(et([`context`],ot([st(`keys`,o),lt(u)])),[`context`])}function rp(e,t,n,r){let i=t.GetKeys();return fe(_e(r),0,([r,a])=>i.has(r)||xp(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function ip(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return pe(_e(a),0,([a,c])=>{let l=new Su,u=o.has(a)||Cp(e,l,n,r,i.unevaluatedProperties,c)&&t.AddKey(a);return u||s.push(a),u})||t.AddError({keyword:`unevaluatedProperties`,schemaPath:n,instancePath:r,params:{unevaluatedProperties:s}})}function ap(e){return!N(e.uniqueItems,!1)}function op(e,t,n,r){return ap(n)?Ve(rt(nt(`Set`,[tt(rt(r,`map`),[rt(`Hashing`,`Hash`)])]),`size`),rt(r,`length`)):it(!0)}function sp(e,t,n,r){if(!ap(n))return!0;let i=new Set(r.map(yr)).size,a=r.length;return N(i,a)}function cp(e,t,n,r,i,a){if(!ap(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=yr(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return N(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function lp(e,t){return hu(e)&&(S(e.type)&&ne(e.type.length,0)&&fe(e.type,0,e=>N(e,t))||N(e.type,t))}function up(e){return lp(e,`object`)}function dp(e){return xl(e)&&(Tl(e)||Ml(e)||Nl(e)||Pl(e)||cu(e)||ou(e)||lu(e)||tu(e)||Xl(e)||pu(e)||vu(e))}function fp(e){return lp(e,`array`)}function pp(e){return xl(e)&&(wl(e)||Wl(e)||Al(e)||ql(e)||Jl(e)||Ql(e)||$l(e)||su(e)||_u(e)||gu(e))}function mp(e){return lp(e,`string`)}function hp(e){return xl(e)&&(eu(e)||Yl(e)||Vl(e)||au(e))}function gp(e){return lp(e,`number`)||lp(e,`bigint`)}function _p(e){return xl(e)&&(Zl(e)||Kl(e)||zl(e)||Bl(e)||nu(e))}function vp(e,t,n,r){return t.UseUnevaluated()?Te(Te(t.Push(),yp(e,t,n,r)),t.Pop()):yp(e,t,n,r)}function yp(e,t,n,r){e.Push(n);let i=[];if(Sl(n))return kie(e,t,n,r);if(hu(n)&&i.push(Xf(e,t,n,r)),dp(n)){let a=[];pu(n)&&a.push(Uf(e,t,n,r)),Tl(n)&&a.push(gie(e,t,n,r)),Ml(n)&&a.push(Fie(e,t,n,r)),Nl(n)&&a.push(Rie(e,t,n,r)),Pl(n)&&a.push(Vie(e,t,n,r)),ou(n)&&a.push(bf(e,t,n,r)),cu(n)&&a.push(kf(e,t,n,r)),lu(n)&&a.push(Mf(e,t,n,r)),tu(n)&&a.push(ef(e,t,n,r)),Xl(n)&&a.push(Rd(e,t,n,r));let o=ut(a),s=Ee(De(Pe(r)),o);i.push(up(n)?o:s)}if(pp(n)){let a=[];wl(n)&&a.push(lie(e,t,n,r)),Al(n)&&a.push(Nie(e,t,n,r)),Wl(n)&&a.push(Sd(e,t,n,r)),ql(n)&&a.push(Ed(e,t,n,r)),Jl(n)&&a.push(Md(e,t,n,r)),Ql(n)&&a.push(Hd(e,t,n,r)),$l(n)&&a.push(Jd(e,t,n,r)),su(n)&&a.push(Cf(e,t,n,r)),gu(n)&&a.push(op(e,t,n,r));let o=ut(a),s=Ee(De(Oe(r)),o);i.push(fp(n)?o:s)}if(hp(n)){let a=[];Yl(n)&&a.push(Fd(e,t,n,r)),eu(n)&&a.push(Zd(e,t,n,r)),Vl(n)&&a.push(zae(e,t,n,r)),au(n)&&a.push(_f(e,t,n,r));let o=ut(a),s=Ee(De(Ie(r)),o);i.push(mp(n)?o:s)}if(_p(n)){let a=[];zl(n)&&a.push(Yie(e,t,n,r)),Bl(n)&&a.push(Zie(e,t,n,r)),Kl(n)&&a.push(kd(e,t,n,r)),Zl(n)&&a.push(Gd(e,t,n,r)),nu(n)&&a.push(rf(e,t,n,r));let o=ut(a),s=Ee(De(Ee(Ne(r),ke(r))),o);i.push(gp(n)?o:s)}fu(n)&&i.push(Bf(e,t,n,r)),du(n)&&i.push(Ff(e,t,n,r)),Il(n)&&i.push(Wie(e,t,n,r)),kl(n)&&i.push(jie(e,t,n,r)),Rl(n)&&i.push(qie(e,t,n,r)),Ul(n)&&i.push(Vae(e,t,n,r)),ru(n)&&i.push(lf(e,t,n,r)),El(n)&&i.push(xie(e,t,n,r)),Ol(n)&&i.push(Eie(e,t,n,r)),iu(n)&&i.push(mf(e,t,n,r)),_u(n)&&i.push(Ee(De(Oe(r)),$f(e,t,n,r))),vu(n)&&i.push(Ee(De(Fe(r)),np(e,t,n,r))),bl(n)&&i.push(aie(e,t,n,r));let a=ut(i);return e.Pop(n),a}function bp(e,t,n,r){return t.Push()&&xp(e,t,n,r)&&t.Pop()}function xp(e,t,n,r){e.Push(n);let i=Sl(n)?ku(e,t,n,r):(!hu(n)||Zf(e,t,n,r))&&(!(j(r)&&!S(r))||(!pu(n)||Wf(e,t,n,r))&&(!Tl(n)||_ie(e,t,n,r))&&(!Ml(n)||Iie(e,t,n,r))&&(!Nl(n)||zie(e,t,n,r))&&(!Pl(n)||Hie(e,t,n,r))&&(!ou(n)||xf(e,t,n,r))&&(!cu(n)||Af(e,t,n,r))&&(!lu(n)||Nf(e,t,n,r))&&(!tu(n)||tf(e,t,n,r))&&(!Xl(n)||zd(e,t,n,r)))&&(!S(r)||(!wl(n)||uie(e,t,n,r))&&(!Al(n)||Mu(e,t,n,r))&&(!Wl(n)||Cd(e,t,n,r))&&(!ql(n)||Dd(e,t,n,r))&&(!Jl(n)||Nd(e,t,n,r))&&(!Ql(n)||Ud(e,t,n,r))&&(!$l(n)||Yd(e,t,n,r))&&(!su(n)||wf(e,t,n,r))&&(!gu(n)||sp(e,t,n,r)))&&(!M(r)||(!Yl(n)||Id(e,t,n,r))&&(!eu(n)||Qd(e,t,n,r))&&(!Vl(n)||vd(e,t,n,r))&&(!au(n)||vf(e,t,n,r)))&&(!(k(r)||C(r))||(!zl(n)||Pu(e,t,n,r))&&(!Bl(n)||Fu(e,t,n,r))&&(!Kl(n)||Ad(e,t,n,r))&&(!Zl(n)||Kd(e,t,n,r))&&(!nu(n)||af(e,t,n,r)))&&(!fu(n)||Vf(e,t,n,r))&&(!du(n)||If(e,t,n,r))&&(!Il(n)||Gie(e,t,n,r))&&(!kl(n)||Au(e,t,n,r))&&(!Rl(n)||Nu(e,t,n,r))&&(!Ul(n)||Hae(e,t,n,r))&&(!ru(n)||uf(e,t,n,r))&&(!El(n)||Sie(e,t,n,r))&&(!Ol(n)||Die(e,t,n,r))&&(!iu(n)||hf(e,t,n,r))&&(!_u(n)||!S(r)||ep(e,t,n,r))&&(!vu(n)||!j(r)||rp(e,t,n,r))&&(!bl(n)||oie(e,t,n,r));return e.Pop(n),i}function Sp(e,t,n,r,i,a){return t.Push()&&Cp(e,t,n,r,i,a)&&t.Pop()}function Cp(e,t,n,r,i,a){e.Push(i);let o=Sl(i)?Aie(e,t,n,r,i,a):!!(+(!hu(i)||Qf(e,t,n,r,i,a))&(!(j(a)&&!S(a))||!!(+(!pu(i)||Gf(e,t,n,r,i,a))&(!Tl(i)||vie(e,t,n,r,i,a))&(!Ml(i)||Lie(e,t,n,r,i,a))&(!Nl(i)||Bie(e,t,n,r,i,a))&(!Pl(i)||Uie(e,t,n,r,i,a))&(!ou(i)||Sf(e,t,n,r,i,a))&(!cu(i)||jf(e,t,n,r,i,a))&(!lu(i)||Pf(e,t,n,r,i,a))&(!tu(i)||nf(e,t,n,r,i,a))&(!Xl(i)||Bd(e,t,n,r,i,a))))&(!S(a)||!!(+(!wl(i)||die(e,t,n,r,i,a))&(!Al(i)||Pie(e,t,n,r,i,a))&(!Wl(i)||wd(e,t,n,r,i,a))&(!ql(i)||Od(e,t,n,r,i,a))&(!Jl(i)||Pd(e,t,n,r,i,a))&(!Ql(i)||Wd(e,t,n,r,i,a))&(!$l(i)||Xd(e,t,n,r,i,a))&(!su(i)||Tf(e,t,n,r,i,a))&(!gu(i)||cp(e,t,n,r,i,a))))&(!M(a)||!!(+(!Yl(i)||Ld(e,t,n,r,i,a))&(!eu(i)||$d(e,t,n,r,i,a))&(!Vl(i)||Bae(e,t,n,r,i,a))&(!au(i)||yf(e,t,n,r,i,a))))&(!(k(a)||C(a))||!!(+(!zl(i)||Xie(e,t,n,r,i,a))&(!Bl(i)||Qie(e,t,n,r,i,a))&(!Kl(i)||jd(e,t,n,r,i,a))&(!Zl(i)||qd(e,t,n,r,i,a))&(!nu(i)||of(e,t,n,r,i,a))))&(!fu(i)||Hf(e,t,n,r,i,a))&(!du(i)||Lf(e,t,n,r,i,a))&(!Il(i)||Kie(e,t,n,r,i,a))&(!kl(i)||Mie(e,t,n,r,i,a))&(!Rl(i)||Jie(e,t,n,r,i,a))&(!Ul(i)||Uae(e,t,n,r,i,a))&(!ru(i)||df(e,t,n,r,i,a))&(!El(i)||Cie(e,t,n,r,i,a))&(!Ol(i)||Oie(e,t,n,r,i,a))&(!iu(i)||gf(e,t,n,r,i,a))&(!_u(i)||!S(a)||tp(e,t,n,r,i,a))&(!vu(i)||!j(a)||ip(e,t,n,r,i,a)))&&(!bl(i)||sie(e,t,n,r,i,a));return e.Pop(i),o}const wp=[0],Tp=new Map,Ep=new Map;function Dp(){return yr(wp[0]++)}function Op(e,t){Tp.has(e)||Tp.set(e,new Map);let n=Tp.get(e);if(n.has(t))return n.get(t);let r=Dp();return n.set(t,r),r}function kp(e,t,n,r){return e.UseUnevaluated()?tt(`check_${n}`,[`context`,r]):tt(`check_${n}`,[r])}function Ap(e,t,n,r){let i=yp(e,t,n,`value`);return t.UseUnevaluated()?st(`check_${r}`,et([`context`,`value`],i)):st(`check_${r}`,et([`value`],i))}function jp(){wp[0]=0,Tp.clear(),Ep.clear()}function Mp(){return[...Ep.values()]}function Np(e,t,n,r){let i=Op(n,e.BaseURL().href),a=kp(t,n,i,r);return Ep.has(i)?a:(Ep.set(i,``),Ep.set(i,Ap(e,t,n,i)),a)}function Pp(e,t){return j(t)&&!he(e)?t[e]:void 0}function Fp(e,t){return e.reduce((e,t)=>Pp(t,e),t)}function Ip(e){if(N(e.length,0))return[];let t=e.split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`));return t.length>0&&t[0]===``?t.slice(1):t}function Lp(e,t){return Fp(Ip(t),e)}function Rp(e,t,n){if(e.$id===n.hash)return e;let r=new URL(e.$id,t.href),i=new URL(n.href,t.href);if(N(r.pathname,i.pathname))return n.hash.startsWith(`#`)?Vp(e,t,n):e}function zp(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return N(r.href,i.href)?e:void 0}function Bp(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return N(r.href,i.href)?e:void 0}function Vp(e,t,n){if(n.href.endsWith(`#`))return e;if(!n.hash.startsWith(`#`))return;let r=decodeURIComponent(n.hash.slice(1));if(r.startsWith(`/`))return Lp(e,r)}function Hp(e,t,n){if(Hl(e)){let r=Rp(e,t,n);if(!te(r))return r}if(Dl(e)){let r=zp(e,t,n);if(!te(r))return r}if(Fl(e)){let r=Bp(e,t,n);if(!te(r))return r}return Vp(e,t,n)}function Up(e,t,n){return e.reduce((e,r)=>{let i=Gp(r,t,n);return te(i)?e:i},void 0)}function Wp(e,t,n){return F(e).reduce((r,i)=>{let a=Gp(e[i],t,n);return te(a)?r:a},void 0)}function Gp(e,t,n){let r=xl(e)&&Hl(e)?new URL(e.$id,t.href):t;if(xl(e)){let t=Hp(e,r,n);if(!te(t))return t}if(S(e))return Up(e,r,n);if(j(e))return Wp(e,r,n)}function Kp(e,t){let n=new URL(`http://unknown/`),r=Hl(e)?new URL(e.$id,n.href):n;return Gp(e,r,new URL(t,r.href))}function qp(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?Kp(t,n.$dynamicRef):Kp(e,n.$dynamicRef);if(!te(i))return!xl(i)||!Fl(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var Jp=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Yp,Xp,Zp,Qp,$p,em=class{constructor(e,t){Yp.add(this),this.context=e,this.schema=t,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((e,t)=>new URL(t.$id,e),new URL(`http://unknown`))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(e){xl(e)&&(Hl(e)&&(this.ids.push(e),Jp(this,Yp,`m`,Xp).call(this,e)),Dl(e)&&this.anchors.push(e),uu(e)&&this.recursiveAnchors.push(e),Fl(e)&&this.dynamicAnchors.push(e))}Pop(e){xl(e)&&(Hl(e)&&(this.ids.pop(),Jp(this,Yp,`m`,Zp).call(this,e)),Dl(e)&&this.anchors.pop(),uu(e)&&this.recursiveAnchors.pop(),Fl(e)&&this.dynamicAnchors.pop())}Ref(e){return Jp(this,Yp,`m`,Qp).call(this,e)??Jp(this,Yp,`m`,$p).call(this,e)}RecursiveRef(e){return uu(this.Base())?Kp(this.recursiveAnchors[0],e.$recursiveRef):Kp(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return qp(t,this.Base(),e,this.dynamicAnchors)}};Yp=new WeakSet,Xp=function e(t,n=!0){if(!xl(t))return;let r=t;if(n||!Hl(r)){!n&&Fl(r)&&this.dynamicAnchors.push(r);for(let t of F(r))Jp(this,Yp,`m`,e).call(this,r[t],!1)}},Zp=function e(t,n=!0){if(!xl(t))return;let r=t;if(n||!Hl(r)){!n&&Fl(r)&&this.dynamicAnchors.pop();for(let t of F(r))Jp(this,Yp,`m`,e).call(this,r[t],!1)}},Qp=function(e){return P(this.context,e.$ref)?this.context[e.$ref]:void 0},$p=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?Kp(this.Base(),e.$ref):Kp(t,e.$ref)};function tm(e){return`${e.Functions().join(`; +`)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function nm(e,t){return Hn(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(bu,x,Rae,Wn,e.External().variables)}function rm(e){let t=new em(e.Context(),e.Schema()),n=new bu;return r=>xp(t,n,e.Schema(),r)}function im(e,t){return Vn()?nm(e,t):rm(e)}var am=class{constructor(e,t,n){this.isAccelerated=e,this.code=t,this.check=n}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}},om=class{constructor(e,t,n,r,i,a){this.context=e,this.schema=t,this.external=n,this.functions=r,this.entry=i,this.useUnevaluated=a}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=tm(this),t=im(this,e);return new am(Vn(),e,t)}};function sm(...e){let[t,n]=An(e,{2:(e,t)=>[e,t],1:e=>[{},e]});rie(),jp();let r=new em(t,n),i=new nie(tie(t,n)),a=Np(r,i,n,`value`),o=Mp();return new om(t,n,iie(),o,a,i.UseUnevaluated())}function cm(...e){let[t,n,r]=An(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=It(),a=Sr(),o=[];return[Cp(new em(t,n),new xu(e=>{if(!ae(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function lm(...e){let[t,n,r]=An(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return xp(new em(t,n),new bu,n,r)}function um(...e){let[t,n,r]=An(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return lm(t,n,r)}function dm(...e){let[t,n,r]=An(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=cm(t,n,r);return a}var fm=class extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"cause",{value:{source:e,errors:n,value:t},writable:!1,configurable:!1,enumerable:!1})}};function pm(e,t,n){return S(n)?n.map(n=>ym(e,t.items,n)):n}function mm(e,t,n){return ym({...e,...t.$defs},cn(t.$ref),n)}function hm(e,t){let n=P(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=pl(cl(e,t));return Cn(r)?Jc(r,n):r}function gm(e,t,n){return ym(e,hm(e,t),n)}function _m(e){return P(e,`additionalProperties`)?e.additionalProperties:void 0}function qae(e,t,n){if(!j(n)||S(n))return n;let r=_m(t);for(let i of F(n)){if(P(t.properties,i)){n[i]=ym(e,t.properties[i],n[i]);continue}if(w(r)&&N(r,!0)||Ut(r)&&um(e,r,n[i])){n[i]=ym(e,r,n[i]);continue}delete n[i]}return n}function Jae(e,t,n){if(!j(n))return n;let r=_m(t),[i,a]=[new RegExp(Da(t)),ka(t)];for(let t of F(n)){if(i.test(t)){n[t]=ym(e,a,n[t]);continue}if(w(r)&&N(r,!0)||Ut(r)&&um(e,r,n[t])){n[t]=ym(e,r,n[t]);continue}delete n[t]}return n}function Yae(e,t,n){return P(e,t.$ref)?ym(e,e[t.$ref],n):n}function Xae(e,t,n){if(!S(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;ixm(e))}function xm(e){return Qae(e,$t(e)?Qt(xm(e.items),en(e)):Ln(e)?In(bm(e.allOf)):Qr(e)?Zr(eoe(e.anyOf)):Cn(e)?Sn($ae(e.properties)):Aa(e)?wa(Oa(e),xm(ka(e))):xi(e)?bi(bm(e.items)):e)}function Sm(e){return xm(e)}function Cm(...e){let[t,n,r]=An(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return ym(t,It().unionPrioritySort?Sm(n):n,r)}function wm(e){return j(e)&&P(e,`value`)}function Tm(e){return{value:e}}function toe(e){return S(e)?Tm(e):Tm([e])}function noe(e){return N(e,!0)?Tm(BigInt(1)):Tm(BigInt(0))}const roe=/^-?(0|[1-9]\d*)n$/,ioe=/^-?(0|[1-9]\d*)\.\d+$/,aoe=/^-?(0|[1-9]\d*)$/;function ooe(e){return roe.test(e)}function soe(e){return ioe.test(e)}function coe(e){return aoe.test(e)}function loe(e){let t=e.toLowerCase();return ooe(e)?Tm(BigInt(e.slice(0,e.length-1))):soe(e)?Tm(BigInt(e.split(`.`)[0])):coe(e)?Tm(BigInt(e)):N(t,`false`)?Tm(BigInt(0)):N(t,`true`)?Tm(BigInt(1)):void 0}function Em(e){return C(e)?Tm(e):w(e)?noe(e):k(e)?Tm(BigInt(Math.trunc(e))):O(e)?Tm(BigInt(0)):M(e)?loe(e):te(e)?Tm(BigInt(0)):void 0}function uoe(e){return N(e,BigInt(0))?Tm(!1):N(e,BigInt(1))?Tm(!0):void 0}function doe(e){return N(e,0)?Tm(!1):N(e,1)?Tm(!0):void 0}function foe(e){return N(e.toLowerCase(),`false`)?Tm(!1):N(e.toLowerCase(),`true`)?Tm(!0):N(e,`0`)?Tm(!1):N(e,`1`)?Tm(!0):void 0}function Dm(e){return C(e)?uoe(e):w(e)?Tm(e):k(e)?doe(e):O(e)?Tm(!1):M(e)?foe(e):te(e)?Tm(!1):void 0}function poe(e){return N(e,BigInt(0))?Tm(null):void 0}function moe(e){return N(e,!1)?Tm(null):void 0}function hoe(e){return N(e,0)?Tm(null):void 0}function goe(e){let t=e.toLowerCase();return N(t,`undefined`)||N(t,`null`)||N(e,``)||N(e,`0`)?Tm(null):void 0}function _oe(e){return C(e)?poe(e):w(e)?moe(e):k(e)?hoe(e):O(e)?Tm(null):M(e)?goe(e):te(e)?Tm(null):void 0}const Om=BigInt(2**53-1),km=BigInt(-(2**53-1));function voe(e){return e<=Om&&e>=km?Tm(Number(e)):void 0}function yoe(e){return Tm(+!!e)}function boe(e){let t=+e;if(k(t))return Tm(t);let n=e.toLowerCase();if(N(n,`false`))return Tm(0);if(N(n,`true`))return Tm(1);let r=Em(e);if(wm(r))return r.value<=Om&&r.value>=km?Tm(Number(r.value)):void 0}function Am(e){return C(e)?voe(e):w(e)?yoe(e):k(e)?Tm(e):O(e)?Tm(0):M(e)?boe(e):te(e)?Tm(0):void 0}function jm(e){return C(e)||w(e)||k(e)?Tm(e.toString()):O(e)?Tm(`null`):M(e)?Tm(e):te(e)?Tm(``):void 0}function xoe(e){return N(e,BigInt(0))?Tm(void 0):void 0}function Soe(e){return N(e,!1)?Tm(void 0):void 0}function Coe(e){return N(e,0)?Tm(void 0):void 0}function woe(e){let t=e.toLowerCase();return N(t,`undefined`)||N(t,`null`)||N(e,``)||N(e,`0`)?Tm(void 0):void 0}function Mm(e){return C(e)?xoe(e):w(e)?Soe(e):k(e)?Coe(e):O(e)?Tm(void 0):M(e)?woe(e):te(e)?Tm(e):void 0}function Toe(e,t,n){return toe(n).value.map(n=>Fm(e,t.items,n))}function Eoe(e,t,n){let r=Em(n);return wm(r)?r.value:n}function Doe(e,t,n){let r=Dm(n);return wm(r)?r.value:n}function Ooe(e,t,n){return Fm({...e,...t.$defs},cn(t.$ref),n)}function koe(e,t,n){return Fm(e,pl(t),n)}function Aoe(e,t,n){let r=Am(n);return wm(r)?Math.trunc(r.value):n}function joe(e,t,n){return Fm(e,pl(cl(e,t)),n)}function Moe(e,t,n){let r=Em(n);return wm(r)&&N(t.const,r.value)?r.value:n}function Noe(e,t,n){let r=Dm(n);return wm(r)&&N(t.const,r.value)?r.value:n}function Poe(e,t,n){let r=Am(n);return wm(r)&&N(t.const,r.value)?r.value:n}function Foe(e,t,n){let r=jm(n);return wm(r)&&N(t.const,r.value)?r.value:n}function Ioe(e,t,n){return N(t.const,n)?n:Lr(t)?Moe(e,t,n):Rr(t)?Noe(e,t,n):zr(t)?Poe(e,t,n):Br(t)?Foe(e,t,n):Un()}function Loe(e,t,n){let r=_oe(n);return wm(r)?r.value:n}function Roe(e,t,n){let r=Am(n);return wm(r)?r.value:n}function Nm(e,t,n,r){let i=F(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=Fm(e,n,r[t]));return r}function Pm(e,t,n){return vn(e)&&te(n[t])}function zoe(e,t,n){let r=ge(t.properties),i=F(n);for(let[t,a]of r)for(let r of i)t.test(r)&&!Pm(a,r,n)&&(n[r]=Fm(e,a,n[r]));return P(t,`additionalProperties`)&&j(t.additionalProperties)?Nm(e,r,t.additionalProperties,n):n}function Boe(e,t,n){return A(n)?zoe(e,t,n):n}function Voe(e,t,n){let r=ge(t.patternProperties),i=F(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=Fm(e,a,n[r]));return P(t,`additionalProperties`)&&j(t.additionalProperties)?Nm(e,r,t.additionalProperties,n):n}function Hoe(e,t,n){return A(n)?Voe(e,t,n):n}function Uoe(e,t,n){return P(e,t.$ref)?Fm(e,e[t.$ref],n):n}function Woe(e,t,n){let r=jm(n);return wm(r)?r.value:n}function Goe(e,t,n){return Fm(e,pl(t),n)}function Koe(e,t,n){if(!S(n))return n;for(let r=0;rum(e,t,n)))return n;let r=t.anyOf.map(t=>Fm(e,t,vm(n))).find(n=>um(e,t,n));return te(r)?n:r}function Yoe(e,t,n){return wm(Mm(n))?void 0:n}function Fm(e,t,n){return $t(t)?Toe(e,t,n):Or(t)?Eoe(e,t,n):kr(t)?Doe(e,t,n):On(t)?Ooe(e,t,n):Fn(t)?koe(e,t,n):Mr(t)?Aoe(e,t,n):Ln(t)?joe(e,t,n):Vr(t)?Ioe(e,t,n):Ur(t)?Loe(e,t,n):Kr(t)?Roe(e,t,n):Cn(t)?Boe(e,t,n):Aa(t)?Hoe(e,t,n):ln(t)?Uoe(e,t,n):Xr(t)?Woe(e,t,n):Ho(t)?Goe(e,t,n):xi(t)?Koe(e,t,n):Fa(t)?qoe(e,t,n):Qr(t)?Joe(e,t,n):Ia(t)?Yoe(e,t,n):n}function Im(...e){let[t,n,r]=An(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Fm(t,n,r)}function Xoe(e,t,n){if(!S(n))return n;for(let r=0;r[e,t,n],2:(e,t)=>[{},e,t]});return Lm(t,n,r)}function zm(e){return(...t)=>{let[n,r,i]=An(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function ase(e,t,n){return t[`~codec`].decode(n)}function ose(e,t,n){return t[`~codec`].encode(n)}function Bm(e,t,n,r){return Cr(n)?N(e,`Decode`)?ase(t,n,r):ose(t,n,r):r}function sse(e,t,n,r){if(!S(r))return r;for(let i=0;i({...e,...t}),{})}function Hm(e,t){for(let n of t)if(!Se(e,n))return n;return e}function dse(e,t,n,r){if(N(n.allOf.length,0))return Bm(e,t,n,r);let i=n.allOf.map(n=>Wm(e,t,n,Cm(n,vm(r))));return Bm(e,t,n,i.every(e=>j(e))?Vm(i):Hm(r,i))}function fse(e,t,n,r){if(N(n.allOf.length,0))return Bm(e,t,n,r);let i=Bm(e,t,n,r),a=n.allOf.map(n=>Wm(e,t,n,Cm(n,vm(i))));return a.every(e=>j(e))?Vm(a):Hm(i,a)}function pse(e,t,n,r){return N(e,`Decode`)?dse(e,t,n,r):fse(e,t,n,r)}function mse(e,t,n,r){if(!A(r))return r;for(let i of F(n.properties))P(r,i)&&!Pm(n.properties[i],i,r)&&(r[i]=Wm(e,t,n.properties[i],r[i]));return Bm(e,t,n,r)}function hse(e,t,n,r){let i=Bm(e,t,n,r);if(!A(i))return i;for(let r of F(n.properties))P(i,r)&&!Pm(n.properties[r],r,i)&&(i[r]=Wm(e,t,n.properties[r],i[r]));return i}function gse(e,t,n,r){return N(e,`Decode`)?mse(e,t,n,r):hse(e,t,n,r)}function _se(e,t,n,r){if(!A(r))return r;let i=new RegExp(Da(n));for(let a of F(r))i.test(a)&&(r[a]=Wm(e,t,ka(n),r[a]));return Bm(e,t,n,r)}function vse(e,t,n,r){let i=Bm(e,t,n,r);if(!A(i))return i;let a=new RegExp(Da(n));for(let r of F(i))a.test(r)&&(i[r]=Wm(e,t,ka(n),i[r]));return i}function yse(e,t,n,r){return N(e,`Decode`)?_se(e,t,n,r):vse(e,t,n,r)}function Um(e,t,n,r){return P(t,n.$ref)?Wm(e,t,t[n.$ref],r):r}function bse(e,t,n,r){return N(e,`Decode`)?Bm(e,t,n,Um(e,t,n,r)):Um(e,t,n,Bm(e,t,n,r))}function xse(e,t,n,r){if(!S(r))return r;for(let i=0;ivm(n),(e,t,n)=>Rm(e,t,n),(e,t,n)=>Im(e,t,n),(e,t,n)=>Cm(e,t,n),(e,t,n)=>Ose(e,t,n),(e,t,n)=>kse(e,t,n)]);function jse(...e){let[t,n,r]=An(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Ase(t,n,r)}var Mse=class extends fm{constructor(e,t){super(`Encode`,e,t)}};function Nse(e,t,n){if(!um(e,t,n))throw new Mse(n,dm(e,t,n));return n}function Pse(e,t,n){return Wm(`Encode`,e,It().unionPrioritySort?Sm(t):t,n)}const Fse=zm([(e,t,n)=>vm(n),(e,t,n)=>Pse(e,t,n),(e,t,n)=>Rm(e,t,n),(e,t,n)=>Im(e,t,n),(e,t,n)=>Cm(e,t,n),(e,t,n)=>Nse(e,t,n)]);function Ise(...e){let[t,n,r]=An(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Fse(t,n,r)}function Lse(e,t){return Cr(t)||Km(e,t.items)}function Rse(e,t){return Cr(t)||Gm({...e,...t.$defs},cn(t.$ref))}function zse(e,t){return Cr(t)||t.allOf.some(t=>Km(e,t))}function Bse(e,t){return Cr(t)||F(t.properties).some(n=>Km(e,t.properties[n]))}function Vse(e,t){return Cr(t)||Km(e,ka(t))}function Gm(e,t){return!qm.has(t.$ref)&&(qm.add(t.$ref),Cr(t)||P(e,t.$ref)&&Km(e,e[t.$ref]))}function Hse(e,t){return Cr(t)||t.items.some(t=>Km(e,t))}function Use(e,t){return Cr(t)||t.anyOf.some(t=>Km(e,t))}function Km(e,t){return $t(t)?Lse(e,t):On(t)?Rse(e,t):Ln(t)?zse(e,t):Cn(t)?Bse(e,t):Aa(t)?Vse(e,t):ln(t)?Gm(e,t):xi(t)?Hse(e,t):Qr(t)?Use(e,t):Cr(t)}const qm=new Set;function Wse(...e){let[t,n]=An(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return qm.clear(),Km(t,n)}var Jm=class extends Error{constructor(e,t){super(t),this.type=e}};function Gse(e,t){return E(t.default)?t.default(t):j(t.default)?vm(t.default):t.default}function Kse(e,t){if(gu(t)&&!jl(t))throw new Jm(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=$l(t)?t.minItems:0;return Array.from({length:n},()=>Ym(e,t.items))}function qse(e,t){return Bl(t)?BigInt(t.exclusiveMinimum)+BigInt(1):Zl(t)?BigInt(t.minimum):BigInt(0)}function Jse(e,t){return!1}function Yse(e,t){let n=Ym(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function Xse(e,t){return Ym({...e,...t.$defs},cn(t.$ref))}function Zse(e,t){return Ym(e,pl(t))}function Qse(e,t){let n=Ym(e,t.returnType);return()=>n}function $se(e,t){return Bl(t)&&k(t.exclusiveMinimum)?t.exclusiveMinimum+1:Zl(t)?t.minimum:0}function ece(e,t){return Ym(e,pl(cl(e,t)))}function tce(e,t){return t.const}function nce(e,t){throw new Jm(t,`Cannot create TNever types`)}function rce(e,t){return null}function ice(e,t){return Bl(t)&&k(t.exclusiveMinimum)?t.exclusiveMinimum+1:Zl(t)?t.minimum:0}function ace(e,t){return(te(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:Ym(e,t.properties[r])}),{})}function oce(e,t){if(tu(t)&&!jl(t))throw new Jm(t,`Record with the minProperties constraint must have a default annotation`);return{}}function sce(e,t){return P(e,t.$ref)?Ym(e,e[t.$ref]):(()=>{throw new Jm(t,`Unable to deref Ref`)})()}function cce(e,t){if((au(t)||Vl(t))&&!jl(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=eu(t)?t.minLength:0;return``.padEnd(n)}function lce(e,t){return Symbol()}function uce(e,t){let n=gi(t.pattern);if(Xr(n))throw new Jm(t,`Unable to create TemplateLiteral due to infinite type expansion`);return Ym(e,n)}function dce(e,t){return Array.from({length:t.minItems},(n,r)=>Ym(e,t.items[r]))}function fce(e,t){if(N(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return Ym(e,t.anyOf[0])}function Ym(e,t){return jl(t)?Gse(e,t):$t(t)?Kse(e,t):Or(t)?qse(e,t):kr(t)?Jse(e,t):nn(t)?Yse(e,t):On(t)?Xse(e,t):Fn(t)?Zse(e,t):on(t)?Qse(e,t):Mr(t)?$se(e,t):Ln(t)?ece(e,t):Vr(t)?tce(e,t):hn(t)?nce(e,t):Ur(t)?rce(e,t):Kr(t)?ice(e,t):Cn(t)?ace(e,t):Aa(t)?oce(e,t):ln(t)?sce(e,t):Xr(t)?cce(e,t):Jr(t)?lce(e,t):Ho(t)?uce(e,t):xi(t)?dce(e,t):Fa(t)?void 0:Qr(t)?fce(e,t):(Ia(t),void 0)}function pce(...e){let[t,n]=An(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Ym(t,n)}var Xm=class extends fm{constructor(e,t){super(`Parse`,e,t)}};function mce(e,t,n){if(!um(e,t,n))throw new Xm(n,dm(e,t,n));return n}const hce=zm([(e,t,n)=>vm(n),(e,t,n)=>Rm(e,t,n),(e,t,n)=>Im(e,t,n),(e,t,n)=>Cm(e,t,n),(e,t,n)=>mce(e,t,n)]);Zr([Sn({type:Fr(`insert`),path:Yr(),value:Tn()}),Object({type:Fr(`update`),path:Yr(),value:Tn()}),Sn({type:Fr(`delete`),path:Yr()})]);var gce=class{constructor(e,t){this.hasCodec=Wse(e,t),this.buildResult=sm(e,t),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(It().correctiveParse)return hce(this.Context(),this.Type(),e);throw new Xm(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:dm(this.Context(),this.Type(),e)}Clean(e){return Cm(this.Context(),this.Type(),e)}Convert(e){return Im(this.Context(),this.Type(),e)}Create(){return pce(this.Context(),this.Type())}Default(e){return Rm(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?jse(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Ise(this.Context(),this.Type(),e):this.Parse(e)}};function _ce(...e){let[t,n]=An(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new gce(t,n)}const Zm=new WeakMap,vce=Symbol.for(`TypeBox.Kind`);function yce(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function bce(e,t){switch(t){case`number`:return typeof e==`number`;case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`string`:return typeof e==`string`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!1}}function Qm(e){try{return nh(e)}catch{return}}function xce(e,t){switch(t){case`number`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return typeof e==`boolean`?+!!e:e;case`integer`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isInteger(t))return t}return typeof e==`boolean`?+!!e:e;case`boolean`:if(e===null)return!1;if(typeof e==`string`){if(e===`true`)return!0;if(e===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return e;case`string`:return e===null?``:typeof e==`number`||typeof e==`boolean`?String(e):e;case`null`:return e===``||e===0||e===!1?null:e;default:return e}}function Sce(e,t){let n=t.properties,r=new Set(n?Object.keys(n):[]);if(n)for(let[t,r]of Object.entries(n))t in e&&(e[t]=eh(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=eh(i,t.additionalProperties))}function Cce(e,t){if(Array.isArray(t.items)){for(let n=0;n1&&r.some(e=>bce(n,e));if(r.length>0&&!i)for(let e of r){let t=xce(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&Sce(n,t),r.includes(`array`)&&Array.isArray(n)&&Cce(n,t),n}function th(e,t){if(Array.isArray(e)){if(Array.isArray(t.items))for(let n=0;n` - ${wce(e)}: ${e.message}`).join(` +`)||`Unknown validation error`,a=`Validation failed for tool "${t.name}":\n${i}\n\nReceived arguments:\n${JSON.stringify(t.arguments,null,2)}`;throw Error(a)}function Ece(e,t){try{return Promise.resolve(t(rh))}catch(e){return Promise.reject(e)}}const rh={startSpan:Ece,addEvent:()=>{},setAttributes:()=>{},setStatus:()=>{}};Object.freeze(rh);function ih(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function Dce(e,t,n,r,i,a){let o=[...e],s={...t,messages:[...t.messages,...e]};await r({type:`agent_start`}),await r({type:`turn_start`});for(let t of e)await r({type:`message_start`,message:t}),await r({type:`message_end`,message:t});return await ah(s,o,n,i,r,a??ih()),o}async function Oce(e,t,n,r,i){if(e.messages.length===0)throw Error(`Cannot continue: no messages in context`);if(e.messages[e.messages.length-1].role===`assistant`)throw Error(`Cannot continue from message role: assistant`);let a=[],o={...e};return await n({type:`agent_start`}),await n({type:`turn_start`}),await ah(o,a,t,r,n,i??ih()),a}async function ah(e,t,n,r,i,a){let o=e,s=n,c,l=await s.getSteeringMessages?.()||[];for(;;){let e=!0;for(;e||l.length>0;){if(c){let e=await s.prepareNextTurn?.(c);e&&(o=e.context??o,s={...s,model:e.model??s.model,reasoning:e.thinkingLevel===void 0?s.reasoning:e.thinkingLevel===`off`?void 0:e.thinkingLevel}),l.length===0&&(l=await s.getSteeringMessages?.()||[]),await i({type:`turn_start`})}if(l.length>0){for(let e of l)await i({type:`message_start`,message:e}),await i({type:`message_end`,message:e}),o.messages.push(e),t.push(e);l=[]}let n=await kce(o,s,r,i,a);if(t.push(n),n.stopReason===`error`||n.stopReason===`aborted`){await i({type:`turn_end`,message:n,toolResults:[]}),await i({type:`agent_end`,messages:t});return}let u=n.content.filter(e=>e.type===`toolCall`),d=[];if(e=!1,u.length>0){let a=n.stopReason===`length`?await Ace(u,i):await jce(o,n,s,r,i);d.push(...a.messages),e=!a.terminate;for(let e of d)o.messages.push(e),t.push(e)}if(await i({type:`turn_end`,message:n,toolResults:d}),c={message:n,toolResults:d,context:o,newMessages:t},await s.shouldStopAfterTurn?.(c)){await i({type:`agent_end`,messages:t});return}l=await s.getSteeringMessages?.()||[]}let n=await s.getFollowUpMessages?.()||[];if(n.length>0){l=n;continue}break}await i({type:`agent_end`,messages:t})}async function kce(e,t,n,r,i){let a=e.messages;t.transformContext&&(a=await t.transformContext(a,n));let o=await t.convertToLlm(a),s={systemPrompt:e.systemPrompt,messages:o,tools:e.tools},c=(t.getApiKey?await t.getApiKey(t.model.provider):void 0)||t.apiKey,l=await i(t.model,s,{...t,apiKey:c,signal:n}),u=null,d=!1;for await(let t of l)switch(t.type){case`start`:u=t.partial,e.messages.push(u),d=!0,await r({type:`message_start`,message:{...u}});break;case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:u&&(u=t.partial,e.messages[e.messages.length-1]=u,await r({type:`message_update`,assistantMessageEvent:t,message:{...u}}));break;case`done`:case`error`:{let t=await l.result();return d?e.messages[e.messages.length-1]=t:e.messages.push(t),d||await r({type:`message_start`,message:{...t}}),await r({type:`message_end`,message:t}),t}}let f=await l.result();return d?e.messages[e.messages.length-1]=f:(e.messages.push(f),await r({type:`message_start`,message:{...f}})),await r({type:`message_end`,message:f}),f}async function Ace(e,t){let n=[];for(let r of e){await t({type:`tool_execution_start`,toolCallId:r.id,toolName:r.name,args:r.arguments});let e={toolCall:r,result:uh(`Tool call "${r.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await dh(e,t);let i=fh(e);await ph(i,t),n.push(i)}return{messages:n,terminate:!1}}async function jce(e,t,n,r,i){let a=t.content.filter(e=>e.type===`toolCall`),o=a.some(t=>e.tools?.find(e=>e.name===t.name)?.executionMode===`sequential`);return n.toolExecution===`sequential`||o?Mce(e,t,a,n,r,i):Nce(e,t,a,n,r,i)}async function Mce(e,t,n,r,i,a){let o=[],s=[];for(let c of n){await a({type:`tool_execution_start`,toolCallId:c.id,toolName:c.name,args:c.arguments});let n=await sh(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await lh(e,t,n,await ch(n,i,a),r,i),await dh(l,a);let u=fh(l);if(await ph(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:oh(o)}}async function Nce(e,t,n,r,i,a){let o=[];for(let s of n){await a({type:`tool_execution_start`,toolCallId:s.id,toolName:s.name,args:s.arguments});let n=await sh(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await dh(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{if(i?.aborted){let e={toolCall:s,result:uh(`Operation aborted`),isError:!0};return await dh(e,a),e}let o=await ch(n,i,a),c=await lh(e,t,n,o,r,i);return await dh(c,a),c}),i?.aborted)break}let s=await Promise.all(o.map(e=>typeof e==`function`?e():Promise.resolve(e))),c=[];for(let e of s){let t=fh(e);await ph(t,a),c.push(t)}return{messages:c,terminate:oh(s)}}function oh(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function Pce(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function sh(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:uh(`Tool ${n.name} not found`),isError:!0};try{let o=Tce(a,Pce(a,n));if(r.beforeToolCall){let a=await r.beforeToolCall({assistantMessage:t,toolCall:n,args:o,context:e},i);if(i?.aborted)return{kind:`immediate`,result:uh(`Operation aborted`),isError:!0};if(a?.block){let e=uh(a.reason||`Tool execution was blocked`);return a.terminate===!0&&(e.terminate=!0),{kind:`immediate`,result:e,isError:!0}}}return i?.aborted?{kind:`immediate`,result:uh(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:uh(e instanceof Error?e.message:String(e)),isError:!0}}}async function ch(e,t,n){let r=[],i=!0;try{let a=await e.tool.execute(e.toolCall.id,e.args,t,t=>{i&&r.push(Promise.resolve(n({type:`tool_execution_update`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,args:e.toolCall.arguments,partialResult:t})))});return i=!1,await Promise.all(r),{result:a,isError:!1}}catch(e){return i=!1,await Promise.all(r),{result:uh(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function lh(e,t,n,r,i,a){let o=r.result,s=r.isError;if(i.afterToolCall)try{let r=await i.afterToolCall({assistantMessage:t,toolCall:n.toolCall,args:n.args,result:o,isError:s,context:e},a);r&&(o={...o,content:r.content??o.content,details:r.details??o.details,usage:r.usage??o.usage,terminate:r.terminate??o.terminate},s=r.isError??s)}catch(e){o=uh(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function uh(e){return{content:[{type:`text`,text:e}],details:{}}}async function dh(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function fh(e){return{role:`toolResult`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,...e.result.addedToolNames?.length?{addedToolNames:e.result.addedToolNames}:{},isError:e.isError,timestamp:Date.now()}}async function ph(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function Fce(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const Ice={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Lce={id:`unknown`,name:`unknown`,api:`unknown`,provider:`unknown`,baseUrl:``,reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function Rce(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??Lce,thinkingLevel:e?.thinkingLevel??`off`,get tools(){return t},set tools(e){t=e.slice()},get messages(){return n},set messages(e){n=e.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}var mh=class{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}drain(){if(this.mode===`all`){let e=this.messages.slice();return this.messages=[],e}let e=this.messages[0];return e?(this.messages=this.messages.slice(1),[e]):[]}clear(){this.messages=[]}},zce=class{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;beforeToolCall;afterToolCall;shouldStopAfterTurn;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let t=e??{};this._state=Rce(t.initialState),this.convertToLlm=t.convertToLlm??Fce,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??ih(),this.getApiKey=t.getApiKey,this.onPayload=t.onPayload,this.onResponse=t.onResponse,this.beforeToolCall=t.beforeToolCall,this.afterToolCall=t.afterToolCall,this.shouldStopAfterTurn=t.shouldStopAfterTurn,this.prepareNextTurn=t.prepareNextTurn,this.prepareNextTurnWithContext=t.prepareNextTurnWithContext,this.steeringQueue=new mh(t.steeringMode??`one-at-a-time`),this.followUpQueue=new mh(t.followUpMode??`one-at-a-time`),this.sessionId=t.sessionId,this.thinkingBudgets=t.thinkingBudgets,this.transport=t.transport??`auto`,this.maxRetryDelayMs=t.maxRetryDelayMs,this.toolExecution=t.toolExecution??`parallel`}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before resetting.`);this._state.messages=[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,t){if(this.activeRun)throw Error(`Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.`);let n=this.normalizePromptInput(e,t);await this.runPromptMessages(n)}async continue(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before continuing.`);let e=this._state.messages[this._state.messages.length-1];if(!e)throw Error(`No messages to continue from`);if(e.role===`assistant`){let e=this.steeringQueue.drain();if(e.length>0){await this.runPromptMessages(e,{skipInitialSteeringPoll:!0});return}let t=this.followUpQueue.drain();if(t.length>0){await this.runPromptMessages(t);return}throw Error(`Cannot continue from message role: assistant`)}await this.runContinuation()}normalizePromptInput(e,t){if(Array.isArray(e))return e;if(typeof e!=`string`)return[e];let n=[{type:`text`,text:e}];return t&&t.length>0&&n.push(...t),[{role:`user`,content:n,timestamp:Date.now()}]}async runPromptMessages(e,t={}){await this.runWithLifecycle(async n=>{await Dce(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await Oce(this.createContextSnapshot(),this.createLoopConfig(),e=>this.processEvents(e),e,this.streamFunction)})}createContextSnapshot(){return{systemPrompt:this._state.systemPrompt,messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let t=e.skipInitialSteeringPoll===!0,n=this.shouldStopAfterTurn;return{model:this._state.model,reasoning:this._state.thinkingLevel===`off`?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,shouldStopAfterTurn:n?async e=>await n(e,this.signal):void 0,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async e=>this.prepareNextTurnWithContext?await this.prepareNextTurnWithContext(e,this.signal):await this.prepareNextTurn?.(this.signal):void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>t?(t=!1,[]):this.steeringQueue.drain(),getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error(`Agent is already processing.`);let t=new AbortController,n=()=>{},r=new Promise(e=>{n=e});this.activeRun={promise:r,resolve:n,abortController:t},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(t.signal)}catch(e){await this.handleRunFailure(e,t.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,t){let n={role:`assistant`,content:[{type:`text`,text:``}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:Ice,stopReason:t?`aborted`:`error`,errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:`message_start`,message:n}),await this.processEvents({type:`message_end`,message:n}),await this.processEvents({type:`turn_end`,message:n,toolResults:[]}),await this.processEvents({type:`agent_end`,messages:[n]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case`message_start`:this._state.streamingMessage=e.message;break;case`message_update`:this._state.streamingMessage=e.message;break;case`message_end`:this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case`tool_execution_start`:{let t=new Set(this._state.pendingToolCalls);t.add(e.toolCallId),this._state.pendingToolCalls=t;break}case`tool_execution_end`:{let t=new Set(this._state.pendingToolCalls);t.delete(e.toolCallId),this._state.pendingToolCalls=t;break}case`turn_end`:e.message.role===`assistant`&&e.message.errorMessage&&(this._state.errorMessage=e.message.errorMessage);break;case`agent_end`:this._state.streamingMessage=void 0}let t=this.activeRun?.abortController.signal;if(!t)throw Error(`Agent listener invoked outside active run`);for(let n of this.listeners)await n(e,t)}};const Bce=Object.freeze({token:Symbol(`chord.abortSignal`)});var Vce=class{get abortSignal(){return this.value(Bce)}},hh=class extends Vce{#e;constructor(e){super(),this.#e=e}value(e){}toString(){return this.#e}};new hh(`[Context BACKGROUND_CONTEXT]`),new hh(`[Context TODO_CONTEXT]`);function Hce(e){return Object.freeze({token:Symbol(e)})}Hce(`pi.telemetryContext`);const gh={"pi.session.id":{type:`string`,required:!0,cardinality:`high`,description:`Session id`},"pi.lane.name":{type:`string`,required:!0,cardinality:`high`,description:`Lane name`},"pi.operation.id":{type:`string`,required:!0,cardinality:`high`,description:`Durable operation id`},"pi.operation.recovery":{type:`boolean`,required:!0,description:`Whether this invocation resumes durable work`}},_h={"pi.error.code":{type:`string`,cardinality:`low`,description:`Stable operation error code`},"pi.error.type":{type:`string`,cardinality:`low`,description:`Low-cardinality operation error class`}};({...gh}),{..._h},{...gh},{..._h},{...gh},{..._h};function Uce(e,t){if(e.length===0)throw TypeError(`Value namespace must not be empty`);if(e.includes(`\0`))throw TypeError(`Value namespace must not contain \\u0000`);if(t.includes(`\0`))throw TypeError(`Value key must not contain \\u0000`)}function Wce(e,t=``){return Uce(e,t),Object.freeze({namespace:e,key:t,kind:`value`})}Wce(`pi.session.name`);const vh=Symbol.for(`yaml.alias`),Gce=Symbol.for(`yaml.document`),yh=Symbol.for(`yaml.map`),bh=Symbol.for(`yaml.pair`),xh=Symbol.for(`yaml.scalar`),Sh=Symbol.for(`yaml.seq`),Ch=Symbol.for(`yaml.node.type`),wh=e=>!!e&&typeof e==`object`&&e[Ch]===vh,Th=e=>!!e&&typeof e==`object`&&e[Ch]===Gce,Eh=e=>!!e&&typeof e==`object`&&e[Ch]===yh,Dh=e=>!!e&&typeof e==`object`&&e[Ch]===bh,Oh=e=>!!e&&typeof e==`object`&&e[Ch]===xh,kh=e=>!!e&&typeof e==`object`&&e[Ch]===Sh;function Ah(e){if(e&&typeof e==`object`)switch(e[Ch]){case yh:case Sh:return!0}return!1}function jh(e){if(e&&typeof e==`object`)switch(e[Ch]){case vh:case yh:case xh:case Sh:return!0}return!1}const Mh=e=>(Oh(e)||Ah(e))&&!!e.anchor,Nh=Symbol(`break visit`),Kce=Symbol(`skip children`),Ph=Symbol(`remove node`);function Fh(e,t){let n=qce(t);Th(e)?Ih(null,e.contents,n,Object.freeze([e]))===Ph&&(e.contents=null):Ih(null,e,n,Object.freeze([]))}Fh.BREAK=Nh,Fh.SKIP=Kce,Fh.REMOVE=Ph;function Ih(e,t,n,r){let i=Jce(e,t,n,r);if(jh(i)||Dh(i))return Yce(e,r,i),Ih(e,i,n,r);if(typeof i!=`symbol`){if(Ah(t)){r=Object.freeze(r.concat(t));for(let e=0;ezh(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!Mh(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var Bh=class{constructor(e){Object.defineProperty(this,Ch,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!Th(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=zh(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?Rh(i,{"":o},``,o):o}},Xce=class extends Bh{constructor(e){super(vh),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Fh(e,{Node:(e,t)=>{(wh(t)||Mh(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,a=this.resolve(r,t);if(!a){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let o=n.get(a);if(o||=(zh(a,null,t),n.get(a)),o?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(o.count+=1,o.aliasCount===0&&(o.aliasCount=Vh(r,a,n)),o.count*o.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return o.res}toString(e,t,n){let r=`*${this.source}`;if(e){if(Lh(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function Vh(e,t,n){if(wh(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Ah(t)){let r=0;for(let i of t.items){let t=Vh(e,i,n);t>r&&(r=t)}return r}if(Dh(t)){let r=Vh(e,t.key,n),i=Vh(e,t.value,n);return Math.max(r,i)}return 1}const Hh=e=>!e||typeof e!=`function`&&typeof e!=`object`;var Uh=class extends Bh{constructor(e){super(xh),this.value=e}toJSON(e,t){return t?.keep?this.value:zh(this.value,e,t)}toString(){return String(this.value)}};Uh.BLOCK_FOLDED=`BLOCK_FOLDED`,Uh.BLOCK_LITERAL=`BLOCK_LITERAL`,Uh.PLAIN=`PLAIN`,Uh.QUOTE_DOUBLE=`QUOTE_DOUBLE`,Uh.QUOTE_SINGLE=`QUOTE_SINGLE`;function Zce(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function Wh(e,t,n){if(Th(e)&&(e=e.contents),jh(e))return e;if(Dh(e)){let t=n.schema[yh].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new Xce(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=`tag:yaml.org,2002:`+t.slice(2));let l=Zce(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new Uh(e);return c&&(c.node=t),t}l=e instanceof Map?o[yh]:Symbol.iterator in Object(e)?o[Sh]:o[yh]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new Uh(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Gh(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return Wh(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}const Qce=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;var Kh=class extends Bh{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>jh(t)||Dh(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Qce(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(Ah(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Gh(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(Ah(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&Oh(i)?i.value:i:Ah(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Dh(t))return!1;let n=t.value;return n==null||e&&Oh(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return Ah(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(Ah(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Gh(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};const $ce=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function qh(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const Jh=(e,t,n)=>e.endsWith(` +`)?qh(n,t):n.includes(` +`)?` +`+qh(n,t):(e.endsWith(` `)?``:` `)+n,Yh=`flow`;function Xh(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;ii-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=Zh(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===` +`)n===`block`&&(h=Zh(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==` +`&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==` +`&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),$h=e=>/^(%|---|\.\.\.)/m.test(e);function ele(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;tr)return!0;if(n=t+1,i-n<=r)return!1}return!0}function eg(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||($h(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length +`;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==` +`&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(` +`);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===` +`&&(p=p.slice(0,-1)),p.replace(rg,`$&${l}`));let h=!1,g,_=-1;for(g=0;g{i=!0});let s=Xh(`${v}${e}${p}`,l,`block`,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function tle(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(` +`)||u&&/[[\]{},]/.test(a))return ng(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(` +`)?ng(a,t):ig(e,t,n,r);if(!s&&!u&&i!==Uh.PLAIN&&a.includes(` +`))return ig(e,t,n,r);if($h(a)){if(c===``)return t.forceBlockIndent=!0,ig(e,t,n,r);if(s&&c===l)return ng(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return ng(a,t)}return s?d:Xh(d,c,Yh,Qh(t,!1))}function nle(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Uh.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Uh.QUOTE_DOUBLE);let c=e=>{switch(e){case Uh.BLOCK_FOLDED:case Uh.BLOCK_LITERAL:return i||a?ng(o.value,t):ig(o,t,n,r);case Uh.QUOTE_DOUBLE:return eg(o.value,t);case Uh.QUOTE_SINGLE:return tg(o.value,t);case Uh.PLAIN:return tle(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function rle(e,t){let n=Object.assign({blockQuote:!0,commentString:$ce,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function ile(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(Oh(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function ale(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(Oh(e)||Ah(e))&&e.anchor;a&&Lh(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function ag(e,t,n,r){if(Dh(e))return e.toString(t,n,r);if(wh(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=jh(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=ile(t.doc.schema.tags,a);let o=ale(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):Oh(a)?nle(a,t,n,r):a.toString(t,n,r);return o?Oh(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function ole({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=jh(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(Ah(e)||!jh(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||Ah(e)||(Oh(e)?e.type===Uh.BLOCK_FOLDED||e.type===Uh.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=ag(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=Jh(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Jh(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Jh(g,n.indent,l(f))));let _,v,y;jh(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&Oh(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&kh(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=ag(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?` +`:``,v){let e=l(v);S+=`\n${qh(e,n.indent)}`}x===``&&!n.inFlow?S===` +`&&y&&(S=` + +`):S+=`\n${n.indent}`}else if(!p&&Ah(t)){let e=x[0],r=x.indexOf(` +`),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=x.indexOf(` `);e===`&`&&n!==-1&&ne===`<<`||typeof e==`symbol`&&e.description===`<<`,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new Uh(Symbol(`<<`)),{addToJSMap:sg}),stringify:()=>`<<`},cle=(e,t)=>(og.identify(t)||Oh(t)&&(!t.type||t.type===Uh.PLAIN)&&og.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===og.tag&&e.default);function sg(e,t,n){let r=lg(e,n);if(kh(r))for(let n of r.items)cg(e,t,n);else if(Array.isArray(r))for(let n of r)cg(e,t,n);else cg(e,t,r)}function cg(e,t,n){let r=lg(e,n);if(!Eh(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function lg(e,t){return e&&wh(t)?t.resolve(e.doc,e):t}function ug(e,t,{key:n,value:r}){if(jh(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(cle(e,n))sg(e,t,r);else{let i=zh(n,``,e);if(t instanceof Map)t.set(i,zh(r,i,e));else if(t instanceof Set)t.add(i);else{let a=lle(n,i,e),o=zh(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function lle(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(jh(e)&&n?.doc){let t=rle(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),sle(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function dg(e,t,n){return new fg(Wh(e,void 0,n),Wh(t,void 0,n))}var fg=class e{constructor(e,t=null){Object.defineProperty(this,Ch,{value:bh}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return jh(n)&&(n=n.clone(t)),jh(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return ug(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?ole(this,e,t,n):JSON.stringify(this)}};function pg(e,t,n){return(t.inFlow??e.flow?dle:ule)(e,t,n)}function ule({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;eo=null,()=>d=!0);o&&(s+=Jh(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;ea=null);l||=d.length>u||o.includes(` +`),n0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=Jh(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:` +`;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function mg({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=qh(t(r),e);n.push(i.trimStart())}}function hg(e,t){let n=Oh(t)?t.value:t;for(let r of e)if(Dh(r)&&(r.key===t||r.key===n||Oh(r.key)&&r.key.value===n))return r}var gg=class extends Kh{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(yh,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(dg(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=Dh(e)?e:!e||typeof e!=`object`||!(`key`in e)?new fg(e,e?.value):new fg(e.key,e.value);let r=hg(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);Oh(r.value)&&Hh(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=hg(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=hg(this.items,e)?.value;return(!t&&Oh(n)?n.value:n)??void 0}has(e){return!!hg(this.items,e)}set(e,t){this.add(new fg(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)ug(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!Dh(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),pg(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}};const fle={collection:`map`,default:!0,nodeClass:gg,tag:`tag:yaml.org,2002:map`,resolve(e,t){return Eh(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>gg.from(e,t,n)};var _g=class extends Kh{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(Sh,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=vg(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=vg(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&Oh(r)?r.value:r}has(e){let t=vg(e);return typeof t==`number`&&t=0?t:null}const ple={collection:`seq`,default:!0,nodeClass:_g,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return kh(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>_g.from(e,t,n)};function yg(e){return typeof e==`bigint`||Number.isInteger(e)}const bg=({value:e})=>JSON.stringify(e),mle=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:bg},{identify:e=>e==null,createNode:()=>new Uh(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:bg},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:bg},{identify:yg,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>yg(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:bg}];[fle,ple].concat(mle,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}});function hle(e,t,n){let{replacer:r}=n,i=new _g(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(dg(o,s,n))}return i}var gle=class e extends _g{constructor(){super(),this.add=gg.prototype.add.bind(this),this.delete=gg.prototype.delete.bind(this),this.get=gg.prototype.get.bind(this),this.has=gg.prototype.has.bind(this),this.set=gg.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(Dh(e)?(r=zh(e.key,``,t),i=zh(e.value,r,t)):r=zh(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=hle(e,t,n),i=new this;return i.items=r.items,i}};gle.tag=`tag:yaml.org,2002:omap`;var _le=class e extends gg{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=Dh(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new fg(e.key,null):new fg(e,null),hg(this.items,t.key)||this.items.push(t)}get(e,t){let n=hg(this.items,e);return!t&&Dh(n)?Oh(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=hg(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new fg(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(dg(e,null,n));return i}};_le.tag=`tag:yaml.org,2002:set`;const xg=Symbol(`break visit`),vle=Symbol(`skip children`),Sg=Symbol(`remove item`);function Cg(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),wg(Object.freeze([]),e,t)}Cg.BREAK=xg,Cg.SKIP=vle,Cg.REMOVE=Sg,Cg.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},Cg.parentCollection=(e,t)=>{let n=Cg.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function wg(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.{0,2}\/|^\.{1,2}$/,l=/\/$/,u=`node-ignore`;typeof Symbol<`u`&&(u=Symbol.for(`node-ignore`));let d=u,f=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),p=/([0-z])-([0-z])/g,m=()=>!1,h=e=>e.replace(p,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),g=e=>{let{length:t}=e;return e.slice(0,t-t%2)},_=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${g(r)}${i}`:i===`]`&&r.length%2==0?`[${h(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],v=/(^|\\\/)?\\\*$/,y=`regex`,b=`checkRegex`,x={[y](e,t){return`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`},[b](e,t){return`${t?`${t}[^/]*`:`[^/]*`}(?=$|\\/$)`}},S=e=>_.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),C=e=>typeof e==`string`,w=e=>e&&C(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,T=e=>e.split(s).filter(Boolean);var E=class{constructor(e,t,n,r,i,a){this.pattern=e,this.mark=t,this.negative=i,f(this,`body`,n),f(this,`ignoreCase`,r),f(this,`regexPrefix`,a)}get regex(){let e=`_regex`;return this[e]?this[e]:this._make(y,e)}get checkRegex(){let e=`_checkRegex`;return this[e]?this[e]:this._make(b,e)}_make(e,t){let n=this.regexPrefix.replace(v,x[e]),r=this.ignoreCase?new RegExp(n,`i`):new RegExp(n);return f(this,t,r)}};let D=({pattern:e,mark:t},n)=>{let r=!1,i=e;i.indexOf(`!`)===0&&(r=!0,i=i.substr(1)),i=i.replace(a,`!`).replace(o,`#`);let s=S(i);return new E(e,t,i,n,r,s)};var O=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[d]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(C(e)&&(e={pattern:e}),w(e.pattern)){let t=D(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(C(e)?T(e):e).forEach(this._add,this),this._added}test(e,t,n){let r=!1,i=!1,a;this._rules.forEach(o=>{let{negative:s}=o;i===s&&r!==i||s&&!r&&!i&&!t||o[n].test(e)&&(r=!s,i=s,a=s?void 0:o)});let o={ignored:r,unignored:i};return a&&(o.rule=a),o}};let k=(e,t)=>{throw new t(e)},A=(e,t,n)=>C(e)?e?!A.isNotRelative(e)||n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),j=e=>c.test(e);A.isNotRelative=j,A.convert=e=>e;var M=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){f(this,d,!0),this._rules=new O(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,r){let i=e&&A.convert(e);return A(i,e,this._strictPathCheck?k:m),this._t(i,t,n,r)}checkIgnore(e){if(!l.test(e))return this.test(e);let t=e.split(`/`).filter(Boolean);if(t.pop(),t.length){let e=this._t(t.join(`/`)+`/`,this._testCache,!0,t);if(e.ignored)return e}return this._rules.test(e,!1,b)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`).filter(Boolean),r.pop(),!r.length)return t[e]=this._rules.test(e,n,y);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._rules.test(e,n,y)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let ee=e=>new M(e),te=e=>A(e&&A.convert(e),e,m),N=()=>{A.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;A.isNotRelative=t=>e.test(t)||j(t)};typeof process<`u`&&process.platform===`win32`&&N(),t.exports=ee,ee.default=ee,t.exports.isPathValid=te,f(t.exports,Symbol.for(`setupWindows`),N)}))(),globalThis.Buffer,new TextEncoder,new TextDecoder,Sn({command:Yr({description:`Bash command to execute`}),timeout:_n(Gr({description:`Timeout in seconds (optional, no default timeout)`}))});var Tg=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Tg{};function Eg(e,t){let n=0;for(;nt.length&&(n=e.length-t.length);let r=t.length;e.length0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Ng(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function Pg(e,t){if(t)return Ig(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function Fg(e,t){if(t)return Ig(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function Ig(e,t){if(!t)return[Fg(e),Pg(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=Ng(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}const Lg=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,ble=RegExp(`[${Lg}]+|\\s+|[^${Lg}]`,`ug`);new class extends Tg{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Ng(e,r)}else n=e.match(ble)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Rg(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&Rg(n,i,r,null,t.intlSegmenter),e}};function Rg(e,t,n,r,i){if(t&&n){let[a,o]=Ig(t.value,i),[s,c]=Ig(n.value,i);if(e){let r=Eg(a,s);e.value=kg(e.value,s,r),t.value=Ag(t.value,r),n.value=Ag(n.value,r)}if(r){let e=Dg(o,c);r.value=Og(r.value,c,e),t.value=jg(t.value,e),n.value=jg(n.value,e)}}else if(n){if(e){let e=Fg(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=Fg(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Fg(r.value,i),[a,o]=Ig(t.value,i),s=Eg(n,a);t.value=Ag(t.value,s);let c=Dg(Ag(n,s),o);t.value=jg(t.value,c),r.value=Og(r.value,n,c),e.value=kg(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=Fg(r.value,i),n=Mg(Pg(t.value,i),e);t.value=jg(t.value,n)}else if(e){let n=Mg(Pg(e.value,i),Fg(t.value,i));t.value=Ag(t.value,n)}}new class extends Tg{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Lg}]+|[^\\S\\n\\r]+|[^${Lg}]`,`ug`);return e.match(t)||[]}};const xle=new class extends Tg{constructor(){super(...arguments),this.tokenize=Bg}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(` +`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(` +`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(` +`)&&(e=e.slice(0,-1)),t.endsWith(` +`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function zg(e,t,n){return xle.diff(e,t,n)}function Bg(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,` +`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;et===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(Vg(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function Vg(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a=0;for(;a{let n=l(t);e(n)}}))}else return l(zg(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s){if(i.length<=c*2&&e1&&!t.includeFileHeaders)throw Error(`Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)`);return e.map(e=>Ug(e,t)).join(` +`)}let n=[];t.includeIndex&&e.oldFileName==e.newFileName&&n.push(`Index: `+e.oldFileName),t.includeUnderline&&n.push(`===================================================================`),t.includeFileHeaders&&(n.push(`--- `+e.oldFileName+(e.oldHeader===void 0?``:` `+e.oldHeader)),n.push(`+++ `+e.newFileName+(e.newHeader===void 0?``:` `+e.newHeader)));for(let t=0;t{s(e?Ug(e,o.headerOptions):void 0)}}))}else{let s=Hg(e,t,n,r,i,a,o);return s?Ug(s,o?.headerOptions):void 0}}function Tle(e){let t=e.endsWith(` +`),n=e.split(` +`).map(e=>e+` +`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const Ele=Sn({oldText:Yr({description:`Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.`}),newText:Yr({description:`Replacement text for this targeted edit.`})},{});Sn({path:Yr({description:`Path to the file to edit (relative or absolute)`}),edits:Qt(Ele,{description:`One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.`})},{}),Sn({path:Yr({description:`Path to the file to read (relative or absolute)`}),offset:_n(Gr({description:`Line number to start reading from (1-indexed)`})),limit:_n(Gr({description:`Maximum number of lines to read`}))}),Sn({path:Yr({description:`Path to the file to write (relative or absolute)`}),content:Yr({description:`Content to write to the file`})});var Dle=n({InferenceSession:()=>j_,TRACE:()=>C_,TRACE_EVENT_BEGIN:()=>D_,TRACE_EVENT_END:()=>O_,TRACE_FUNC_BEGIN:()=>T_,TRACE_FUNC_END:()=>E_,Tensor:()=>x_,default:()=>Yy,env:()=>i_,registerBackend:()=>Xg}),Wg=Object.defineProperty,Ole=Object.getOwnPropertyDescriptor,kle=Object.getOwnPropertyNames,Ale=Object.prototype.hasOwnProperty,jle=(e=>typeof r<`u`?r:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof r<`u`?r:e)[t]}):e)(function(e){ +/*! +* ONNX Runtime Web v1.26.0-dev.20260416-b7804b056c +* Copyright (c) Microsoft Corporation. All rights reserved. +* Licensed under the MIT License. +*/ +if(typeof r<`u`)return r.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),Gg=(e,t)=>()=>(e&&(t=e(e=0)),t),Kg=(e,t)=>{for(var n in t)Wg(e,n,{get:t[n],enumerable:!0})},Mle=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of kle(t))!Ale.call(e,i)&&i!==n&&Wg(e,i,{get:()=>t[i],enumerable:!(r=Ole(t,i))||r.enumerable});return e},qg=e=>Mle(Wg({},`__esModule`,{value:!0}),e),Jg,Yg,Xg,Zg,Qg,$g=Gg(()=>{Jg=new Map,Yg=[],Xg=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=Jg.get(e);if(r===void 0)Jg.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=Yg.indexOf(e);t!==-1&&Yg.splice(t,1);for(let t=0;t{let t=Jg.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Qg=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?Yg:n,i,a=[],o=new Set;for(let e of r){let t=await Zg(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),Nle=Gg(()=>{$g()}),e_,Ple=Gg(()=>{e_=`1.24.0-dev.20251116-b39e144322`}),t_,n_,r_=Gg(()=>{Ple(),t_=`warning`,n_={wasm:{},webgl:{},webgpu:{},versions:{common:e_},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);t_=e}},get logLevel(){return t_}},Object.defineProperty(n_,"logLevel",{enumerable:!0})}),i_,Fle=Gg(()=>{r_(),i_=n_}),a_,o_,Ile=Gg(()=>{a_=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{b_(),s_=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,s_(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(s_(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return s_(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},l_=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new y_({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},u_=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new y_({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},d_=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new y_({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},f_=(e,t,n)=>new y_({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),p_,m_,h_,g_,Rle=Gg(()=>{p_=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),m_=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),h_=!1,g_=()=>{if(!h_){h_=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(p_.set(`int64`,BigInt64Array),m_.set(BigInt64Array,`int64`)),t&&(p_.set(`uint64`,BigUint64Array),m_.set(BigUint64Array,`uint64`)),r?(p_.set(`float16`,n),m_.set(n,`float16`)):p_.set(`float16`,Uint16Array)}}}),__,v_,zle=Gg(()=>{b_(),__=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new y_(e.type,e.data,t);case`cpu-pinned`:return new y_({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new y_({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new y_({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new y_({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),y_,b_=Gg(()=>{Ile(),Lle(),Rle(),zle(),y_=class{constructor(e,t,n){g_();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=p_.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=p_.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=m_.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=__(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return c_(e,t)}static fromTexture(e,t){return l_(e,t)}static fromGpuBuffer(e,t){return u_(e,t)}static fromMLTensor(e,t){return d_(e,t)}static fromPinnedBuffer(e,t,n){return f_(e,t,n)}toDataURL(e){return a_(this,e)}toImageData(e){return o_(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return v_(this,e)}}}),x_,S_=Gg(()=>{b_(),x_=y_}),C_,w_,T_,E_,D_,O_,k_=Gg(()=>{r_(),C_=(e,t)=>{(typeof n_.trace>`u`?!n_.wasm.trace:!n_.trace)||console.timeStamp(`${e}::ORT::${t}`)},w_=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof n_.trace>`u`?!n_.wasm.trace:!n_.trace)||w_(`BEGIN`,e)},E_=e=>{(typeof n_.trace>`u`?!n_.wasm.trace:!n_.trace)||w_(`END`,e)},D_=e=>{(typeof n_.trace>`u`?!n_.wasm.trace:!n_.trace)||console.time(`ORT::${e}`)},O_=e=>{(typeof n_.trace>`u`?!n_.wasm.trace:!n_.trace)||console.timeEnd(`ORT::${e}`)}}),A_,Ble=Gg(()=>{$g(),S_(),k_(),A_=class e{constructor(e){this.handler=e}async run(e,t,n){T_(),D_(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof x_||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof x_)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof x_)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof x_?t:new x_(t.type,t.data,t.dims)}return O_(`InferenceSession.run`),E_(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){T_(),D_(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await Qg(o),l=await s.createInferenceSessionHandler(a,c);return O_(`InferenceSession.create`),E_(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),j_,Vle=Gg(()=>{Ble(),j_=A_}),Hle=Gg(()=>{}),Ule=Gg(()=>{}),Wle=Gg(()=>{}),Gle=Gg(()=>{}),M_={};Kg(M_,{InferenceSession:()=>j_,TRACE:()=>C_,TRACE_EVENT_BEGIN:()=>D_,TRACE_EVENT_END:()=>O_,TRACE_FUNC_BEGIN:()=>T_,TRACE_FUNC_END:()=>E_,Tensor:()=>x_,env:()=>i_,registerBackend:()=>Xg});var N_=Gg(()=>{Nle(),Fle(),Vle(),S_(),Hle(),Ule(),k_(),Wle(),Gle()}),P_=Gg(()=>{}),F_={};Kg(F_,{default:()=>R_});var I_,L_,R_,Kle=Gg(()=>{by(),pv(),rv(),I_=`ort-wasm-proxy-worker`,L_=globalThis.self?.name===I_,L_&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:dv(n.wasm).then(()=>{cy(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;ly(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=py(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;my(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:hy(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;_y(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},yy([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:vy(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),R_=L_?null:e=>new Worker(e??K_,{type:`module`,name:I_})}),z_={};Kg(z_,{default:()=>V_});async function B_(e={}){var t=e,n=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith(`em-pthread`);t.mountExternalData=(e,n)=>{e.startsWith(`./`)&&(e=e.substring(2)),(t.Uc||=new Map).set(e,n)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let e=e=>(...t)=>{let n=rn;return t=e(...t),rn==n?t:new Promise((e,t)=>{dn={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),typeof jsepRunAsync<`u`&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,s,c=(e,t)=>{throw t},l=import.meta.url,u=``;if(n||r){try{u=new URL(`.`,l).href}catch{}r&&(s=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),o=async e=>{if(S(e))return new Promise((t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{r.status==200||r.status==0&&r.response?t(r.response):n(r.status)},r.onerror=n,r.send(null)});var t=await fetch(e,{credentials:`same-origin`});if(t.ok)return t.arrayBuffer();throw Error(t.status+` : `+t.url)}}var d,f,p,m,h,g,_=console.log.bind(console),v=console.error.bind(console),y=_,b=v,x=!1,S=e=>e.startsWith(`file://`);function C(){Te.buffer!=T.buffer&&re()}if(i){let e=function(n){try{var r=n.data,i=r.Oc;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),g=()=>{postMessage({Oc:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.ce)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({Oc:`callHandler`,be:e,args:t})},e==`print`&&(y=t[e]),e==`printErr`&&(b=t[e]));Te=r.ie,re(),f=r.je,se(),zo()}else if(i===`run`){(function(e){var t=(C(),A)[e+52>>>2>>>0];e=(C(),A)[e+56>>>2>>>0],aa(t,t-e),oa(t)})(r.Nc),Yi(r.Nc,0,0,1,0,0),Se(),Kt(r.Nc),w||=(Ei(),!0);try{Ee(r.ge,r.Wc)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?w&&qt():i&&(b(`worker: received unknown command ${i}`),b(r)))}catch(e){throw Xi(),e}};var w=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var T,E,D,O,k,A,j,M,ee,te,N,ne=!1;function re(){var e=Te.buffer;t.HEAP8=T=new Int8Array(e),D=new Int16Array(e),t.HEAPU8=E=new Uint8Array(e),O=new Uint16Array(e),t.HEAP32=k=new Int32Array(e),t.HEAPU32=A=new Uint32Array(e),j=new Float32Array(e),M=new Float64Array(e),ee=new BigInt64Array(e),te=new BigUint64Array(e)}function ie(){ne=!0,i?g():$a._b()}function ae(e){throw b(e=`Aborted(`+e+`)`),x=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),h?.(e),e}function oe(){return{a:{f:Ae,J:Me,k:Le,p:Re,l:ze,sa:Be,b:Ve,ca:He,Ja:We,q:Ge,da:Xe,Za:Ze,Fa:Qe,Ha:$e,_a:et,Xa:tt,Qa:nt,Wa:rt,oa:it,Ga:at,Xb:ot,Ya:st,Yb:ct,db:lt,Da:_t,Sb:vt,Qb:Et,Ca:Ot,M:kt,I:At,Rb:Nt,ja:Vt,Tb:Ht,Ta:Ut,Vb:Jt,Ka:Xt,Ob:Zt,ka:Qt,Sa:Kt,ab:$t,U:mn,n:xn,c:xt,rb:Sn,w:Cn,L:wn,z:Tn,j:En,o:Dn,sb:On,G:kn,T:An,h:jn,u:Mn,m:Nn,i:Pn,Na:Fn,Oa:zn,Pa:Bn,La:Vn,Ma:Hn,Pb:Gn,eb:Kn,cb:Yn,Y:Qn,qb:$n,la:er,bb:qn,fb:tr,$a:nr,Wb:rr,N:Wn,gb:ir,X:ar,Ub:or,nb:Or,C:kr,ra:Ar,qa:jr,pb:Mr,W:Nr,v:Pr,mb:Fr,lb:Ir,kb:Lr,ob:Rr,jb:zr,ib:Br,hb:Vr,Ua:Gr,Va:Kr,Ia:_e,V:qr,na:Jr,Ra:Yr,ma:Zr,Cb:Lo,xa:jo,Db:Io,ya:Ao,F:yo,e:ao,s:ro,x:no,B:go,Fb:Do,ba:Eo,D:co,za:Oo,$:Mo,ga:To,Gb:wo,Hb:Co,Ba:bo,Aa:So,Ib:xo,wa:Fo,aa:ko,d:io,A:so,r:oo,Bb:Ro,t:uo,y:_o,H:lo,E:fo,K:vo,R:No,ia:ho,_:Po,Jb:mo,Kb:po,g:Qr,a:Te,Nb:P,Eb:$r,ha:ei,O:ti,pa:ni,Lb:ri,ta:ii,Q:ai,yb:oi,zb:si,ua:ci,ea:li,P:ui,Ea:di,va:fi,Z:pi,wb:mi,Zb:hi,S:gi,Ab:_i,tb:vi,ub:bi,vb:xi,fa:Si,xb:Ci,Mb:wi}}}async function se(){function e(e,n){var r=$a=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=tn(n),e[t]=r):e[t]=n;return $a=e,$a=function(){var e=$a,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).$b=t(e.$b),e.Cc=n(e.Cc),e.Ec=t(e.Ec),e.rd=(e=>(t,n)=>e(t,n)>>>0)(e.rd),e.wd=t(e.wd),e.xd=n(e.xd),e.Bd=t(e.Bd),e}(),ye.push($a.id),Ti=(e=$a).$b,Ei=e.ac,t._OrtInit=e.bc,t._OrtGetLastError=e.cc,t._OrtCreateSessionOptions=e.dc,t._OrtAppendExecutionProvider=e.ec,t._OrtAddFreeDimensionOverride=e.fc,t._OrtAddSessionConfigEntry=e.gc,t._OrtReleaseSessionOptions=e.hc,t._OrtCreateSession=e.ic,t._OrtReleaseSession=e.jc,t._OrtGetInputOutputCount=e.kc,t._OrtGetInputOutputMetadata=e.lc,t._OrtFree=e.mc,t._OrtCreateTensor=e.nc,t._OrtGetTensorData=e.oc,t._OrtReleaseTensor=e.pc,t._OrtCreateRunOptions=e.qc,t._OrtAddRunConfigEntry=e.rc,t._OrtReleaseRunOptions=e.sc,t._OrtCreateBinding=e.tc,t._OrtBindInput=e.uc,t._OrtBindOutput=e.vc,t._OrtClearBoundOutputs=e.wc,t._OrtReleaseBinding=e.xc,t._OrtRunWithBinding=e.yc,t._OrtRun=e.zc,t._OrtEndProfiling=e.Ac,Di=t._OrtGetWebGpuDevice=e.Bc,Oi=e.Cc,ki=t._free=e.Dc,Ai=t._malloc=e.Ec,ji=t._wgpuBufferRelease=e.Fc,Mi=t._wgpuCreateInstance=e.Gc,Ni=e.Hc,Pi=e.Ic,Fi=e.Jc,Ii=e.Kc,Li=e.Lc,Ri=e.Pc,zi=e.Zc,Bi=e._c,Vi=e.$c,Hi=e.bd,Ui=e.cd,Wi=e.dd,Gi=e.ed,Ki=e.fd,qi=e.gd,Ji=e.hd,Yi=e.kd,Xi=e.ld,Zi=e.md,Qi=e.nd,$i=e.od,ea=e.pd,ta=e.qd,na=e.rd,ra=e.sd,ia=e.td,aa=e.ud,oa=e.vd,sa=e.wd,ca=e.xd,la=e.yd,ua=e.zd,da=e.Ad,fa=e.Bd,pa=e.Cd,ma=e.Dd,ha=e.Ed,ga=e.Fd,_a=e.Gd,va=e.Hd,ya=e.Id,ba=e.Jd,xa=e.Kd,Sa=e.Ld,Ca=e.Md,wa=e.Nd,Ta=e.Od,Ea=e.Pd,Da=e.Qd,Oa=e.Rd,ka=e.Td,Aa=e.Ud,ja=e.Vd,Ma=e.Wd,Na=e.Yd,Pa=e.Zd,Fa=e._d,Ia=e.$d,La=e.ae,Ra=e.oe,za=e.pe,Ba=e.qe,Va=e.re,Ha=e.se,Ua=e.te,Wa=e.ue,Ga=e.ve,Ka=e.we,qa=e.xe,Ja=e.ye,Ya=e.Ye,Xa=e.Ze,Za=e._e,Qa=e.$e,f=n,$a}var n,r=oe();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(f,oe()),f):(N??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.asyncify.wasm`,u):u+`ort-wasm-simd-threaded.asyncify.wasm`:new URL(new URL(`ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm`,import.meta.url).href,``+import.meta.url).href,n=await async function(e){var t=N;if(!d&&!S(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){b(`wasm streaming compile failed: ${e}`),b(`falling back to ArrayBuffer instantiation`)}return async function(e,t){try{var n=await async function(e){if(!d)try{var t=await o(e);return new Uint8Array(t)}catch{}if(e==N&&d)e=new Uint8Array(d);else{if(!s)throw`both async and sync fetching of the wasm failed`;e=s(e)}return e}(e);return await WebAssembly.instantiate(n,t)}catch(e){b(`failed to asynchronously prepare wasm: ${e}`),ae(e)}}(t,e)}(r),e(n.instance,n.module))}class ce{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var le=e=>{e.terminate(),e.onmessage=()=>{}},ue=[],de=0,fe=null,pe=e=>{F.length==0&&(we(),Ce(F[0]));var t=F.pop();if(!t)return 6;ve.push(t),be[e.Nc]=t,t.Nc=e.Nc;var n={Oc:`run`,ge:e.fe,Wc:e.Wc,Nc:e.Nc};return t.postMessage(n,e.Yc),0},me=0,he=(e,t,...n)=>{var r,i=16*n.length,a=ca(),o=sa(i),s=o>>>3;for(r of n)typeof r==`bigint`?((C(),ee)[s++>>>0]=1n,(C(),ee)[s++>>>0]=r):((C(),ee)[s++>>>0]=0n,(C(),M)[s++>>>0]=r);return e=Zi(e,0,i,o,t),oa(a),e};function P(e){if(i)return he(0,1,e);if(p=e,!(0{if(p=e,i)throw ge(e),`unwind`;P(e)},F=[],ve=[],ye=[],be={},xe=e=>{var t=e.Nc;delete be[t],F.push(e),ve.splice(ve.indexOf(e),1),e.Nc=0,Qi(t)};function Se(){ye.forEach(e=>e())}var Ce=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.Oc,i.Vc&&i.Vc!=Oi()){var a=be[i.Vc];a?a.postMessage(i,i.Yc):b(`Internal error! Worker sent a message "${r}" to target pthread ${i.Vc}, but that thread no longer exists!`)}else r===`checkMailbox`?qt():r===`spawnThread`?pe(i):r===`cleanupThread`?Wt(()=>{xe(be[i.he])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.be](...i.args):r&&b(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw b(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r,i=[];for(r of[])t.propertyIsEnumerable(r)&&i.push(r);e.postMessage({Oc:`load`,ce:i,ie:Te,je:f})});function we(){var e=new Worker((()=>{let e=URL;return import.meta.url>`file:`&&import.meta.url<`file;`?new e(`ort.webgpu.bundle.min.mjs`,import.meta.url):new URL(import.meta.url)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});F.push(e)}var Te,Ee=(e,t)=>{me=0,e=ma(e,t),0-9007199254740992>e||9007199254740992>>=0);return(C(),T)[t.Qc+12>>>0]==0&&(Ne(t,!0),Oe--),Pe(t,!1),De.push(t),fa(e)}var je=0,Me=()=>{ra(0,0);var e=De.pop();la(e.Xc),je=0};function Ne(e,t){t=+!!t,(C(),T)[e.Qc+12>>>0]=t}function Pe(e,t){t=+!!t,(C(),T)[e.Qc+13>>>0]=t}class Fe{constructor(e){this.Xc=e,this.Qc=e-24}}var Ie=e=>{var t=je;if(!t)return ia(0),0;var n=new Fe(t);(C(),A)[n.Qc+16>>>2>>>0]=t;var r=(C(),A)[n.Qc+4>>>2>>>0];if(!r)return ia(0),t;for(var i of e){if(i===0||i===r)break;if(da(i,r,n.Qc+16))return ia(i),t}return ia(r),t};function Le(){return Ie([])}function Re(e){return Ie([e>>>0])}function ze(e,t,n,r){return Ie([e>>>0,t>>>0,n>>>0,r>>>0])}var Be=()=>{var e=De.pop();e||ae(`no exception to throw`);var t=e.Xc;throw(C(),T)[e.Qc+13>>>0]==0&&(De.push(e),Pe(e,!0),Ne(e,!1),Oe++),ua(t),je=t};function Ve(e,t,n){var r=new Fe(e>>>=0);throw t>>>=0,n>>>=0,(C(),A)[r.Qc+16>>>2>>>0]=0,(C(),A)[r.Qc+4>>>2>>>0]=t,(C(),A)[r.Qc+8>>>2>>>0]=n,ua(e),Oe++,je=e}var He=()=>Oe;function Ue(e,t,n,r){return i?he(2,1,e,t,n,r):We(e,t,n,r)}function We(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?Ue(e,t,n,r):(e={fe:n,Nc:e,Wc:r,Yc:a},i?(e.Oc=`spawnThread`,postMessage(e,a),0):pe(e))}function Ge(e){throw je||=e>>>0,je}var Ke=globalThis.TextDecoder&&new TextDecoder,qe=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},Je=(e,t=0,n,r)=>{if(16<(n=qe(e,t>>>=0,n,r))-t&&e.buffer&&Ke)return Ke.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t(i=(240&i)==224?(15&i)<<12|a<<6|o:(7&i)<<18|a<<12|o<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},Ye=(e,t,n)=>(e>>>=0)?Je((C(),E),e,t,n):``;function Xe(e,t,n){return i?he(3,1,e,t,n):0}function Ze(e,t){if(i)return he(4,1,e,t)}function Qe(e,t){if(i)return he(5,1,e,t)}function $e(e,t,n){if(i)return he(6,1,e,t,n)}function et(e,t,n){return i?he(7,1,e,t,n):0}function tt(e,t){if(i)return he(8,1,e,t)}function nt(e,t,n){if(i)return he(9,1,e,t,n)}function rt(e,t,n,r){if(i)return he(10,1,e,t,n,r)}function it(e,t,n,r){if(i)return he(11,1,e,t,n,r)}function at(e,t,n,r){if(i)return he(12,1,e,t,n,r)}function ot(e){if(i)return he(13,1,e)}function st(e,t){if(i)return he(14,1,e,t)}function ct(e,t,n){if(i)return he(15,1,e,t,n)}var lt=()=>ae(``),ut=e=>{e>>>=0;for(var t=``;;){var n=(C(),E)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},dt={},ft={},pt={},mt=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function ht(e,t,n={}){return function(e,t,n={}){var r=t.name;if(!e)throw new mt(`type "${r}" must have a positive integer typeid pointer`);if(ft.hasOwnProperty(e)){if(n.de)return;throw new mt(`Cannot register type '${r}' twice`)}ft[e]=t,delete pt[e],dt.hasOwnProperty(e)&&(t=dt[e],delete dt[e],t.forEach(e=>e()))}(e,t,n)}var gt=(e,t,n)=>{switch(t){case 1:return n?e=>(C(),T)[e>>>0]:e=>(C(),E)[e>>>0];case 2:return n?e=>(C(),D)[e>>>1>>>0]:e=>(C(),O)[e>>>1>>>0];case 4:return n?e=>(C(),k)[e>>>2>>>0]:e=>(C(),A)[e>>>2>>>0];case 8:return n?e=>(C(),ee)[e>>>3>>>0]:e=>(C(),te)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function _t(e,t,n,r,i){e>>>=0,n>>>=0,t=ut(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}ht(e,{name:t,Mc:a,Sc:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),Rc:gt(t,n,!r),Tc:null})}function vt(e,t,n,r){ht(e>>>=0,{name:t=ut(t>>>0),Mc:function(e){return!!e},Sc:function(e,t){return t?n:r},Rc:function(e){return this.Mc((C(),E)[e>>>0])},Tc:null})}var yt=[],bt=[0,1,,1,null,1,!0,1,!1,1];function xt(e){9<(e>>>=0)&&--bt[e+1]==0&&(bt[e]=void 0,yt.push(e))}var St=e=>{if(!e)throw new mt(`Cannot use deleted val. handle = ${e}`);return bt[e]},Ct=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=yt.pop()||bt.length;return bt[t]=e,bt[t+1]=1,t}};function wt(e){return this.Mc((C(),A)[e>>>2>>>0])}var Tt={name:`emscripten::val`,Mc:e=>{var t=St(e);return xt(e),t},Sc:(e,t)=>Ct(t),Rc:wt,Tc:null};function Et(e){return ht(e>>>0,Tt)}var Dt=(e,t)=>{switch(t){case 4:return function(e){return this.Mc((C(),j)[e>>>2>>>0])};case 8:return function(e){return this.Mc((C(),M)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function Ot(e,t,n){n>>>=0,ht(e>>>=0,{name:t=ut(t>>>0),Mc:e=>e,Sc:(e,t)=>t,Rc:Dt(t,n),Tc:null})}function kt(e,t,n,r,i){e>>>=0,n>>>=0,t=ut(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<>>o,i=a(i)}ht(e,{name:t,Mc:a,Sc:(e,t)=>t,Rc:gt(t,n,r!==0),Tc:null})}function At(e,t,n){function r(e){var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],new i((C(),T).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];ht(e>>>=0,{name:n=ut(n>>>0),Mc:r,Rc:r},{de:!0})}var jt=(e,t,n)=>{var r=(C(),E);if(t>>>=0,0=o){if(t>=n)break;r[t++>>>0]=o}else if(2047>=o){if(t+1>=n)break;r[t++>>>0]=192|o>>6,r[t++>>>0]=128|63&o}else if(65535>=o){if(t+2>=n)break;r[t++>>>0]=224|o>>12,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o}else{if(t+3>=n)break;r[t++>>>0]=240|o>>18,r[t++>>>0]=128|o>>12&63,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o,a++}}r[t>>>0]=0,e=t-i}else e=0;return e},Mt=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function Nt(e,t){ht(e>>>=0,{name:t=ut(t>>>0),Mc(e){var t=(C(),A)[e>>>2>>>0];return t=Ye(e+4,t,!0),ki(e),t},Sc(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var n=typeof t==`string`;if(!(n||ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT==1))throw new mt(`Cannot pass non-string to std::string`);var r=n?Mt(t):t.length,i=Ai(4+r+1),a=i+4;return(C(),A)[i>>>2>>>0]=r,n?jt(t,a,r+1):(C(),E).set(t,a>>>0),e!==null&&e.push(ki,i),i},Rc:wt,Tc(e){ki(e)}})}var Pt=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,Ft=(e,t,n)=>{if(e>>>=1,16<(t=qe((C(),O),e,t/2,n))-e&&Pt)return Pt.decode((C(),O).slice(e,t));for(n=``;e>>0];n+=String.fromCharCode(r)}return n},It=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var i=0;i>>1>>>0]=a,t+=2}return(C(),D)[t>>>1>>>0]=0,t-r},Lt=e=>2*e.length,Rt=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(C(),A)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},zt=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i>>2>>>0]=a,(t+=4)+4>n)break}return(C(),k)[t>>>2>>>0]=0,t-r},Bt=e=>{for(var t=0,n=0;n>>=0,t>>>=0,n=ut(n>>>=0),t===2)var r=Ft,i=It,a=Lt;else r=Rt,i=zt,a=Bt;ht(e,{name:n,Mc:e=>{var n=(C(),A)[e>>>2>>>0];return n=r(e+4,n*t,!0),ki(e),n},Sc:(e,r)=>{if(typeof r!=`string`)throw new mt(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=Ai(4+o+t);return(C(),A)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(ki,s),s},Rc:wt,Tc(e){ki(e)}})}function Ht(e,t){ht(e>>>=0,{ee:!0,name:t=ut(t>>>0),Mc:()=>{},Sc:()=>{}})}function Ut(e){Yi(e>>>0,!r,1,!n,131072,!1),Se()}var Wt=e=>{if(!x)try{if(e(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Kt(e){e>>>=0,Gt||(Atomics.waitAsync((C(),k),e>>>2,e).value.then(qt),e+=128,Atomics.store((C(),k),e>>>2,1))}var qt=()=>Wt(()=>{var e=Oi();e&&(Kt(e),ta())});function Jt(e,t){(e>>>=0)==t>>>0?setTimeout(qt):i?postMessage({Vc:e,Oc:`checkMailbox`}):(e=be[e])&&e.postMessage({Oc:`checkMailbox`})}var Yt=[];function Xt(e,t,n,r,i){for(t>>>=0,i>>>=0,Yt.length=0,n=i>>>3,r=i+r>>>3;n>>0]?(C(),ee)[n++>>>0]:(C(),M)[n++>>>0];Yt.push(a)}return(t?to[t]:eo[e])(...Yt)}var Zt=()=>{me=0};function Qt(e){e>>>=0,i?postMessage({Oc:`cleanupThread`,he:e}):xe(be[e])}function $t(e){}var en=e=>{try{e()}catch(e){ae(e)}};function tn(e){var t=(...t)=>{on.push(e);try{return e(...t)}finally{x||(on.pop(),rn&&nn===1&&on.length===0&&(nn=0,me+=1,en(Xa),typeof Fibers<`u`&&Fibers.Be()))}};return ln.set(e,t),t}var nn=0,rn=null,an=0,on=[],sn=new Map,cn=new Map,ln=new Map,un=0,dn=null,fn=[],pn=e=>function(e){if(!x){if(nn===0){var t=!1,n=!1;e((e=0)=>{if(!x&&(an=e,t=!0,n)){nn=2,en(()=>Za(rn)),typeof MainLoop<`u`&&MainLoop.Xd&&MainLoop.resume(),e=!1;try{var r=function(){var e=(C(),k)[rn+8>>>2>>>0];return e=cn.get(e),e=ln.get(e),--me,e()}()}catch(t){r=t,e=!0}var i=!1;if(!rn){var a=dn;a&&(dn=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(nn=1,rn=function(){var e=Ai(65548),t=e+12;if((C(),A)[e>>>2>>>0]=t,(C(),A)[e+4>>>2>>>0]=t+65536,t=on[0],!sn.has(t)){var n=un++;sn.set(t,n),cn.set(n,t)}return t=sn.get(t),(C(),k)[e+8>>>2>>>0]=t,e}(),typeof MainLoop<`u`&&MainLoop.Xd&&MainLoop.pause(),en(()=>Ya(rn)))}else nn===2?(nn=0,en(Qa),ki(rn),rn=null,fn.forEach(Wt)):ae(`invalid state: ${nn}`);return an}}(t=>{e().then(t)});function mn(e){return e>>>=0,pn(async()=>Ct(await St(e)))}var hn=[],gn=e=>{var t=hn.length;return hn.push(e),t},_n=(e,t)=>{for(var n=Array(e),r=0;r>>2>>>0],o=ft[a];if(o===void 0)throw e=`parameter ${r}`,a=Ti(a),t=ut(a),ki(a),new mt(`${e} has unknown type ${t}`);n[i]=o}return n},vn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((C(),A)[t>>>2>>>0]=Ct(r)),e},yn={},bn=e=>{var t=yn[e];return t===void 0?ut(e):t};function xn(e,t,n){var[r,...i]=_n(e,t>>>0);t=r.Sc.bind(r);var a=i.map(e=>e.Rc.bind(e));e--;var o={toValue:St};switch(e=a.map((e,t)=>{var n=`argFromPtr${t}`;return o[n]=e,`${n}(args${t?`+`+8*t:``})`}),n){case 0:var s=`toValue(handle)`;break;case 2:s=`new (toValue(handle))`;break;case 3:s=``;break;case 1:o.getStringOrSymbol=bn,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.ee||(o.toReturnWire=t,o.emval_returnValue=vn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) { + ${s} + }`,n=Function(Object.keys(o),s)(...Object.values(o)),s=`methodCaller<(${i.map(e=>e.name)}) => ${r.name}>`,gn(Object.defineProperty(n,"name",{value:s}))}function Sn(e,t){return t>>>=0,(e=St(e>>>0))==St(t)}function Cn(e){return(e>>>=0)?(e=bn(e),Ct(globalThis[e])):Ct(globalThis)}function wn(e){return e=bn(e>>>0),Ct(t[e])}function Tn(e,t){return t>>>=0,e=St(e>>>0),t=St(t),Ct(e[t])}function En(e){9<(e>>>=0)&&(bt[e+1]+=1)}function Dn(e,t,n,r,i){return hn[e>>>0](t>>>0,n>>>0,r>>>0,i>>>0)}function On(e,t,n,r,i){return Dn(e>>>0,t>>>0,n>>>0,r>>>0,i>>>0)}function kn(){return Ct([])}function An(e){e=St(e>>>0);for(var t=Array(e.length),n=0;n>>0))}function Mn(){return Ct({})}function Nn(e){for(var t=St(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}xt(e)}function Pn(e,t,n){t>>>=0,n>>>=0,e=St(e>>>0),t=St(t),n=St(n),e[t]=n}function Fn(e,t){e=ke(e),t>>>=0,e=new Date(1e3*e),(C(),k)[t>>>2>>>0]=e.getUTCSeconds(),(C(),k)[t+4>>>2>>>0]=e.getUTCMinutes(),(C(),k)[t+8>>>2>>>0]=e.getUTCHours(),(C(),k)[t+12>>>2>>>0]=e.getUTCDate(),(C(),k)[t+16>>>2>>>0]=e.getUTCMonth(),(C(),k)[t+20>>>2>>>0]=e.getUTCFullYear()-1900,(C(),k)[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(C(),k)[t+28>>>2>>>0]=e}var In=e=>e%4==0&&(e%100!=0||e%400==0),Ln=[0,31,60,91,121,152,182,213,244,274,305,335],Rn=[0,31,59,90,120,151,181,212,243,273,304,334];function zn(e,t){e=ke(e),t>>>=0,e=new Date(1e3*e),(C(),k)[t>>>2>>>0]=e.getSeconds(),(C(),k)[t+4>>>2>>>0]=e.getMinutes(),(C(),k)[t+8>>>2>>>0]=e.getHours(),(C(),k)[t+12>>>2>>>0]=e.getDate(),(C(),k)[t+16>>>2>>>0]=e.getMonth(),(C(),k)[t+20>>>2>>>0]=e.getFullYear()-1900,(C(),k)[t+24>>>2>>>0]=e.getDay();var n=(In(e.getFullYear())?Ln:Rn)[e.getMonth()]+e.getDate()-1|0;(C(),k)[t+28>>>2>>>0]=n,(C(),k)[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),(C(),k)[t+32>>>2>>>0]=e}function Bn(e){e>>>=0;var t=new Date((C(),k)[e+20>>>2>>>0]+1900,(C(),k)[e+16>>>2>>>0],(C(),k)[e+12>>>2>>>0],(C(),k)[e+8>>>2>>>0],(C(),k)[e+4>>>2>>>0],(C(),k)[e>>>2>>>0],0),n=(C(),k)[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?(C(),k)[e+32>>>2>>>0]=+(i!=a&&o==r):0>>2>>>0]=t.getDay(),n=(In(t.getFullYear())?Ln:Rn)[t.getMonth()]+t.getDate()-1|0,(C(),k)[e+28>>>2>>>0]=n,(C(),k)[e>>>2>>>0]=t.getSeconds(),(C(),k)[e+4>>>2>>>0]=t.getMinutes(),(C(),k)[e+8>>>2>>>0]=t.getHours(),(C(),k)[e+12>>>2>>>0]=t.getDate(),(C(),k)[e+16>>>2>>>0]=t.getMonth(),(C(),k)[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function Vn(e,t,n,r,a,o,s){return i?he(16,1,e,t,n,r,a,o,s):-52}function Hn(e,t,n,r,a,o){if(i)return he(17,1,e,t,n,r,a,o)}var Un={},Wn=()=>performance.timeOrigin+performance.now();function Gn(e,t){return i?he(18,1,e,t):(Un[e]&&(clearTimeout(Un[e].id),delete Un[e]),t&&(Un[e]={id:setTimeout(()=>{delete Un[e],Wt(()=>ea(e,performance.timeOrigin+performance.now()))},t),Ae:t}),0)}function Kn(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=new Date().getFullYear(),a=new Date(i,0,1).getTimezoneOffset();i=new Date(i,6,1).getTimezoneOffset();var o=Math.max(a,i);(C(),A)[e>>>2>>>0]=60*o,(C(),k)[t>>>2>>>0]=+(a!=i),e=(t=e=>{var t=Math.abs(e);return`UTC${0<=e?`-`:`+`}${String(Math.floor(t/60)).padStart(2,`0`)}${String(t%60).padStart(2,`0`)}`})(a),t=t(i),iDate.now(),Jn=1;function Yn(e,t,n){if(n>>>=0,!(0<=e&&3>=e))return 28;if(e===0)e=Date.now();else{if(!Jn)return 52;e=performance.timeOrigin+performance.now()}return e=Math.round(1e6*e),(C(),ee)[n>>>3>>>0]=BigInt(e),0}var Xn=[],Zn=(e,t)=>{Xn.length=0;for(var n;n=(C(),E)[e++>>>0];){var r=n!=105;t+=(r&=n!=112)&&t%8?4:0,Xn.push(n==112?(C(),A)[t>>>2>>>0]:n==106?(C(),ee)[t>>>3>>>0]:n==105?(C(),k)[t>>>2>>>0]:(C(),M)[t>>>3>>>0]),t+=r?8:4}return Xn};function Qn(e,t,n){return e>>>=0,t=Zn(t>>>0,n>>>0),to[e](...t)}function $n(e,t,n){return e>>>=0,t=Zn(t>>>0,n>>>0),to[e](...t)}var er=()=>{};function tr(e,t){return b(Ye(e>>>0,t>>>0))}var nr=()=>{throw me+=1,`unwind`};function rr(){return 4294901760}var ir=()=>1,ar=()=>navigator.hardwareConcurrency;function or(e){e>>>=0;var t=(C(),E).length;if(e<=t||4294901760=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);e:{r=(Math.min(4294901760,65536*Math.ceil(Math.max(e,r)/65536))-Te.buffer.byteLength+65535)/65536|0;try{Te.grow(r),re();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1}var sr=e=>{var t=Mt(e)+1,n=sa(t);return jt(e,n,t),n},cr=(e,t)=>{(C(),A)[e>>>2>>>0]=t;var n=(C(),A)[e>>>2>>>0];(C(),A)[e+4>>>2>>>0]=(t-n)/4294967296},lr=e=>(C(),A)[e>>>2>>>0]+4294967296*(C(),k)[e+4>>>2>>>0],ur=[],dr=(e,t)=>{ur[e>>>0]=t},fr=[],pr=[],mr=(e,t)=>{pr[e]=new Promise(n=>t.finally(()=>n(e)))},hr=e=>{if(e)return ur[e>>>0]},gr=(e,t)=>{for(e=(C(),A)[e>>>2>>>0];e;e=(C(),A)[e>>>2>>>0])t[(C(),k)[e+4>>>2>>>0]](e)},_r=(e,t,n)=>{(C(),A)[e>>>2>>>0]=t,(C(),A)[e+4>>>2>>>0]=n},vr=e=>{var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],Ye(t,e)},yr=e=>{var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],t?Ye(t,e):e===0?``:void 0},br=e=>{var t=yr(e+4),n=(n=(C(),A)[e+12>>>2>>>0])?hr(n):`auto`;if(e+=16){var r=hr((C(),A)[e+4>>>2>>>0]),i=(C(),A)[e+16>>>2>>>0],a=(C(),A)[e+20>>>2>>>0];if(i){for(var o={},s=0;s>>3>>>0]}i=o}else i=void 0;e={module:r,constants:i,entryPoint:yr(e+8)}}else e=void 0;return{label:t,layout:n,compute:e}},xr=(e,t)=>{function n(n,r){n=e[n],(C(),A)[t+r>>>2>>>0]=n}n(`maxTextureDimension1D`,4),n(`maxTextureDimension2D`,8),n(`maxTextureDimension3D`,12),n(`maxTextureArrayLayers`,16),n(`maxBindGroups`,20),n(`maxBindGroupsPlusVertexBuffers`,24),n(`maxBindingsPerBindGroup`,28),n(`maxDynamicUniformBuffersPerPipelineLayout`,32),n(`maxDynamicStorageBuffersPerPipelineLayout`,36),n(`maxSampledTexturesPerShaderStage`,40),n(`maxSamplersPerShaderStage`,44),n(`maxStorageBuffersPerShaderStage`,48),n(`maxStorageTexturesPerShaderStage`,52),n(`maxUniformBuffersPerShaderStage`,56),n(`minUniformBufferOffsetAlignment`,80),n(`minStorageBufferOffsetAlignment`,84),cr(t+64,e.maxUniformBufferBindingSize),cr(t+72,e.maxStorageBufferBindingSize),n(`maxVertexBuffers`,88),cr(t+96,e.maxBufferSize),n(`maxVertexAttributes`,104),n(`maxVertexBufferArrayStride`,108),n(`maxInterStageShaderVariables`,112),n(`maxColorAttachments`,116),n(`maxColorAttachmentBytesPerSample`,120),n(`maxComputeWorkgroupStorageSize`,124),n(`maxComputeInvocationsPerWorkgroup`,128),n(`maxComputeWorkgroupSizeX`,132),n(`maxComputeWorkgroupSizeY`,136),n(`maxComputeWorkgroupSizeZ`,140),n(`maxComputeWorkgroupsPerDimension`,144),e.ze!==void 0&&n(`maxImmediateSize`,148)},Sr=[,`validation`,`out-of-memory`,`internal`],Cr=[,`compatibility`,`core`],wr={1:`core-features-and-limits`,2:`depth-clip-control`,3:`depth32float-stencil8`,4:`texture-compression-bc`,5:`texture-compression-bc-sliced-3d`,6:`texture-compression-etc2`,7:`texture-compression-astc`,8:`texture-compression-astc-sliced-3d`,9:`timestamp-query`,10:`indirect-first-instance`,11:`shader-f16`,12:`rg11b10ufloat-renderable`,13:`bgra8unorm-storage`,14:`float32-filterable`,15:`float32-blendable`,16:`clip-distances`,17:`dual-source-blending`,18:`subgroups`,19:`texture-formats-tier1`,20:`texture-formats-tier2`,21:`primitive-index`,22:`texture-component-swizzle`,327692:`chromium-experimental-unorm16-texture-formats`,327729:`chromium-experimental-multi-draw-indirect`},Tr=[,`low-power`,`high-performance`],Er=[,`occlusion`,`timestamp`],Dr={undefined:1,unknown:1,destroyed:2};function Or(e,t,n,r,i,a){t=ke(t),n=ke(n),r>>>=0,i>>>=0,a>>>=0;var o=hr(e>>>0);if(e={},a){var s=(C(),A)[a+12>>>2>>>0];if(s){var c=(C(),A)[a+16>>>2>>>0];e.requiredFeatures=Array.from((C(),A).subarray(c>>>2>>>0,c+4*s>>>2>>>0),e=>wr[e])}var l=(C(),A)[a+20>>>2>>>0];if(l){let t=function(e,t,n=!1){t=l+t,(t=(C(),A)[t>>>2>>>0])==4294967295||n&&t==0||(u[e]=t)},n=function(e,t){t=l+t;var n=(C(),A)[t>>>2>>>0],r=(C(),A)[t+4>>>2>>>0];n==4294967295&&r==4294967295||(u[e]=lr(t))};var u={};t(`maxTextureDimension1D`,4),t(`maxTextureDimension2D`,8),t(`maxTextureDimension3D`,12),t(`maxTextureArrayLayers`,16),t(`maxBindGroups`,20),t(`maxBindGroupsPlusVertexBuffers`,24),t(`maxDynamicUniformBuffersPerPipelineLayout`,32),t(`maxDynamicStorageBuffersPerPipelineLayout`,36),t(`maxSampledTexturesPerShaderStage`,40),t(`maxSamplersPerShaderStage`,44),t(`maxStorageBuffersPerShaderStage`,48),t(`maxStorageTexturesPerShaderStage`,52),t(`maxUniformBuffersPerShaderStage`,56),t(`minUniformBufferOffsetAlignment`,80),t(`minStorageBufferOffsetAlignment`,84),n(`maxUniformBufferBindingSize`,64),n(`maxStorageBufferBindingSize`,72),t(`maxVertexBuffers`,88),n(`maxBufferSize`,96),t(`maxVertexAttributes`,104),t(`maxVertexBufferArrayStride`,108),t(`maxInterStageShaderVariables`,112),t(`maxColorAttachments`,116),t(`maxColorAttachmentBytesPerSample`,120),t(`maxComputeWorkgroupStorageSize`,124),t(`maxComputeInvocationsPerWorkgroup`,128),t(`maxComputeWorkgroupSizeX`,132),t(`maxComputeWorkgroupSizeY`,136),t(`maxComputeWorkgroupSizeZ`,140),t(`maxComputeWorkgroupsPerDimension`,144),t(`maxImmediateSize`,148,!0),e.requiredLimits=u}(s=(C(),A)[a+24>>>2>>>0])&&(s={label:yr(s+4)},e.defaultQueue=s),e.label=yr(a+4)}me+=1,mr(t,o.requestDevice(e).then(e=>{--me,Wt(()=>{ur[i>>>0]=e.queue,ur[r>>>0]=e,me+=1,mr(n,e.lost.then(t=>{Wt(()=>{e.onuncapturederror=()=>{};var r=ca(),i=sr(t.message);Ui(n,Dr[t.reason],i),oa(r)}),--me})),e.onuncapturederror=e=>{var t=5;e.error instanceof GPUValidationError?t=2:e.error instanceof GPUOutOfMemoryError?t=3:e.error instanceof GPUInternalError&&(t=4);var n=ca();e=sr(e.error.message),Ji(r,t,e),oa(n)},`adapterInfo`in e||(e.adapterInfo=o.info),qi(t,1,r,0)})},e=>{--me,Wt(()=>{var i=ca(),a=sr(e.message);qi(t,3,r,a),n&&Ui(n,4,a),oa(i)})}))}function kr(e){var t=hr(e>>>=0),n=fr[e];if(n){for(var r=0;r>>=0;var r=hr(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=na(16,i.byteLength);return(C(),E).set(new Uint8Array(i),a>>>0),fr[e].push(()=>ki(a)),a}function jr(e,t,n){n>>>=0;var r=hr(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=na(16,i.byteLength);return(C(),E).fill(0,a,i.byteLength),fr[e].push(()=>{new Uint8Array(i).set((C(),E).subarray(a>>>0,a+i.byteLength>>>0)),ki(a)}),a}function Mr(e,t,n,r,i){e>>>=0,t=ke(t),n=ke(n),i>>>=0;var a=hr(e);fr[e]=[],i==4294967295&&(i=void 0),me+=1,mr(t,a.mapAsync(n,r>>>0,i).then(()=>{--me,Wt(()=>{Wi(t,1,0)})},n=>{--me,Wt(()=>{ca();var r=sr(n.message);Wi(t,n.name===`AbortError`?4:n.name===`OperationError`?3:0,r),delete fr[e]})}))}function Nr(e){var t=hr(e>>>=0),n=fr[e];if(n){for(var r=0;r>>0]}function Fr(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=!!(C(),A)[t+32>>>2>>>0];t={label:yr(t+4),usage:(C(),A)[t+16>>>2>>>0],size:lr(t+24),mappedAtCreation:r},e=hr(e);try{var i=e.createBuffer(t)}catch{return!1}return ur[n>>>0]=i,r&&(fr[n]=[]),!0}function Ir(e,t,n,r){e>>>=0,t=ke(t),r>>>=0,n=br(n>>>0),e=hr(e),me+=1,mr(t,e.createComputePipelineAsync(n).then(e=>{--me,Wt(()=>{ur[r>>>0]=e,Hi(t,1,r,0)})},e=>{--me,Wt(()=>{var n=ca(),i=sr(e.message);Hi(t,e.reason===`validation`?3:e.reason===`internal`?4:0,r,i),oa(n)})}))}function Lr(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=(C(),A)[t>>>2>>>0],i=(C(),k)[r+4>>>2>>>0];t={label:yr(t+4),code:``},i===2&&(t.code=vr(r+8)),e=hr(e).createShaderModule(t),ur[n>>>0]=e}var Rr=e=>{(e=hr(e)).onuncapturederror=null,e.destroy()};function zr(e,t){t=ke(t),e=hr(e>>>0),me+=1,mr(t,e.popErrorScope().then(e=>{--me,Wt(()=>{var n=5;e?e instanceof GPUValidationError?n=2:e instanceof GPUOutOfMemoryError?n=3:e instanceof GPUInternalError&&(n=4):n=1;var r=ca(),i=e?sr(e.message):0;Gi(t,1,n,i),oa(r)})},e=>{--me,Wt(()=>{var n=ca(),r=sr(e.message);Gi(t,1,5,r),oa(n)})}))}function Br(e,t,n,r){if(t=ke(t),r>>>=0,n>>>=0){var i={featureLevel:Cr[(C(),k)[n+4>>>2>>>0]],powerPreference:Tr[(C(),k)[n+8>>>2>>>0]],forceFallbackAdapter:!!(C(),A)[n+12>>>2>>>0]};(e=(C(),A)[n>>>2>>>0])!==0&&(C(),i.De=!!(C(),A)[e+8>>>2>>>0])}`gpu`in navigator?(me+=1,mr(t,navigator.gpu.requestAdapter(i).then(e=>{--me,Wt(()=>{if(e)ur[r>>>0]=e,Ki(t,1,r,0);else{var n=ca(),i=sr(`WebGPU not available on this browser (requestAdapter returned null)`);Ki(t,3,r,i),oa(n)}})},e=>{--me,Wt(()=>{var n=ca(),i=sr(e.message);Ki(t,4,r,i),oa(n)})}))):(i=ca(),e=sr(`WebGPU not available on this browser (navigator.gpu is not available)`),Ki(t,3,r,e),oa(i))}function Vr(e,t,n){return e>>>=0,t>>>=0,n>>>=0,pn(async()=>{var r=[];if(n){var i=(C(),k)[n>>>2>>>0];r.length=t+1,r[t]=new Promise(e=>setTimeout(e,i,0))}else r.length=t;for(var a=0;a{if(!Hr){var e,t={USER:`web_user`,LOGNAME:`web_user`,PATH:`/`,PWD:`/`,HOME:`/home/web_user`,LANG:(globalThis.navigator?.language??`C`).replace(`-`,`_`)+`.UTF-8`,_:`./this.program`};for(e in Ur)Ur[e]===void 0?delete t[e]:t[e]=Ur[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);Hr=n}return Hr};function Gr(e,t){if(i)return he(19,1,e,t);e>>>=0,t>>>=0;var n,r=0,a=0;for(n of Wr()){var o=t+r;(C(),A)[e+a>>>2>>>0]=o,r+=jt(n,o,1/0)+1,a+=4}return 0}function Kr(e,t){if(i)return he(20,1,e,t);e>>>=0,t>>>=0;var n=Wr();for(var r of((C(),A)[e>>>2>>>0]=n.length,e=0,n))e+=Mt(r)+1;return(C(),A)[t>>>2>>>0]=e,0}function qr(e){return i?he(21,1,e):52}function Jr(e,t,n,r){return i?he(22,1,e,t,n,r):52}function Yr(e,t,n,r){return i?he(23,1,e,t,n,r):70}var Xr=[null,[],[]];function Zr(e,t,n,r){if(i)return he(24,1,e,t,n,r);t>>>=0,n>>>=0,r>>>=0;for(var a=0,o=0;o>>2>>>0],c=(C(),A)[t+4>>>2>>>0];t+=8;for(var l=0;l>>0],f=Xr[u];d===0||d===10?((u===1?y:b)(Je(f)),f.length=0):f.push(d)}a+=c}return(C(),A)[r>>>2>>>0]=a,0}function Qr(e){return e>>>0}function $r(e,t){return xr(hr(e>>>0).limits,t>>>0),1}function ei(e,t){return hr(e>>>0).features.has(wr[t])}function ti(e){return BigInt(hr(e>>>0).size)}function ni(e){return BigInt(hr(e>>>0).usage)}function ri(e,t){if(e>>>=0,t>>>=0){var n=yr(t+4);n={label:n,timestampWrites:t=(t=(C(),A)[t+12>>>2>>>0])===0?void 0:{querySet:hr((C(),A)[t+4>>>2>>>0]),beginningOfPassWriteIndex:(C(),A)[t+8>>>2>>>0],endOfPassWriteIndex:(C(),A)[t+12>>>2>>>0]}}}return t=hr(e),e=Li(0),n=t.beginComputePass(n),ur[e>>>0]=n,e}function ii(e,t,n,r){n=ke(n),(r=ke(r))==-1&&(r=void 0),(e=hr(e>>>0)).clearBuffer(hr(t>>>0),n,r)}function ai(e,t,n,r,i,a){n=ke(n),i=ke(i),a=ke(a),hr(e>>>0).copyBufferToBuffer(hr(t>>>0),n,hr(r>>>0),i,a)}function oi(e){var t=hr(e>>>0);return e=Fi(0),t=t.finish(),ur[e>>>0]=t,e}function si(e,t,n,r,i,a){a=ke(a),hr(e>>>0).resolveQuerySet(hr(t>>>0),n,r,hr(i>>>0),a)}function ci(e,t,n,r){hr(e>>>0).dispatchWorkgroups(t,n,r)}function li(e,t,n){n=ke(n),hr(e>>>0).dispatchWorkgroupsIndirect(hr(t>>>0),n)}function ui(e){hr(e>>>0).end()}function di(e,t,n,r,i){r>>>=0,i>>>=0,e=hr(e>>>0),n=hr(n>>>0),r==0?e.setBindGroup(t,n):e.setBindGroup(t,n,(C(),A),i>>>2,r)}function fi(e,t){hr(e>>>0).setPipeline(hr(t>>>0))}function pi(e,t,n){hr(e>>>0).Ce(hr(t>>>0),n)}function mi(e,t){var n=hr(e>>>0);return e=Pi(0),t=n.getBindGroupLayout(t),ur[e>>>0]=t,e}function hi(e,t){function n(e){var t=(C(),A)[e+8>>>2>>>0],n=(C(),A)[e+32>>>2>>>0],r=(C(),A)[e+36>>>2>>>0],i=0;return gr(e,{327681:e=>{i=(C(),A)[e+8>>>2>>>0]}}),t?((n=lr(e+24))==-1&&(n=void 0),t={buffer:hr(t),offset:lr(e+16),size:n}):t=hr(n||r||i),{binding:(C(),A)[e+4>>>2>>>0],resource:t}}e>>>=0,t={label:yr(4+(t>>>=0)),layout:hr((C(),A)[t+12>>>2>>>0]),entries:function(e,t){for(var r=[],i=0;i>>2>>>0],(C(),A)[t+20>>>2>>>0])},e=hr(e);var r=Ni(0);return dr(r,e.createBindGroup(t)),r}function gi(e,t){var n;return e>>>=0,(t>>>=0)&&(n={label:yr(t+4)}),t=hr(e),e=Ii(0),n=t.createCommandEncoder(n),ur[e>>>0]=n,e}function _i(e,t){e>>>=0,t>>>=0,t={type:Er[(C(),k)[t+12>>>2>>>0]],count:(C(),A)[t+16>>>2>>>0]};var n=hr(e);return e=Ri(0),t=n.createQuerySet(t),ur[e>>>0]=t,e}function vi(e,t){e=hr(e>>>0).adapterInfo,t>>>=0,(C(),A)[t+52>>>2>>>0]=e.subgroupMinSize,(C(),A)[t+56>>>2>>>0]=e.subgroupMaxSize;var n=e.vendor+e.architecture+e.device+e.description,r=Mt(n)+1,i=Ai(r);return i&&jt(n,i,r),n=i,r=Mt(e.vendor),_r(t+4,n,r),n+=r,r=Mt(e.architecture),_r(t+12,n,r),n+=r,r=Mt(e.device),_r(t+20,n,r),_r(t+28,n+r,Mt(e.description)),(C(),k)[t+36>>>2>>>0]=2,e=e.isFallbackAdapter?3:4,(C(),k)[t+40>>>2>>>0]=e,(C(),A)[t+44>>>2>>>0]=0,(C(),A)[t+48>>>2>>>0]=0,1}var yi={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function bi(e,t){t>>>=0;var n=hr(e>>>0);e=Ai(4*n.features.size);var r=0,i=0;for(let t of n.features)0<=(n=yi[t])&&((C(),k)[e+r>>>2>>>0]=n,r+=4,i++);(C(),A)[t+4>>>2>>>0]=e,(C(),A)[t>>>2>>>0]=i}function xi(e,t){return xr(hr(e>>>0).limits,t>>>0),1}function Si(e,t){hr(e>>>0).pushErrorScope(Sr[t])}function Ci(e,t,n){t>>>=0,n>>>=0,e=hr(e>>>0),t=Array.from((C(),k).subarray(n>>>2>>>0,n+4*t>>>2>>>0),e=>hr(e)),e.submit(t)}function wi(e,t,n,r,i){n=ke(n),r>>>=0,i>>>=0,e=hr(e>>>0),t=hr(t>>>0),r=(C(),E).subarray(r>>>0,r+i>>>0),e.writeBuffer(t,n,r,0,i)}i||function(){for(var e=t.numThreads-1;e--;)we();ue.push(async()=>{var e=async function(){if(!i)return Promise.all(F.map(Ce))}();de++,await e,--de==0&&fe&&(e=fe,fe=null,e())})}(),i||(Te=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),re()),t.wasmBinary&&(d=t.wasmBinary),t.stackSave=()=>ca(),t.stackRestore=e=>oa(e),t.stackAlloc=e=>sa(e),t.setValue=function(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:case`i8`:(C(),T)[e>>>0]=t;break;case`i16`:(C(),D)[e>>>1>>>0]=t;break;case`i32`:(C(),k)[e>>>2>>>0]=t;break;case`i64`:(C(),ee)[e>>>3>>>0]=BigInt(t);break;case`float`:(C(),j)[e>>>2>>>0]=t;break;case`double`:(C(),M)[e>>>3>>>0]=t;break;case`*`:(C(),A)[e>>>2>>>0]=t;break;default:ae(`invalid type for setValue: ${n}`)}},t.getValue=function(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:case`i8`:return(C(),T)[e>>>0];case`i16`:return(C(),D)[e>>>1>>>0];case`i32`:return(C(),k)[e>>>2>>>0];case`i64`:return(C(),ee)[e>>>3>>>0];case`float`:return(C(),j)[e>>>2>>>0];case`double`:return(C(),M)[e>>>3>>>0];case`*`:return(C(),A)[e>>>2>>>0];default:ae(`invalid type for getValue: ${t}`)}},t.UTF8ToString=Ye,t.stringToUTF8=jt,t.lengthBytesUTF8=Mt;var Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja,Ya,Xa,Za,Qa,$a,eo=[P,ge,Ue,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at,ot,st,ct,Vn,Hn,Gn,Gr,Kr,qr,Jr,Yr,Zr],to={970348:(e,n,r,i,a)=>{if(t===void 0||!t.Uc)return 1;if((e=Ye(Number(e>>>0))).startsWith(`./`)&&(e=e.substring(2)),!(e=t.Uc.get(e)))return 2;if(n=Number(n>>>0),r=Number(r>>>0),i=Number(i>>>0),n+r>e.byteLength)return 3;try{let o=e.subarray(n,n+r);switch(a){case 0:(C(),E).set(o,i>>>0);break;case 1:t.ad?t.ad(i,o):t.ne(i,o);break;default:return 4}return 0}catch{return 4}},971172:(e,n,r)=>{t.Sd(e,(C(),E).subarray(n>>>0,n+r>>>0))},971236:()=>t.le(),971278:e=>{t.jd(e)},971315:()=>typeof wasmOffsetConverter<`u`};function no(e,t,n,r){var i=ca();try{return Sa(e,t,n,r)}catch(e){if(oa(i),e!==e+0)throw e;ra(1,0)}}function ro(e,t,n){var r=ca();try{return ya(e,t,n)}catch(e){if(oa(r),e!==e+0)throw e;ra(1,0)}}function io(e){var t=ca();try{ha(e)}catch(e){if(oa(t),e!==e+0)throw e;ra(1,0)}}function ao(e,t){var n=ca();try{return ma(e,t)}catch(e){if(oa(n),e!==e+0)throw e;ra(1,0)}}function oo(e,t,n){var r=ca();try{pa(e,t,n)}catch(e){if(oa(r),e!==e+0)throw e;ra(1,0)}}function so(e,t){var n=ca();try{Ca(e,t)}catch(e){if(oa(n),e!==e+0)throw e;ra(1,0)}}function co(e,t,n,r,i,a,o){var s=ca();try{return va(e,t,n,r,i,a,o)}catch(e){if(oa(s),e!==e+0)throw e;ra(1,0)}}function lo(e,t,n,r,i,a){var o=ca();try{ga(e,t,n,r,i,a)}catch(e){if(oa(o),e!==e+0)throw e;ra(1,0)}}function uo(e,t,n,r){var i=ca();try{xa(e,t,n,r)}catch(e){if(oa(i),e!==e+0)throw e;ra(1,0)}}function fo(e,t,n,r,i,a,o){var s=ca();try{Ta(e,t,n,r,i,a,o)}catch(e){if(oa(s),e!==e+0)throw e;ra(1,0)}}function po(e,t,n,r,i,a,o){var s=ca();try{Ea(e,t,n,r,i,a,o)}catch(e){if(oa(s),e!==e+0)throw e;ra(1,0)}}function mo(e,t,n,r,i,a,o,s){var c=ca();try{Fa(e,t,n,r,i,a,o,s)}catch(e){if(oa(c),e!==e+0)throw e;ra(1,0)}}function ho(e,t,n,r,i,a,o,s,c,l,u,d){var f=ca();try{Da(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(oa(f),e!==e+0)throw e;ra(1,0)}}function go(e,t,n,r,i){var a=ca();try{return wa(e,t,n,r,i)}catch(e){if(oa(a),e!==e+0)throw e;ra(1,0)}}function _o(e,t,n,r,i){var a=ca();try{_a(e,t,n,r,i)}catch(e){if(oa(a),e!==e+0)throw e;ra(1,0)}}function vo(e,t,n,r,i,a,o,s){var c=ca();try{ba(e,t,n,r,i,a,o,s)}catch(e){if(oa(c),e!==e+0)throw e;ra(1,0)}}function yo(e){var t=ca();try{return Ia(e)}catch(e){if(oa(t),e!==e+0)throw e;ra(1,0)}}function bo(e,t,n){var r=ca();try{return La(e,t,n)}catch(e){if(oa(r),e!==e+0)throw e;ra(1,0)}}function xo(e,t){var n=ca();try{return Ja(e,t)}catch(e){if(oa(n),e!==e+0)throw e;return ra(1,0),0n}}function So(e){var t=ca();try{return Oa(e)}catch(e){if(oa(t),e!==e+0)throw e;return ra(1,0),0n}}function Co(e,t,n,r){var i=ca();try{return Ra(e,t,n,r)}catch(e){if(oa(i),e!==e+0)throw e;ra(1,0)}}function wo(e,t,n,r,i){var a=ca();try{return za(e,t,n,r,i)}catch(e){if(oa(a),e!==e+0)throw e;ra(1,0)}}function To(e,t,n,r,i,a){var o=ca();try{return Ba(e,t,n,r,i,a)}catch(e){if(oa(o),e!==e+0)throw e;ra(1,0)}}function Eo(e,t,n,r,i,a){var o=ca();try{return Na(e,t,n,r,i,a)}catch(e){if(oa(o),e!==e+0)throw e;ra(1,0)}}function Do(e,t,n,r,i,a){var o=ca();try{return Va(e,t,n,r,i,a)}catch(e){if(oa(o),e!==e+0)throw e;ra(1,0)}}function Oo(e,t,n,r,i,a,o,s){var c=ca();try{return Pa(e,t,n,r,i,a,o,s)}catch(e){if(oa(c),e!==e+0)throw e;ra(1,0)}}function ko(e,t,n,r,i){var a=ca();try{return Ha(e,t,n,r,i)}catch(e){if(oa(a),e!==e+0)throw e;return ra(1,0),0n}}function Ao(e,t,n,r){var i=ca();try{return Ua(e,t,n,r)}catch(e){if(oa(i),e!==e+0)throw e;ra(1,0)}}function jo(e,t,n,r){var i=ca();try{return Wa(e,t,n,r)}catch(e){if(oa(i),e!==e+0)throw e;ra(1,0)}}function Mo(e,t,n,r,i,a,o,s,c,l,u,d){var f=ca();try{return Ga(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(oa(f),e!==e+0)throw e;ra(1,0)}}function No(e,t,n,r,i,a,o,s,c,l,u){var d=ca();try{Ka(e,t,n,r,i,a,o,s,c,l,u)}catch(e){if(oa(d),e!==e+0)throw e;ra(1,0)}}function Po(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){var g=ca();try{qa(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}catch(e){if(oa(g),e!==e+0)throw e;ra(1,0)}}function Fo(e,t,n){var r=ca();try{return Aa(e,t,n)}catch(e){if(oa(r),e!==e+0)throw e;return ra(1,0),0n}}function Io(e,t,n){var r=ca();try{return ka(e,t,n)}catch(e){if(oa(r),e!==e+0)throw e;ra(1,0)}}function Lo(e,t,n){var r=ca();try{return ja(e,t,n)}catch(e){if(oa(r),e!==e+0)throw e;ra(1,0)}}function Ro(e,t,n,r){var i=ca();try{Ma(e,t,n,r)}catch(e){if(oa(i),e!==e+0)throw e;ra(1,0)}}function zo(){if(0{let n=new WeakMap,r,i,a=1;t.webgpuRegisterDevice=e=>{if(i!==void 0)throw Error(`another WebGPU EP inference session is being created.`);if(e){var t=n.get(e);if(!t){let r=((e,t=0)=>{var n=Vi(t);return t=Bi(t,n),ur[n>>>0]=e.queue,ur[t>>>0]=e,t})(e,t=Mi(0));t=[a++,t,r],n.set(e,t)}return r=e,i=t[0],t}r=void 0,i=0};let o=new Map;t.webgpuOnCreateSession=t=>{if(i!==void 0){var n=i;if(i=void 0,t){let i=Di(n);o.set(t,i),n===0&&e(r??hr(i))}r=void 0}},t.webgpuOnReleaseSession=e=>{o.delete(e)};let s=Symbol(`gpuBufferMetadata`);t.webgpuRegisterBuffer=(e,t,n)=>{if(n)return e[s]=[n,NaN],n;if(n=e[s])return n[1]++,n[0];if((t=o.get(t))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);return t=((e,t=0)=>(e.mapState===`unmapped`||ae(),t=zi(t),ur[t>>>0]=e,t))(e,t),e[s]=[t,1],t},t.webgpuUnregisterBuffer=e=>{let t=e[s];if(!t)throw Error(`Buffer is not registered`);t[1]--,t[1]===0&&(ji(t[0]),delete e[s])},t.webgpuGetBuffer=e=>hr(e),t.webgpuCreateDownloader=(e,t,n)=>{if((n=o.get(n))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);let r=hr(n),i=16*Math.ceil(Number(t)/16);return async()=>{let n=r.createBuffer({size:i,usage:9});try{let a=r.createCommandEncoder();return a.copyBufferToBuffer(e,0,n,0,i),r.queue.submit([a.finish()]),await n.mapAsync(GPUMapMode.READ),n.getMappedRange().slice(0,t)}finally{n.destroy()}}},t.ad=(e,t)=>{var n=t.buffer;let a=t.byteOffset,o=t.byteLength;if(t=16*Math.ceil(Number(o)/16),e=hr(e),!r){var s=Di(i);r=hr(s)}let c=(s=r.createBuffer({mappedAtCreation:!0,size:t,usage:6})).getMappedRange();new Uint8Array(c).set(new Uint8Array(n,a,o)),s.unmap(),(n=r.createCommandEncoder()).copyBufferToBuffer(s,0,e,0,t),r.queue.submit([n.finish()]),s.destroy()}},t.webnnInit=e=>{let n=e[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=e.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=e=>n.onRunStart(e),t.webnnOnRunEnd=n.onRunEnd.bind(n),t.webnnOnReleaseSession=e=>{n.onReleaseSession(e)},t.webnnCreateMLTensorDownloader=(e,t)=>n.createMLTensorDownloader(e,t),t.webnnRegisterMLTensor=(e,t,r,i)=>n.registerMLTensor(e,t,r,i),t.webnnCreateMLContext=e=>n.createMLContext(e),t.webnnRegisterMLConstant=(e,r,i,a,o,s)=>n.registerMLConstant(e,r,i,a,o,t.Uc,s),t.webnnRegisterGraphInput=n.registerGraphInput.bind(n),t.webnnIsGraphInput=n.isGraphInput.bind(n),t.webnnRegisterGraphOutput=n.registerGraphOutput.bind(n),t.webnnIsGraphOutput=n.isGraphOutput.bind(n),t.webnnCreateTemporaryTensor=n.createTemporaryTensor.bind(n),t.webnnIsGraphInputOutputTypeSupported=n.isGraphInputOutputTypeSupported.bind(n)},ne?t:new Promise((e,t)=>{m=e,h=t})}var V_,H_,qle=Gg(()=>{V_=B_,H_=globalThis.self?.name?.startsWith(`em-pthread`),H_&&B_()}),U_,W_,G_,K_,q_,J_,Y_,X_,Z_,Q_,$_,ev,tv,nv,rv=Gg(()=>{P_(),U_=typeof location>`u`?void 0:location.origin,W_=import.meta.url>`file:`&&import.meta.url<`file;`,G_=()=>W_?new URL(new URL(`ort.webgpu.bundle.min.mjs`,import.meta.url).href,U_).href:import.meta.url,K_=G_(),q_=()=>{if(K_&&!K_.startsWith(`blob:`))return K_.substring(0,K_.lastIndexOf(`/`)+1)},J_=(e,t)=>{try{let n=t??K_;return(n?new URL(e,n):new URL(e)).origin===U_}catch{return!1}},Y_=(e,t)=>{let n=t??K_;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},X_=(e,t)=>`${t??`./`}${e}`,Z_=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},Q_=async e=>(await import(e)).default,$_=(Kle(),qg(F_)).default,ev=async()=>{if(!K_)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(J_(K_))return[void 0,$_()];let e=await Z_(K_);return[e,$_(e)]},tv=(qle(),qg(z_)).default,nv=async(e,t,n,r)=>{let i=tv&&!(e||t);if(i){if(K_)i=J_(K_)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,tv];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??Y_(r,t),a=n&&i&&!J_(i,t),o=a?await Z_(i):i??X_(r,t);return[a?o:void 0,await Q_(o)]}}}),iv,av,ov,sv,cv,lv,uv,dv,fv,pv=Gg(()=>{rv(),av=!1,ov=!1,sv=!1,cv=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},lv=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},uv=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},dv=async e=>{if(av)return Promise.resolve();if(ov)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(sv)throw Error(`previous call to 'initializeWebAssembly()' failed.`);ov=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!uv())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!lv())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=cv();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await nv(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=q_();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{ov=!1,av=!0,iv=t,e(),d&&URL.revokeObjectURL(d)},e=>{ov=!1,sv=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},fv=()=>{if(av&&iv)return iv;throw Error(`WebAssembly is not initialized yet.`)}}),mv,hv,gv,_v=Gg(()=>{pv(),mv=(e,t)=>{let n=fv(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},hv=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)hv(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},gv=e=>{let t=fv(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),vv,Jle=Gg(()=>{pv(),_v(),vv=e=>{let t=fv(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=mv(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&gv(`Can't create run options.`),e?.extra!==void 0&&hv(e.extra,``,new WeakSet,(e,i)=>{let a=mv(e,r),o=mv(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&gv(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),yv,bv,xv,Sv,Cv,wv,Tv,Yle=Gg(()=>{pv(),_v(),yv=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},bv=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},xv=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},Sv=(e,t,n,r)=>{let i=mv(t,r),a=mv(n,r);fv()._OrtAddSessionConfigEntry(e,i,a)!==0&&gv(`Can't set a session config entry: ${t} - ${n}.`)},Cv=(e,t,n,r)=>{let i=mv(t,r),a=mv(n,r);e.push([i,a])},wv=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,typeof i!=`string`){let t=i?.deviceType;t&&Sv(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device){if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&Cv(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&Cv(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];Cv(a,`forceCpuNodeNames`,e.join(` +`),n)}r.validationMode&&Cv(a,`validationMode`,r.validationMode,n)}let o=fv().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;Cv(a,`deviceId`,e.toString(),n),Cv(a,`webgpuInstance`,t.toString(),n),Cv(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=mv(r,n),s=a.length,c=0,l=0;if(s>0){c=fv()._malloc(s*fv().PTR_SIZE),n.push(c),l=fv()._malloc(s*fv().PTR_SIZE),n.push(l);for(let e=0;e{let t=fv(),n=0,r=[],i=e||{};xv(i);try{let e=yv(i.graphOptimizationLevel??`all`),a=bv(i.executionMode??`sequential`),o=typeof i.logId==`string`?mv(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?mv(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&gv(`Can't create session options.`),i.executionProviders&&await wv(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);Sv(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=mv(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&gv(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&hv(i.extra,``,new WeakSet,(e,t)=>{Sv(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&gv(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),Ev,Dv,Ov,kv,Av,jv,Mv,Nv,Pv=Gg(()=>{Ev=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},Dv=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},Ov=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},kv=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},Av=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},jv=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Mv=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Nv=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Fv,Iv=Gg(()=>{P_(),Fv=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Lv,Xle=Gg(()=>{Pv(),Lv=(e,t)=>new(kv(t))(e)}),Rv,zv,Bv,Vv,Hv,Uv,Wv,Gv=Gg(()=>{Pv(),Rv=[`V`,`I`,`W`,`E`,`F`],zv=(e,t)=>{console.log(`[${Rv[e]},${new Date().toISOString()}]${t}`)},Hv=(e,t)=>{Bv=e,Vv=t},Uv=(e,t)=>{let n=Av(e);n>=Av(Bv)&&zv(n,typeof t==`function`?t():t)},Wv=(...e)=>{Vv&&Uv(...e)}}),Kv,qv,Jv,Yv,Xv,Zv,Qv,$v,ey,ty,ny,Zle=Gg(()=>{Pv(),Gv(),Kv=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),qv=(e,t)=>{if(t===`int32`)return e;let n=Kv.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(kv(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},Jv=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},Yv=1,Xv=()=>Yv++,Zv=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),Qv=(e,t)=>{let n=Kv.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},$v=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Qv(this.dataType,this.tensorShape)}destroy(){Wv(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Jv(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return n.buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},ey=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Zv.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);Wv(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==Qv(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=qv(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}Wv(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Jv(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},ty=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Xv();return this.tensorTrackersById.set(e,new ey(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){Wv(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){Wv(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=Xv(),o=new $v({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new ey(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){Wv(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}Wv(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new $v({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},ny=(...e)=>new ty(...e)}),ry={};Kg(ry,{WebNNBackend:()=>oy});var iy,ay,oy,Qle=Gg(()=>{Pv(),pv(),Xle(),Zle(),Gv(),iy=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),ay=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},oy=class{constructor(e){this.tensorManager=ny(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Hv(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){Wv(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Wv(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Wv(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>ay(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Wv(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=iy.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){Wv(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=iy.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!fv().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);Wv(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return Lv(n,t)}}registerMLTensor(e,t,n,r){let i=iy.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return Wv(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,n,r,i,a,o=!1){if(!a)throw Error(`External mounted files are not available.`);let s=e;e.startsWith(`./`)&&(s=e.substring(2));let c=a.get(s);if(!c)throw Error(`File with name ${s} not found in preloaded files.`);if(t+n>c.byteLength)throw Error(`Out of bounds: data offset and length exceed the external file data size.`);let l=c.slice(t,t+n).buffer,u;switch(i.dataType){case`float32`:u=new Float32Array(l);break;case`float16`:u=typeof Float16Array<`u`&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case`int32`:u=new Int32Array(l);break;case`uint32`:u=new Uint32Array(l);break;case`int64`:if(o){let e=qv(new Uint8Array(l),`int64`);u=new Int32Array(e.buffer),i.dataType=`int32`}else u=new BigInt64Array(l);break;case`uint64`:u=new BigUint64Array(l);break;case`int8`:u=new Int8Array(l);break;case`int4`:case`uint4`:case`uint8`:u=new Uint8Array(l);break;default:throw Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return Wv(`verbose`,()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${o?`(Note: it was int64 data type and registered to int32 as workaround)`:``}`),r.constant(i,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=iy.get(Ev(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),sy,cy,ly,uy,dy,fy,py,my,hy,gy,_y,vy,yy,by=Gg(()=>{N_(),Jle(),Yle(),Pv(),pv(),_v(),Iv(),sy=(e,t)=>{fv()._OrtInit(e,t)!==0&&gv(`Can't initialize onnxruntime.`)},cy=async e=>{sy(e.wasm.numThreads,Av(e.logLevel))},ly=async(e,t)=>{fv().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&fv().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(Qle(),qg(ry)).WebNNBackend(e);fv().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},uy=new Map,dy=e=>{let t=fv(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&gv(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},fy=(e,t)=>{let n=fv(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&gv(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e{let t=fv(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},my=async(e,t)=>{let n,r,i=fv();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=py(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await Tv(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(Fv(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&gv(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=dy(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;te===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&gv(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>Nv(e))}),uy.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&gv(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&gv(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&gv(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},hy=e=>{let t=fv(),n=uy.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&gv(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&gv(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&gv(`Can't release session.`),uy.delete(e)},gy=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=fv(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=Ov(Ev(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=Ov(Ev(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,Ev(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;es.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(Ev(l),p,m,g,u.length,Nv(f));e===0&&gv(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},_y=async(e,t,n,r,i,a)=>{let o=fv(),s=o.PTR_SIZE,c=uy.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),w=o.stackAlloc(h*s),T=o.stackAlloc(h*s),E=o.stackAlloc(g*s),D=o.stackAlloc(g*s);try{[_,v]=vv(a),D_(`wasm prepareInputOutputTensor`);for(let r=0;re*t,1);u=Dv(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=Ov(a,g);if(i===void 0||!jv(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);C.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(kv(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&gv(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(Ov(a,g)===void 0||!Mv(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,O.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(kv(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&gv(`Can't clear bound outputs.`),uy.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(O))C[e][2]=t;return O_(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},vy=e=>{let t=fv(),n=uy.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&gv(`Can't get an profile file name.`),t._OrtFree(i)},yy=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),xy,Sy,Cy,wy,Ty,Ey,Dy,Oy,ky,Ay,jy,My,Ny,Py,Fy,Iy,Ly,Ry,zy=Gg(()=>{N_(),by(),pv(),rv(),xy=()=>!!i_.wasm.proxy&&typeof document<`u`,Cy=!1,wy=!1,Ty=!1,Oy=new Map,ky=(e,t)=>{let n=Oy.get(e);n?n.push(t):Oy.set(e,[t])},Ay=()=>{if(Cy||!wy||Ty||!Sy)throw Error(`worker not ready`)},jy=e=>{switch(e.data.type){case`init-wasm`:Cy=!1,e.data.err?(Ty=!0,Dy[1](e.data.err)):(wy=!0,Dy[0]()),Ey&&=(URL.revokeObjectURL(Ey),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Oy.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},My=async()=>{if(!wy){if(Cy)throw Error(`multiple calls to 'initWasm()' detected.`);if(Ty)throw Error(`previous call to 'initWasm()' failed.`);if(Cy=!0,xy())return new Promise((e,t)=>{Sy?.terminate(),ev().then(([n,r])=>{try{Sy=r,Sy.onerror=e=>t(e),Sy.onmessage=jy,Dy=[e,t];let i={type:`init-wasm`,in:i_};!i.in.wasm.wasmPaths&&(n||W_)&&(i.in.wasm.wasmPaths={wasm:new URL(new URL(`ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm`,import.meta.url).href,``+import.meta.url).href}),Sy.postMessage(i),Ey=n}catch(e){t(e)}},t)});try{await dv(i_.wasm),await cy(i_),wy=!0}catch(e){throw Ty=!0,e}finally{Cy=!1}}},Ny=async e=>{if(xy())return Ay(),new Promise((t,n)=>{ky(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:i_}};Sy.postMessage(r)});await ly(i_,e)},Py=async e=>xy()?(Ay(),new Promise((t,n)=>{ky(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};Sy.postMessage(r,[e.buffer])})):py(e),Fy=async(e,t)=>{if(xy()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Ay(),new Promise((n,r)=>{ky(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Sy.postMessage(i,a)})}return my(e,t)},Iy=async e=>{if(xy())return Ay(),new Promise((t,n)=>{ky(`release`,[t,n]);let r={type:`release`,in:e};Sy.postMessage(r)});hy(e)},Ly=async(e,t,n,r,i,a)=>{if(xy()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Ay(),new Promise((i,o)=>{ky(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};Sy.postMessage(c,yy(s))})}return _y(e,t,n,r,i,a)},Ry=async e=>{if(xy())return Ay(),new Promise((t,n)=>{ky(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};Sy.postMessage(r)});vy(e)}}),By,Vy,Hy,Uy=Gg(()=>{N_(),zy(),Pv(),P_(),Iv(),By=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Vy=e=>{switch(e[3]){case`cpu`:return new x_(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!jv(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return x_.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Mv(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return x_.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Hy=class{async fetchModelAndCopyToWasmMemory(e){return Py(await Fv(e))}async loadModel(e,t){T_();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Fy(n,t),E_()}async dispose(){return Iy(this.sessionId)}async run(e,t,n){T_();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>By(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?By(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Ly(this.sessionId,i,s,o,c,n),u={};for(let e=0;eKy,initializeFlags:()=>Gy,wasmBackend:()=>qy});var Gy,Ky,qy,$le=Gg(()=>{N_(),zy(),Uy(),Gy=()=>{(typeof i_.wasm.initTimeout!=`number`||i_.wasm.initTimeout<0)&&(i_.wasm.initTimeout=0);let e=i_.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),i_.wasm.simd=!1),typeof i_.wasm.proxy!=`boolean`&&(i_.wasm.proxy=!1),typeof i_.wasm.trace!=`boolean`&&(i_.wasm.trace=!1),typeof i_.wasm.numThreads!=`number`||!Number.isInteger(i_.wasm.numThreads)||i_.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)i_.wasm.numThreads=1;else{let e=typeof navigator>`u`?jle(`node:os`).cpus().length:navigator.hardwareConcurrency;i_.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},Ky=class{async init(e){Gy(),await My(),await Ny(e)}async createInferenceSessionHandler(e,t){let n=new Hy;return await n.loadModel(e,t),n}},qy=new Ky});N_(),N_(),N_();var Jy=`1.26.0-dev.20260416-b7804b056c`,Yy=M_;{let e=($le(),qg(Wy)).wasmBackend;Xg(`webgpu`,e,5),Xg(`webnn`,e,5),Xg(`cpu`,e,10),Xg(`wasm`,e,10)}Object.defineProperty(i_.versions,"web",{value:Jy,enumerable:!0});let Xy=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:`1.24.3`},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);Xy=e}},get logLevel(){return Xy}},"logLevel",{enumerable:!0});const Zy=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,$y(o,s)}throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t($y(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return $y(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},tb=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new db({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},nb=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new db({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},rb=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new db({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},ib=(e,t,n)=>new db({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),ab=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),ob=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]);let sb=!1;const cb=()=>{if(!sb){sb=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(ab.set(`int64`,BigInt64Array),ob.set(BigInt64Array,`int64`)),t&&(ab.set(`uint64`,BigUint64Array),ob.set(BigUint64Array,`uint64`)),r?(ab.set(`float16`,n),ob.set(n,`float16`)):ab.set(`float16`,Uint16Array)}},lb=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new db(e.type,e.data,t);case`cpu-pinned`:return new db({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new db({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new db({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new db({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var db=class{constructor(e,t,n){cb();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=ab.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=ab.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=ob.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=lb(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return eb(e,t)}static fromTexture(e,t){return tb(e,t)}static fromGpuBuffer(e,t){return nb(e,t)}static fromMLTensor(e,t){return rb(e,t)}static fromPinnedBuffer(e,t,n){return ib(e,t,n)}toDataURL(e){return Zy(this,e)}toImageData(e){return Qy(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ub(this,e)}};const eue=db;var tue=Object.defineProperty,fb=(e,t)=>{for(var n in t)tue(e,n,{get:t[n],enumerable:!0})},pb={},mb={},nue={},rue=`4.2.0`,hb=typeof self<`u`,gb=!Mb(pb),_b=!Mb(mb),vb=hb&&`caches`in self,iue=globalThis.Deno!==void 0;globalThis.Bun;var yb=iue&&vb&&!gb,bb=typeof process<`u`,xb=bb&&process?.release?.name===`node`&&!yb,Sb=typeof window<`u`&&window.document!==void 0,Cb=hb&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),aue=Sb||Cb||yb,oue=xb||typeof navigator<`u`&&`gpu`in navigator,sue=typeof navigator<`u`&&`ml`in navigator,cue=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,lue=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,uue=typeof ServiceWorkerGlobalScope<`u`&&hb&&self instanceof ServiceWorkerGlobalScope,due=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent,t=(navigator.vendor||``).indexOf(`Apple`)>-1,n=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`);return t&&n})(),wb=Object.freeze({IS_BROWSER_ENV:Sb,IS_WEBWORKER_ENV:Cb,IS_WEB_ENV:aue,IS_SERVICE_WORKER_ENV:uue,IS_DENO_WEB_RUNTIME:yb,IS_WEB_CACHE_AVAILABLE:vb,IS_WEBGPU_AVAILABLE:oue,IS_WEBNN_AVAILABLE:sue,IS_SAFARI:due,IS_PROCESS_AVAILABLE:bb,IS_NODE_ENV:xb,IS_FS_AVAILABLE:gb,IS_PATH_AVAILABLE:_b,IS_CRYPTO_AVAILABLE:cue,IS_CHROME_AVAILABLE:lue}),Tb=gb&&_b,Eb=`./`;if(Tb){let e=Object(import.meta).url;e?Eb=mb.dirname(mb.dirname(nue.fileURLToPath(e))):typeof __dirname<`u`&&(Eb=mb.dirname(__dirname))}var fue=Tb?mb.join(Eb,`/.cache/`):null,Db=`/models/`,pue=Tb?mb.join(Eb,Db):Db,Ob=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,kb=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Ab=kb.WARNING,jb={version:rue,backends:{onnx:{}},get logLevel(){return Ab},set logLevel(e){Ab=e,jb.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(Sb||Cb||yb),localModelPath:pue,useFS:gb,useBrowserCache:vb,useFSCache:gb,cacheDir:fue,useCustomCache:!1,customCache:null,useWasmCache:vb||gb,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:Ob};function Mb(e){return Object.keys(e).length===0}var Nb=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}};function Pb(e,t){e&&e(t)}var Fb=class extends Nb{constructor(e,t){super(),this.callback=e,this.files_loading=t}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),n=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0),r=n>0?t/n*100:0;this.callback({status:`progress_total`,name:e.name,progress:r,loaded:t,total:n,files:structuredClone(this.files_loading)})}this.callback(e)}};function Ib(e){return Number.isInteger(e)||typeof e==`bigint`}function Lb(e){return e==null||e===-1}function Rb(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function zb(...e){return Array.prototype.concat.apply([],e)}function Bb(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function Vb(e,t){return Math.abs((e+t)%(2*t)-t)}function Hb(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function Ub(e,t){let n=0;for(let r of e)r===t&&++n;return n}var Wb={error(...e){jb.logLevel<=kb.ERROR&&console.error(...e)},warn(...e){jb.logLevel<=kb.WARNING&&console.warn(...e)},info(...e){jb.logLevel<=kb.INFO&&console.log(...e)},debug(...e){jb.logLevel<=kb.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},Gb=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let n of e){let e=t;for(let t=0;tr&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),Jb=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(qb),Yb=`.,!?…。,、।۔،`,Xb=new Map([[`(?i:'s|'t|'re|'ve|'m|'ll|'d)`,`(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))`],[`(?i:[sdmt]|ll|ve|re)`,`(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])`],[`[^\\r\\n\\p{L}\\p{N}]?+`,`[^\\r\\n\\p{L}\\p{N}]?`],[`[^\\s\\p{L}\\p{N}]++`,`[^\\s\\p{L}\\p{N}]+`],[`(?>\\p{Nd}{510})`,`(?:\\p{Nd}{510})`],[`\\p{Nd}{3}+`,`(?:\\p{Nd}{3})+`],[`\\G`,``],[` ?[^(\\s|[${Yb}])]+`,` ?[^\\s${Yb}]+`]]),Zb=`\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E`,Qb=e=>e.replace(/ \./g,`.`).replace(/ \?/g,`?`).replace(/ \!/g,`!`).replace(/ ,/g,`,`).replace(/ \' /g,`'`).replace(/ n't/g,`n't`).replace(/ 'm/g,`'m`).replace(/ 's/g,`'s`).replace(/ 've/g,`'ve`).replace(/ 're/g,`'re`),$b=(e,t=!0)=>{if(e.Regex!==void 0){let t=e.Regex.replace(/\\([#&~])/g,`$1`);t=t.replace(/\\A/g,`^`).replace(/\\z/g,`$`).replace(/\\Z/g,`(?=\\r?\\n?$)`);for(let[e,n]of Xb)t=t.replaceAll(e,n);try{return new RegExp(t,`gu`)}catch(e){if(!(e instanceof SyntaxError)||!e.message.toLowerCase().includes(`invalid property name`))throw e;let n=!1,r=t.replace(/(\\[pP])\{([^}=]+)\}/g,(e,t,r)=>{try{return RegExp(`\\p{${r}}`,`u`),`${t}{${r}}`}catch{return n=!0,`${t}{Script=${r}}`}});if(!n)throw e;try{return new RegExp(r,`gu`)}catch{throw e}}}if(e.String!==void 0){let n=ex(e.String);return new RegExp(t?n:`(${n})`,`gu`)}return console.warn(`Unknown pattern type:`,e),null},ex=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),tx=(e,t,n)=>{let r=[],i=0;for(;ie>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,rx=e=>Number.isInteger(e)||typeof e==`bigint`,ix=e=>{let t=0;for(let n of e)++t;return t},ax=e=>lx(e.toLowerCase()),ox=(...e)=>Array.prototype.concat.apply([],e),sx=e=>new Map(Object.entries(e)),cx=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r0&&n.push(t),r=i.index+t.length}return re.replace(/\p{M}/gu,``),ux=(e,t,n=[])=>{if(!e||Array.isArray(e)||typeof e!=`object`)return`${t} must be a valid object`;for(let r of n)if(!(r in e))return`${t} must contain a "${r}" property`;return null},dx=e=>e.match(/\S+/g)||[],fx=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},px=class extends fx{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},mx=class extends px{tokenize_chinese_chars(e){let t=[];for(let n=0;ne.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},gx=class extends px{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>Ox(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},_x=class extends px{normalize(e){let t=$b(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??``)}},vx=class extends px{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},yx=class extends vx{constructor(){super(...arguments),this.form=`NFC`}},bx=class extends vx{constructor(){super(...arguments),this.form=`NFD`}},xx=class extends vx{constructor(){super(...arguments),this.form=`NFKC`}},Sx=class extends vx{constructor(){super(...arguments),this.form=`NFKD`}},Cx=class extends px{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},wx=class extends px{normalize(e){return lx(e)}},Tx=class extends px{normalize(e){return e.toLowerCase()}},Ex=class extends px{normalize(e){return e=this.config.prepend+e,e}};function Dx(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new mx(e);case`Precompiled`:return new hx(e);case`Sequence`:return new gx(e);case`Replace`:return new _x(e);case`NFC`:return new yx(e);case`NFD`:return new bx(e);case`NFKC`:return new xx(e);case`NFKD`:return new Sx(e);case`Strip`:return new Cx(e);case`StripAccents`:return new wx(e);case`Lowercase`:return new Tx(e);case`Prepend`:return new Ex(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var Ox=Dx,kx=class extends fx{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},Ax=class extends kx{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=qb,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(` `)&&(e=` `+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(``))}},jx=class extends kx{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Mx=class extends kx{constructor(e){super(),this.replacement=e.replacement??`▁`,this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??`always`}pre_tokenize_text(e,t){let{section_index:n=void 0}=t??{},r=e.replaceAll(` `,this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme===`always`||this.prepend_scheme===`first`&&n===0)&&(r=this.str_rep+r),[r]}},Nx=class extends kx{constructor(e){super(),this.config=e,this.pattern=$b(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):cx(e,this.pattern)}},Px=class extends kx{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${Zb}]+|[${Zb}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Fx=class extends kx{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?``:`+`}`;this.pattern=new RegExp(t,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Ix=class extends kx{constructor(){super(),this.pattern=RegExp(`[^\\s${Zb}]+|[${Zb}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},Lx=class extends kx{constructor(e){super(),this.config=e,this.pattern=$b(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},Rx=class extends kx{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>Hx(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},zx=class extends kx{pre_tokenize_text(e){return dx(e)}},Bx=class extends kx{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;nthis.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}},Gx=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,new Map)}},Kx=class{constructor(){this.root=Gx.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);e===void 0&&(e=Gx.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let n=``;for(let r of e){if(n+=r,t=t.children.get(r),t===void 0)return;t.is_leaf&&(yield n)}}},qx=class e{constructor(e,t,n,r,i){this.token_id=e,this.node_id=t,this.pos=n,this.length=r,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},Jx=class{constructor(e,t,n){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new qx(this.bos_token_id??0,0,0,0,0),i=new qx(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(r)}insert(e,t,n,r){let i=this.nodes.length,a=new qx(r,i,e,t,n);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let e of this.begin_nodes[t]){e.prev=null;let n=0,r=null;for(let i of this.end_nodes[t]){let t=i.backtrace_score+e.score;(r===null||t>n)&&(r=i.clone(),n=t)}if(r!==null)e.prev=r,e.backtrace_score=n;else return[]}++t}let n=[],r=this.begin_nodes[e][0].prev;if(r===null)return[];let i=r.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join(``)}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}};function Yx(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r[e,t])),this.bos_token=` `,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=Yx(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Kx,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;ne>t,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},$x=class extends Ux{constructor(e){super(e),this.tokens_to_ids=sx(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(e=>e.split(` `,2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new Qx(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new Zx((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,`0`)}>`);e.every(e=>this.tokens_to_ids.has(e))?t.push(...e):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},eS=class extends Ux{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=sx(t.target_lang?n[t.target_lang]:n),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}};function tS(e,t){switch(e.type){case`WordPiece`:return new Wx(e);case`Unigram`:return new Xx(e,t.eos_token);case`BPE`:return new $x(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Xx(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new $x(e):new Wx(e):new eS(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw Error(`Unknown TokenizerModel type: ${e?.type}`)}}var mue=tS,nS=class extends fx{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},hue=class extends nS{post_process(e,t=null,n=!0){let r=t===null?this.config.single:this.config.pair,i=[],a=[];for(let o of r)`SpecialToken`in o?n&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):`Sequence`in o&&(o.Sequence.id===`A`?(i=ox(i,e),a=ox(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=ox(i,t),a=ox(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},gue=class extends nS{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},_ue=class extends nS{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=ox([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=ox(e,i,t,a),r=ox(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},vue=class extends nS{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=ox([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=n?[this.sep[0]]:[],a=n?[this.sep[0]]:[];e=ox(e,i,t,a),r=ox(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},yue=class extends nS{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>rS(e))}post_process(e,t=null,n=!0){let r={tokens:e,tokens_pair:t};for(let e of this.processors)r=e.post_process(r.tokens,r.tokens_pair,n);return r}};function bue(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new hue(e);case`ByteLevel`:return new gue(e);case`BertProcessing`:return new _ue(e);case`RobertaProcessing`:return new vue(e);case`Sequence`:return new yue(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var rS=bue,iS=class extends fx{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=`trim_offsets`in e&&e.trim_offsets}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},xue=class extends iS{constructor(e){super(e),this.byte_decoder=Jb,this.text_decoder=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(``),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.find(e=>e.content===r)===void 0?n.push(r):(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r));return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}},Sue=class extends iS{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(t!==0){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,``):` `+e}return this.cleanup&&(e=Qb(e)),e})}},Cue=class extends iS{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;nt.replaceAll(this.suffix,n===e.length-1?``:` `))}},Tue=class extends iS{constructor(e){super(e),this.pad_token=e.pad_token??``,this.word_delimiter_token=e.word_delimiter_token??``,this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return``;let t=[e[0]];for(let n=1;ne!==this.pad_token).join(``);return this.cleanup&&(n=Qb(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},Eue=class extends iS{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>aS(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},Due=class extends iS{decode_chain(e){let t=$b(this.config.pattern),n=this.config.content??``;return t===null?e:e.map(e=>e.replaceAll(t,n))}},Oue=class extends iS{decode_chain(e){return[e.join(``)]}},kue=class extends iS{constructor(e){super(e),this.content=e.content??``,this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n`)){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(e!==null)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}};function jue(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new xue(e);case`WordPiece`:return new Sue(e);case`Metaspace`:return new Cue(e);case`BPEDecoder`:return new wue(e);case`CTC`:return new Tue(e);case`Sequence`:return new Eue(e);case`Replace`:return new Due(e);case`Fuse`:return new Oue(e);case`Strip`:return new kue(e);case`ByteFallback`:return new Aue(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var aS=jue,Mue=class{constructor(e,t){let n=ux(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=ux(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=Ox(this.tokenizer.normalizer),this.pre_tokenizer=Hx(this.tokenizer.pre_tokenizer),this.model=mue(this.tokenizer.model,this.config),this.post_processor=rS(this.tokenizer.post_processor),this.decoder=aS(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=new Map;for(let e of this.tokenizer.added_tokens){let t=new Kb(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&this.normalizer!==null){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else i.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new Gb(i),this.splitter_normalized=new Gb(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:i,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}),o=i.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),s={ids:o,tokens:i,attention_mask:Array(o.length).fill(1)};return r&&a&&(s.token_type_ids=a),s}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!rx(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(` `);return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix,` `),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Qb(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,n)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),r.rstrip&&n{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];if(this.remove_space===!0&&(e=e.trim().split(/\s+/).join(` `)),this.do_lowercase_and_remove_accent&&(e=ax(e)),this.normalizer!==null&&(e=this.normalizer(e)),e.length===0)return[];let n=this.splitter_normalized.split(e);return n.forEach((e,t)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&t>0&&(n[t-1]=n[t-1].trimEnd()),r.rstrip&&t{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];let n=this.pre_tokenizer===null?[e]:this.pre_tokenizer(e,{section_index:t});return this.model(n)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:n=!0}){let r=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(r,i,n):{tokens:ox(r??[],i??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let n=0;n=`,I.ComparisonBinaryOperator],[`==`,I.ComparisonBinaryOperator],[`!=`,I.ComparisonBinaryOperator],[`<`,I.ComparisonBinaryOperator],[`>`,I.ComparisonBinaryOperator],[`+`,I.AdditiveBinaryOperator],[`-`,I.AdditiveBinaryOperator],[`~`,I.AdditiveBinaryOperator],[`*`,I.MultiplicativeBinaryOperator],[`/`,I.MultiplicativeBinaryOperator],[`%`,I.MultiplicativeBinaryOperator],[`=`,I.Equals]],Pue=new Map([[`n`,` +`],[`t`,` `],[`r`,`\r`],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`'`,`'`],[`"`,`"`],[`\\`,`\\`]]);function Fue(e,t={}){return e.endsWith(` +`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,`$1`)),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,`$1`)),e.replace(/{%\s*(end)?generation\s*%}/gs,``)}function Iue(e,t={}){let n=[],r=Fue(e,t),i=0,a=0,o=e=>{let t=``;for(;e(r[i]);){if(r[i]===`\\`){if(++i,i>=r.length)throw SyntaxError(`Unexpected end of input`);let e=r[i++],n=Pue.get(e);if(n===void 0)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=n;continue}if(t+=r[i++],i>=r.length)throw SyntaxError(`Unexpected end of input`)}return t},s=()=>{let e=n.at(-1);e&&e.type===I.Text&&(e.value=e.value.trimEnd(),e.value===``&&n.pop())},c=()=>{for(;i0){n.push(new oS(e,I.Text));continue}}if(r[i]===`{`&&r[i+1]===`#`){i+=2;let e=r[i]===`-`;e&&++i;let t=``;for(;r[i]!==`#`||r[i+1]!==`}`;){if(i+2>=r.length)throw SyntaxError(`Missing end of comment tag`);t+=r[i++]}let a=t.endsWith(`-`);a&&(t=t.slice(0,-1)),e&&s(),n.push(new oS(t,I.Comment)),i+=2,a&&c();continue}if(r.slice(i,i+3)===`{%-`){s(),n.push(new oS(`{%`,I.OpenStatement)),i+=3;continue}if(r.slice(i,i+3)===`{{-`){s(),n.push(new oS(`{{`,I.OpenExpression)),a=0,i+=3;continue}if(o(lS),r.slice(i,i+3)===`-%}`){n.push(new oS(`%}`,I.CloseStatement)),i+=3,c();continue}if(r.slice(i,i+3)===`-}}`){n.push(new oS(`}}`,I.CloseExpression)),i+=3,c();continue}let t=r[i];if(t===`-`||t===`+`){let e=n.at(-1)?.type;if(e===I.Text||e===void 0)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case I.Identifier:case I.NumericLiteral:case I.StringLiteral:case I.CloseParen:case I.CloseSquareBracket:break;default:{++i;let e=o(cS);n.push(new oS(`${t}${e}`,e.length>0?I.NumericLiteral:I.UnaryOperator));continue}}}for(let[e,t]of Nue)if(!(e===`}}`&&a>0)&&r.slice(i,i+e.length)===e){n.push(new oS(e,t)),t===I.OpenExpression?a=0:t===I.OpenCurlyBracket?++a:t===I.CloseCurlyBracket&&--a,i+=e.length;continue main}if(t===`'`||t===`"`){++i;let e=o(e=>e!==t);n.push(new oS(e,I.StringLiteral)),++i;continue}if(cS(t)){let e=o(cS);if(r[i]===`.`&&cS(r[i+1])){++i;let t=o(cS);e=`${e}.${t}`}n.push(new oS(e,I.NumericLiteral));continue}if(sS(t)){let e=o(sS);n.push(new oS(e,I.Identifier));continue}throw SyntaxError(`Unexpected character: ${t}`)}return n}var uS=class{type=`Statement`},Lue=class extends uS{constructor(e){super(),this.body=e}type=`Program`},Rue=class extends uS{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type=`If`},zue=class extends uS{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type=`For`},Bue=class extends uS{type=`Break`},Vue=class extends uS{type=`Continue`},Hue=class extends uS{constructor(e,t,n){super(),this.assignee=e,this.value=t,this.body=n}type=`Set`},Uue=class extends uS{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type=`Macro`},Wue=class extends uS{constructor(e){super(),this.value=e}type=`Comment`},dS=class extends uS{type=`Expression`},Gue=class extends dS{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type=`MemberExpression`},fS=class extends dS{constructor(e,t){super(),this.callee=e,this.args=t}type=`CallExpression`},pS=class extends dS{constructor(e){super(),this.value=e}type=`Identifier`},mS=class extends dS{constructor(e){super(),this.value=e}type=`Literal`},Kue=class extends mS{type=`IntegerLiteral`},que=class extends mS{type=`FloatLiteral`},hS=class extends mS{type=`StringLiteral`},Jue=class extends mS{type=`ArrayLiteral`},gS=class extends mS{type=`TupleLiteral`},Yue=class extends mS{type=`ObjectLiteral`},_S=class extends dS{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type=`BinaryExpression`},Xue=class extends dS{constructor(e,t){super(),this.operand=e,this.filter=t}type=`FilterExpression`},Zue=class extends uS{constructor(e,t){super(),this.filter=e,this.body=t}type=`FilterStatement`},Que=class extends dS{constructor(e,t){super(),this.lhs=e,this.test=t}type=`SelectExpression`},$ue=class extends dS{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type=`TestExpression`},ede=class extends dS{constructor(e,t){super(),this.operator=e,this.argument=t}type=`UnaryExpression`},tde=class extends dS{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type=`SliceExpression`},nde=class extends dS{constructor(e,t){super(),this.key=e,this.value=t}type=`KeywordArgumentExpression`},rde=class extends dS{constructor(e){super(),this.argument=e}type=`SpreadExpression`},ide=class extends uS{constructor(e,t,n){super(),this.call=e,this.callerArgs=t,this.body=n}type=`CallStatement`},ade=class extends dS{constructor(e,t,n){super(),this.condition=e,this.trueExpr=t,this.falseExpr=n}type=`Ternary`};function ode(e){let t=new Lue([]),n=0;function r(t,r){let i=e[n++];if(!i||i.type!==t)throw Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function i(e){if(!c(e))throw SyntaxError(`Expected ${e}`);++n}function a(){switch(e[n].type){case I.Comment:return new Wue(e[n++].value);case I.Text:return l();case I.OpenStatement:return u();case I.OpenExpression:return d();default:throw SyntaxError(`Unexpected token type: ${e[n].type}`)}}function o(...t){return n+t.length<=e.length&&t.every((t,r)=>t===e[n+r].type)}function s(...t){return e[n]?.type===I.OpenStatement&&e[n+1]?.type===I.Identifier&&t.includes(e[n+1]?.value)}function c(...t){return n+t.length<=e.length&&t.every((t,r)=>e[n+r].type===`Identifier`&&t===e[n+r].value)}function l(){return new hS(r(I.Text,`Expected text token`).value)}function u(){if(r(I.OpenStatement,`Expected opening statement token`),e[n].type!==I.Identifier)throw SyntaxError(`Unknown statement, got ${e[n].type}`);let t=e[n].value,c;switch(t){case`set`:++n,c=f();break;case`if`:++n,c=p(),r(I.OpenStatement,`Expected {% token`),i(`endif`),r(I.CloseStatement,`Expected %} token`);break;case`macro`:++n,c=m(),r(I.OpenStatement,`Expected {% token`),i(`endmacro`),r(I.CloseStatement,`Expected %} token`);break;case`for`:++n,c=g(),r(I.OpenStatement,`Expected {% token`),i(`endfor`),r(I.CloseStatement,`Expected %} token`);break;case`call`:{++n;let e=null;o(I.OpenParen)&&(e=E());let t=ee();if(t.type!==`Identifier`)throw SyntaxError(`Expected identifier following call statement`);let l=E();r(I.CloseStatement,`Expected closing statement token`);let u=[];for(;!s(`endcall`);)u.push(a());r(I.OpenStatement,`Expected '{%'`),i(`endcall`),r(I.CloseStatement,`Expected closing statement token`),c=new ide(new fS(t,l),e,u);break}case`break`:++n,r(I.CloseStatement,`Expected closing statement token`),c=new Bue;break;case`continue`:++n,r(I.CloseStatement,`Expected closing statement token`),c=new Vue;break;case`filter`:{++n;let e=ee();e instanceof pS&&o(I.OpenParen)&&(e=T(e)),r(I.CloseStatement,`Expected closing statement token`);let t=[];for(;!s(`endfilter`);)t.push(a());r(I.OpenStatement,`Expected '{%'`),i(`endfilter`),r(I.CloseStatement,`Expected '%}'`),c=new Zue(e,t);break}default:throw SyntaxError(`Unknown statement type: ${t}`)}return c}function d(){r(I.OpenExpression,`Expected opening expression token`);let e=_();return r(I.CloseExpression,`Expected closing expression token`),e}function f(){let e=h(),t=null,c=[];if(o(I.Equals))++n,t=h();else{for(r(I.CloseStatement,`Expected %} token`);!s(`endset`);)c.push(a());r(I.OpenStatement,`Expected {% token`),i(`endset`)}return r(I.CloseStatement,`Expected closing statement token`),new Hue(e,t,c)}function p(){let e=_();r(I.CloseStatement,`Expected closing statement token`);let t=[],i=[];for(;!s(`elif`,`else`,`endif`);)t.push(a());if(s(`elif`)){++n,++n;let e=p();i.push(e)}else if(s(`else`))for(++n,++n,r(I.CloseStatement,`Expected closing statement token`);!s(`endif`);)i.push(a());return new Rue(e,t,i)}function m(){let e=ee();if(e.type!==`Identifier`)throw SyntaxError(`Expected identifier following macro statement`);let t=E();r(I.CloseStatement,`Expected closing statement token`);let n=[];for(;!s(`endmacro`);)n.push(a());return new Uue(e,t,n)}function h(e=!1){let t=e?ee:_,r=[t()],i=o(I.Comma);for(;i&&(++n,r.push(t()),o(I.Comma)););return i?new gS(r):r[0]}function g(){let e=h(!0);if(!(e instanceof pS||e instanceof gS))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);if(!c(`in`))throw SyntaxError("Expected `in` keyword following loop variable");++n;let t=_();r(I.CloseStatement,`Expected closing statement token`);let i=[];for(;!s(`endfor`,`else`);)i.push(a());let o=[];if(s(`else`))for(++n,++n,r(I.CloseStatement,`Expected closing statement token`);!s(`endfor`);)o.push(a());return new zue(e,t,i,o)}function _(){return v()}function v(){let e=y();if(c(`if`)){++n;let t=y();return c(`else`)?(++n,new ade(t,e,v())):new Que(e,t)}return e}function y(){let t=b();for(;c(`or`);){let r=e[n];++n;let i=b();t=new _S(r,t,i)}return t}function b(){let t=x();for(;c(`and`);){let r=e[n];++n;let i=x();t=new _S(r,t,i)}return t}function x(){let t;for(;c(`not`);){let r=e[n];++n,t=new ede(r,x())}return t??S()}function S(){let t=C();for(;;){let r;if(c(`not`,`in`))r=new oS(`not in`,I.Identifier),n+=2;else if(c(`in`))r=e[n++];else if(o(I.ComparisonBinaryOperator))r=e[n++];else break;let i=C();t=new _S(r,t,i)}return t}function C(){let t=A();for(;o(I.AdditiveBinaryOperator);){let r=e[n];++n;let i=A();t=new _S(r,t,i)}return t}function w(){let e=k(ee());return o(I.OpenParen)?T(e):e}function T(e){let t=new fS(e,E());return t=k(t),o(I.OpenParen)&&(t=T(t)),t}function E(){r(I.OpenParen,`Expected opening parenthesis for arguments list`);let e=D();return r(I.CloseParen,`Expected closing parenthesis for arguments list`),e}function D(){let t=[];for(;!o(I.CloseParen);){let r;if(e[n].type===I.MultiplicativeBinaryOperator&&e[n].value===`*`)++n,r=new rde(_());else if(r=_(),o(I.Equals)){if(++n,!(r instanceof pS))throw SyntaxError(`Expected identifier for keyword argument`);let e=_();r=new nde(r,e)}t.push(r),o(I.Comma)&&++n}return t}function O(){let e=[],t=!1;for(;!o(I.CloseSquareBracket);)o(I.Colon)?(e.push(void 0),++n,t=!0):(e.push(_()),o(I.Colon)&&(++n,t=!0));if(e.length===0)throw SyntaxError(`Expected at least one argument for member/slice expression`);if(t){if(e.length>3)throw SyntaxError(`Expected 0-3 arguments for slice expression`);return new tde(...e)}return e[0]}function k(t){for(;o(I.Dot)||o(I.OpenSquareBracket);){let i=e[n];++n;let a,o=i.type===I.OpenSquareBracket;if(o)a=O(),r(I.CloseSquareBracket,`Expected closing square bracket`);else if(a=ee(),a.type!==`Identifier`)throw SyntaxError(`Expected identifier following dot operator`);t=new Gue(t,a,o)}return t}function A(){let t=j();for(;o(I.MultiplicativeBinaryOperator);){let r=e[n++],i=j();t=new _S(r,t,i)}return t}function j(){let e=M();for(;c(`is`);){++n;let t=c(`not`);t&&++n;let r=ee();if(!(r instanceof pS))throw SyntaxError(`Expected identifier for the test`);e=new $ue(e,t,r)}return e}function M(){let e=w();for(;o(I.Pipe);){++n;let t=ee();if(!(t instanceof pS))throw SyntaxError(`Expected identifier for the filter`);o(I.OpenParen)&&(t=T(t)),e=new Xue(e,t)}return e}function ee(){let t=e[n++];switch(t.type){case I.NumericLiteral:{let e=t.value;return e.includes(`.`)?new que(Number(e)):new Kue(Number(e))}case I.StringLiteral:{let r=t.value;for(;o(I.StringLiteral);)r+=e[n++].value;return new hS(r)}case I.Identifier:return new pS(t.value);case I.OpenParen:{let e=h();return r(I.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),e}case I.OpenSquareBracket:{let e=[];for(;!o(I.CloseSquareBracket);)e.push(_()),o(I.Comma)&&++n;return++n,new Jue(e)}case I.OpenCurlyBracket:{let e=new Map;for(;!o(I.CloseCurlyBracket);){let t=_();r(I.Colon,`Expected colon between key and value in object literal`);let i=_();e.set(t,i),o(I.Comma)&&++n}return++n,new Yue(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;n0)for(let i=e;it;i+=n)r.push(i);return r}function vS(e,t,n,r=1){let i=Math.sign(r);i>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));let a=[];for(let o=t;i*oe.toUpperCase())}function lde(e){return ude(new Date,e)}function ude(e,t){let n=new Intl.DateTimeFormat(void 0,{month:`long`}),r=new Intl.DateTimeFormat(void 0,{month:`short`}),i=e=>e<10?`0`+e:e.toString();return t.replace(/%[YmdbBHM%]/g,t=>{switch(t){case`%Y`:return e.getFullYear().toString();case`%m`:return i(e.getMonth()+1);case`%d`:return i(e.getDate());case`%b`:return r.format(e);case`%B`:return n.format(e);case`%H`:return i(e.getHours());case`%M`:return i(e.getMinutes());case`%%`:return`%`;default:return t}})}function dde(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function fde(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?RegExp(`(?=)`,`gu`):new RegExp(dde(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var yS=class extends Error{},bS=class extends Error{},xS=class{type=`RuntimeValue`;value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new TS(!!this.value)}toString(){return String(this.value)}},SS=class extends xS{type=`IntegerValue`},CS=class extends xS{type=`FloatValue`;toString(){return this.value%1==0?this.value.toFixed(1):this.value.toString()}},wS=class extends xS{type=`StringValue`;builtins=new Map([[`upper`,new MS(()=>new wS(this.value.toUpperCase()))],[`lower`,new MS(()=>new wS(this.value.toLowerCase()))],[`strip`,new MS(()=>new wS(this.value.trim()))],[`title`,new MS(()=>new wS(cde(this.value)))],[`capitalize`,new MS(()=>new wS(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new SS(this.value.length)],[`rstrip`,new MS(()=>new wS(this.value.trimEnd()))],[`lstrip`,new MS(()=>new wS(this.value.trimStart()))],[`startswith`,new MS(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof wS)return new TS(this.value.startsWith(t.value));if(t instanceof AS){for(let e of t.value){if(!(e instanceof wS))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new TS(!0)}return new TS(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new MS(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof wS)return new TS(this.value.endsWith(t.value));if(t instanceof AS){for(let e of t.value){if(!(e instanceof wS))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new TS(!0)}return new TS(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new MS(e=>{let t=e[0]??new NS;if(!(t instanceof wS||t instanceof NS))throw Error(`sep argument must be a string or null`);let n=e[1]??new SS(-1);if(!(n instanceof SS))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof NS){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new AS(r.map(e=>new wS(e)))})],[`replace`,new MS(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof wS&&n instanceof wS))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new NS:e[2]:new NS,!(r instanceof SS||r instanceof NS))throw Error(`replace() count argument must be a number or null`);return new wS(fde(this.value,t.value,n.value,r.value))})]])},TS=class extends xS{type=`BooleanValue`},pde=/[\x7f-\uffff]/g;function ES(e){return e.replace(pde,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function DS(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=ES(t)),t}case`ArrayValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=` +`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>DS(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=ES(s));let c=`${s}${l}${DS(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var OS=class extends xS{type=`ObjectValue`;__bool__(){return new TS(this.value.size>0)}builtins=new Map([[`get`,new MS(([e,t])=>{if(!(e instanceof wS))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new NS})],[`items`,new MS(()=>this.items())],[`keys`,new MS(()=>this.keys())],[`values`,new MS(()=>this.values())],[`dictsort`,new MS(e=>{let t=new Map,n=e.filter(e=>e instanceof kS?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new TS(!1);if(!(r instanceof TS))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new wS(`key`);if(!(i instanceof wS))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new TS(!1);if(!(a instanceof TS))throw Error(`reverse must be a boolean`);return new AS(Array.from(this.value.entries()).map(([e,t])=>new AS([new wS(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=LS(o,s,r.value);return a.value?-c:c}))})]]);items(){return new AS(Array.from(this.value.entries()).map(([e,t])=>new AS([new wS(e),t])))}keys(){return new AS(Array.from(this.value.keys()).map(e=>new wS(e)))}values(){return new AS(Array.from(this.value.values()))}toString(){return DS(this,{},0,!1)}},kS=class extends OS{type=`KeywordArgumentsValue`},AS=class extends xS{type=`ArrayValue`;builtins=new Map([[`length`,new SS(this.value.length)]]);__bool__(){return new TS(this.value.length>0)}toString(){return DS(this,{},0,!1)}},jS=class extends AS{type=`TupleValue`},MS=class extends xS{type=`FunctionValue`},NS=class extends xS{type=`NullValue`},PS=class extends xS{type=`UndefinedValue`},FS=class{constructor(e){this.parent=e}variables=new Map([[`namespace`,new MS(e=>{if(e.length===0)return new OS(new Map);if(e.length!==1||!(e[0]instanceof OS))throw Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof MS],[`odd`,e=>{if(!(e instanceof SS))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof SS))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof SS||e instanceof CS],[`integer`,e=>e instanceof SS],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof OS],[`sequence`,e=>e instanceof AS||e instanceof OS||e instanceof wS],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,RS(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new PS}catch{return new PS}}};function mde(e){e.set(`false`,!1),e.set(`true`,!0),e.set(`none`,null),e.set(`raise_exception`,e=>{throw Error(e)}),e.set(`range`,sde),e.set(`strftime_now`,lde),e.set(`True`,!0),e.set(`False`,!1),e.set(`None`,null)}function IS(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r instanceof OS)r=r.value.get(e)??new PS;else if(r instanceof AS){let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&te instanceof SS||e instanceof CS||e instanceof TS,i=e=>e instanceof TS?+!!e.value:e.value;if(r(e)&&r(t)){let n=i(e),r=i(t);return nr)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),ri)}default:throw Error(`Cannot compare type: ${e.type}`)}}var hde=class{global;constructor(e){this.global=e??new FS}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let n=this.evaluate(e.left,t);switch(e.operator.value){case`and`:return n.__bool__().value?this.evaluate(e.right,t):n;case`or`:return n.__bool__().value?n:this.evaluate(e.right,t)}let r=this.evaluate(e.right,t);switch(e.operator.value){case`==`:return new TS(n.value==r.value);case`!=`:return new TS(n.value!=r.value)}if(n instanceof PS||r instanceof PS){if(r instanceof PS&&[`in`,`not in`].includes(e.operator.value))return new TS(e.operator.value===`not in`);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}if(n instanceof NS||r instanceof NS)throw Error(`Cannot perform operation on null values`);if(e.operator.value===`~`)return new wS(n.value.toString()+r.value.toString());if((n instanceof SS||n instanceof CS)&&(r instanceof SS||r instanceof CS)){let t=n.value,i=r.value;switch(e.operator.value){case`+`:case`-`:case`*`:{let a=e.operator.value===`+`?t+i:e.operator.value===`-`?t-i:t*i;return n instanceof CS||r instanceof CS?new CS(a):new SS(a)}case`/`:return new CS(t/i);case`%`:{let e=t%i;return n instanceof CS||r instanceof CS?new CS(e):new SS(e)}case`<`:return new TS(t`:return new TS(t>i);case`>=`:return new TS(t>=i);case`<=`:return new TS(t<=i)}}else if(n instanceof AS&&r instanceof AS)switch(e.operator.value){case`+`:return new AS(n.value.concat(r.value))}else if(r instanceof AS){let t=r.value.find(e=>e.value===n.value)!==void 0;switch(e.operator.value){case`in`:return new TS(t);case`not in`:return new TS(!t)}}if(n instanceof wS||r instanceof wS)switch(e.operator.value){case`+`:return new wS(n.value.toString()+r.value.toString())}if(n instanceof wS&&r instanceof wS)switch(e.operator.value){case`in`:return new TS(r.value.includes(n.value));case`not in`:return new TS(!r.value.includes(n.value))}if(n instanceof wS&&r instanceof OS)switch(e.operator.value){case`in`:return new TS(r.value.has(n.value));case`not in`:return new TS(!r.value.has(n.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){let n=[],r=new Map;for(let i of e)if(i.type===`SpreadExpression`){let e=i,r=this.evaluate(e.argument,t);if(!(r instanceof AS))throw Error(`Cannot unpack non-iterable type: ${r.type}`);for(let e of r.value)n.push(e)}else if(i.type===`KeywordArgumentExpression`){let e=i;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw Error(`Positional arguments must come before keyword arguments`);n.push(this.evaluate(i,t))}return[n,r]}applyFilter(e,t,n){if(t.type===`Identifier`){let r=t;if(r.value===`safe`)return e;if(r.value===`tojson`)return new wS(DS(e,{}));if(e instanceof AS)switch(r.value){case`list`:return e;case`first`:return e.value[0];case`last`:return e.value[e.value.length-1];case`length`:return new SS(e.value.length);case`reverse`:return new AS(e.value.slice().reverse());case`sort`:return new AS(e.value.slice().sort((e,t)=>LS(e,t,!1)));case`join`:return new wS(e.value.map(e=>e.value).join(``));case`string`:return new wS(DS(e,{},0,!1));case`unique`:{let t=new Set,n=[];for(let r of e.value)t.has(r.value)||(t.add(r.value),n.push(r));return new AS(n)}default:throw Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof wS)switch(r.value){case`length`:case`upper`:case`lower`:case`title`:case`capitalize`:{let t=e.builtins.get(r.value);if(t instanceof MS)return t.value([],n);if(t instanceof SS)return t;throw Error(`Unknown StringValue filter: ${r.value}`)}case`trim`:return new wS(e.value.trim());case`indent`:return new wS(e.value.split(` +`).map((e,t)=>t===0||e.length===0?e:` `+e).join(` +`));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new SS(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new CS(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof SS||e instanceof CS)switch(r.value){case`abs`:return e instanceof SS?new SS(Math.abs(e.value)):new CS(Math.abs(e.value));case`int`:return new SS(Math.floor(e.value));case`float`:return new CS(e.value);case`string`:return new wS(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof OS)switch(r.value){case`items`:return new AS(Array.from(e.value.entries()).map(([e,t])=>new AS([new wS(e),t])));case`length`:return new SS(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof MS?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof TS)switch(r.value){case`bool`:return new TS(e.value);case`int`:return new SS(+!!e.value);case`float`:return new CS(+!!e.value);case`string`:return new wS(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter "${r.value}" to type: ${e.type}`)}if(t.type===`CallExpression`){let r=t;if(r.callee.type!==`Identifier`)throw Error(`Unknown filter: ${r.callee.type}`);let i=r.callee.value;if(i===`tojson`){let[,t]=this.evaluateArguments(r.args,n),i=t.get(`indent`)??new NS;if(!(i instanceof SS||i instanceof NS))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new TS(!1);if(!(a instanceof TS))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new TS(!1);if(!(o instanceof TS))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new NS,c=null;if(s instanceof AS||s instanceof jS){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof wS)||!(t instanceof wS))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof NS))throw Error(`If set, separators must be a tuple of two strings`);return new wS(DS(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}if(i===`join`){let t;if(e instanceof wS)t=Array.from(e.value);else if(e instanceof AS)t=e.value.map(e=>e.value);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`);let[a,o]=this.evaluateArguments(r.args,n),s=a.at(0)??o.get(`separator`)??new wS(``);if(!(s instanceof wS))throw Error(`separator must be a string`);return new wS(t.join(s.value))}if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new SS(0):new CS(0));if(e instanceof wS){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new SS(t):new CS(t)}if(e instanceof SS||e instanceof CS)return e;if(e instanceof TS)return i===`int`?new SS(+!!e.value):new CS(+!!e.value);throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}if(i==="default"){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new wS(``),o=t[1]??i.get(`boolean`)??new TS(!1);if(!(o instanceof TS))throw Error("`default` filter flag must be a boolean");return e instanceof PS||o.value&&!e.__bool__().value?a:e}if(e instanceof AS){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new TS(!1);if(!(a instanceof TS))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new TS(!1);if(!(o instanceof TS))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new NS;if(!(s instanceof wS||s instanceof SS||s instanceof NS))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof NS?e:IS(e,s instanceof SS?String(s.value):s.value);return new AS(e.value.slice().sort((e,t)=>{let n=LS(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!(e instanceof OS)))throw Error(`\`${i}\` can only be applied to array of objects`);if(r.args.some(e=>e.type!==`StringLiteral`))throw Error(`arguments of \`${i}\` must be strings`);let[a,o,s]=r.args.map(e=>this.evaluate(e,n)),c;if(o){let e=n.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);c=e}else c=(...e)=>e[0].__bool__().value;return new AS(e.value.filter(e=>{let n=e.value.get(a.value),r=n?c(n,s):!1;return t?r:!r}))}case`map`:{let[,t]=this.evaluateArguments(r.args,n);if(t.has(`attribute`)){let n=t.get(`attribute`);if(!(n instanceof wS))throw Error(`attribute must be a string`);let r=t.get(`default`);return new AS(e.value.map(e=>{if(!(e instanceof OS))throw Error(`items in map must be an object`);let t=IS(e,n.value);return t instanceof PS?r??new PS:t}))}throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${i}`)}if(e instanceof wS){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new SS(4);if(!(a instanceof SS))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new TS(!1),s=t.at(2)??i.get(`blank`)??new TS(!1),c=e.value.split(` +`),l=` `.repeat(a.value);return new wS(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(` +`))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof MS))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new kS(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}if(e instanceof OS){let t=e.builtins.get(i);if(t&&t instanceof MS){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new kS(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);return this.applyFilter(n,e.filter,t)}evaluateTestExpression(e,t){let n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw Error(`Unknown test: ${e.test.value}`);let i=r(n);return new TS(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new PS}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new TS(!n.value);default:throw SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n=``;for(let r of e){let e=this.evaluate(r,t);e.type!==`NullValue`&&e.type!==`UndefinedValue`&&(n+=e.toString())}return new wS(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new kS(r));let i=this.evaluate(e.callee,t);if(i.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof AS||e instanceof wS))throw Error(`Slice object must be an array or string`);let r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof SS||r instanceof PS))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof SS||i instanceof PS))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof SS||a instanceof PS))throw Error(`Slice step must be numeric or undefined`);return e instanceof AS?new AS(vS(e.value,r.value,i.value,a.value)):new wS(vS(Array.from(e.value),r.value,i.value,a.value).join(``))}evaluateMemberExpression(e,t){let n=this.evaluate(e.object,t),r;if(e.computed){if(e.property.type===`SliceExpression`)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=new wS(e.property.value);let i;if(n instanceof OS){if(!(r instanceof wS))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof AS||n instanceof wS){if(r instanceof SS)i=n.value.at(r.value),n instanceof wS&&(i=new wS(n.value.at(r.value)));else if(r instanceof wS)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`)}else{if(!(r instanceof wS))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof xS?i:new PS}evaluateSet(e,t){let n=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type===`Identifier`){let r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type===`TupleLiteral`){let r=e.assignee;if(!(n instanceof AS))throw Error(`Cannot unpack non-iterable type in set: ${n.type}`);let i=n.value;if(i.length!==r.value.length)throw Error(`Too ${r.value.length>i.length?`few`:`many`} items to unpack in set`);for(let e=0;et.setVariable(e.loopvar.value,c);else if(e.loopvar.type===`TupleLiteral`){let t=e.loopvar;if(c.type!==`ArrayValue`)throw Error(`Cannot unpack non-iterable type: ${c.type}`);let n=c;if(t.value.length!==n.value.length)throw Error(`Too ${t.value.length>n.value.length?`few`:`many`} items to unpack`);l=e=>{for(let r=0;r0?a[t-1]:new PS],[`nextitem`,t{let r=new FS(n);t=t.slice();let i;t.at(-1)?.type===`KeywordArgumentsValue`&&(i=t.pop());for(let n=0;n{let r=new FS(n);if(e.callerArgs)for(let n=0;nthis.evaluate(e,t)));case`TupleLiteral`:return new jS(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof wS))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new OS(n)}case`Identifier`:return this.evaluateIdentifier(e,t);case`CallExpression`:return this.evaluateCallExpression(e,t);case`MemberExpression`:return this.evaluateMemberExpression(e,t);case`UnaryExpression`:return this.evaluateUnaryExpression(e,t);case`BinaryExpression`:return this.evaluateBinaryExpression(e,t);case`FilterExpression`:return this.evaluateFilterExpression(e,t);case`FilterStatement`:return this.evaluateFilterStatement(e,t);case`TestExpression`:return this.evaluateTestExpression(e,t);case`SelectExpression`:return this.evaluateSelectExpression(e,t);case`Ternary`:return this.evaluateTernaryExpression(e,t);case`Comment`:return new NS;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function RS(e){switch(typeof e){case`number`:return Number.isInteger(e)?new SS(e):new CS(e);case`string`:return new wS(e);case`boolean`:return new TS(e);case`undefined`:return new PS;case`object`:return e===null?new NS:Array.isArray(e)?new AS(e.map(RS)):new OS(new Map(Object.entries(e).map(([e,t])=>[e,RS(t)])));case`function`:return new MS((t,n)=>RS(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var zS=` +`,gde=`{%- `,_de=` -%}`;function vde(e){switch(e.operator.type){case`MultiplicativeBinaryOperator`:return 4;case`AdditiveBinaryOperator`:return 3;case`ComparisonBinaryOperator`:return 2;case`Identifier`:return e.operator.value===`and`?1:e.operator.value===`in`||e.operator.value===`not in`?2:0}return 0}function yde(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return VS(e.body,0,n).replace(/\n$/,``)}function BS(...e){return gde+e.join(` `)+_de}function VS(e,t,n){return e.map(e=>bde(e,t,n)).join(zS)}function bde(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return VS(e.body,t,n);case`If`:return xde(e,t,n);case`For`:return Sde(e,t,n);case`Set`:return Cde(e,t,n);case`Macro`:return wde(e,t,n);case`Break`:return r+BS(`break`);case`Continue`:return r+BS(`continue`);case`CallStatement`:return Tde(e,t,n);case`FilterStatement`:return Ede(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+HS(e)+` -}}`}}function xde(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+BS(`if`,HS(i[0].test))+zS+VS(i[0].body,t+1,n);for(let e=1;e0&&(o+=zS+r+BS(`else`)+zS+VS(a.alternate,t+1,n)),o+=zS+r+BS(`endif`),o}function Sde(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${HS(t.lhs)} if ${HS(t.test)}`}else i=HS(e.iterable);let a=r+BS(`for`,HS(e.loopvar),`in`,i)+zS+VS(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=zS+r+BS(`else`)+zS+VS(e.defaultBlock,t+1,n)),a+=zS+r+BS(`endfor`),a}function Cde(e,t,n){let r=n.repeat(t),i=HS(e.assignee),a=e.value?HS(e.value):``,o=r+BS(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+zS+VS(e.body,t+1,n)+zS+r+BS(`endset`)}function wde(e,t,n){let r=n.repeat(t),i=e.args.map(HS).join(`, `);return r+BS(`macro`,`${e.name.value}(${i})`)+zS+VS(e.body,t+1,n)+zS+r+BS(`endmacro`)}function Tde(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(HS).join(`, `)})`:``,a=HS(e.call),o=r+BS(`call${i}`,a)+zS;return o+=VS(e.body,t+1,n)+zS,o+=r+BS(`endcall`),o}function Ede(e,t,n){let r=n.repeat(t),i=r+BS(`filter`,e.filter.type===`Identifier`?e.filter.value:HS(e.filter))+zS;return i+=VS(e.body,t+1,n)+zS,i+=r+BS(`endfilter`),i}function HS(e,t=-1){switch(e.type){case`SpreadExpression`:return`*${HS(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:return`${e.value}`;case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let n=e,r=vde(n),i=HS(n.left,r),a=HS(n.right,r+1),o=`${i} ${n.operator.value} ${a}`;return r`${HS(e)}: ${HS(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?HS(t.start):``}:${t.stop?HS(t.stop):``}${t.step?`:${HS(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${HS(t.value)}`}case`Ternary`:{let n=e,r=`${HS(n.trueExpr)} if ${HS(n.condition,0)} else ${HS(n.falseExpr)}`;return t>-1?`(${r})`:r}default:throw Error(`Unknown expression type: ${e.type}`)}}var Dde=class{parsed;constructor(e){let t=Iue(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ode(t)}render(e){let t=new FS;if(mde(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new hde(t).run(this.parsed).value}format(e){return yde(this.parsed,e?.indent||` `)}},Ode={txt:`text/plain`,html:`text/html`,css:`text/css`,js:`text/javascript`,json:`application/json`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`},US=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=pb.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=pb.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=pb.createReadStream(e);this.body=new ReadableStream({start(e){n.on(`data`,t=>e.enqueue(t)),n.on(`end`,()=>e.close()),n.on(`error`,t=>e.error(t))},cancel(){n.destroy()}})}else this.status=404,this.statusText=`Not Found`,this.body=null}updateContentType(){let e=this.filePath.toString().split(`.`).pop().toLowerCase();this.headers.set(`content-type`,Ode[e]??`application/octet-stream`)}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await pb.promises.readFile(this.filePath)).buffer}async blob(){let e=await pb.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await pb.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},WS=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null){if(wb.IS_CRYPTO_AVAILABLE){let t=new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0}let t=this._mt,n=(e,t)=>Math.imul(e,t)>>>0,r=[];for(let t=e||0;t>0;t=Math.floor(t/4294967296))r.push(t&4294967295);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(1812433253,t[e-1]^t[e-1]>>>30)+e>>>0;let i=1,a=0;for(let e=Math.max(624,r.length);e>0;--e,++i,++a)i>=624&&(t[0]=t[623],i=1),a>=r.length&&(a=0),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1664525))+r[a]+a>>>0;for(let e=623;e>0;--e,++i)i>=624&&(t[0]=t[623],i=1),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1566083941))-i>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let n=e[t]&2147483648|e[(t+1)%624]&2147483647;e[t]=(e[(t+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let n=this._gauss_next;if(this._gauss_next=null,n===null){let e=this.random()*2*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));n=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+n*t}shuffle(e){for(let t=e.length-1;t>0;--t){let n=32-Math.clz32(t+1),r=this._int32()>>>32-n;for(;r>t;)r=this._int32()>>>32-n;let i=e[t];e[t]=e[r],e[r]=i}}choices(e,t){return e[GS(this._random_fn,t)]}};function GS(e,t){let n=0;for(let e=0;eGS(qS.random,e),Ade=new WS,JS=class{constructor(e){this.path=e}async match(e){let t=new US(mb.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=mb.join(this.path,e),i=r+`.tmp.${wb.IS_PROCESS_AVAILABLE?process.pid:Date.now()}.${Ade._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await pb.promises.mkdir(mb.dirname(r),{recursive:!0});let s=pb.createWriteStream(i),c=t.body.getReader();for(;;){let{done:e,value:t}=await c.read();if(e)break;await new Promise((e,n)=>{s.write(t,t=>{if(t){n(t);return}e()})}),o+=t.length;let r=a?o/a*100:0;n?.({progress:r,loaded:o,total:a})}await new Promise((e,t)=>{s.close(n=>n?t(n):e())}),await pb.promises.rename(i,r)}catch(e){try{await pb.promises.unlink(i)}catch{}throw e}}async delete(e){let t=mb.join(this.path,e);try{return await pb.promises.unlink(t),!0}catch{return!1}}},jde={400:`Bad request error occurred while trying to load file`,401:`Unauthorized access to file`,403:`Forbidden access to file`,404:`Could not locate file`,408:`Request timeout error occurred while trying to load file`,500:`Internal server error error occurred while trying to load file`,502:`Bad gateway error occurred while trying to load file`,503:`Service unavailable error occurred while trying to load file`,504:`Gateway timeout error occurred while trying to load file`},YS=100,Mde=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function XS(...e){return e=e.map((t,n)=>(n&&(t=t.replace(RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(RegExp(`/$`),``)),t)),e.join(`/`)}function ZS(e,t=null,n=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||n&&!n.includes(r.hostname))}function Nde(e){return!(!Mde.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function Pde(e,t,n){if(!n)return null;let r=jde[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}async function Fde(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&Wb.warn(`Unable to determine content-length from response headers. Will expand buffer when needed.`);let a=new Uint8Array(i),o=0,s=e.body.getReader();async function c(){let{done:e,value:n}=await s.read();if(e)return;let r=o+n.length;if(r>i){i=r;let e=new Uint8Array(i);e.set(a),a=e}return a.set(n,o),o=r,t({progress:o/i*100,loaded:o,total:i}),c()}return await c(),a}function QS(e){return ZS(e,[`blob:`])}function $S(e){let t;if(typeof location<`u`&&location.href)t=location.href;else if(import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var eC=`SHA-256`,Ide=`experimental_transformers-hash-cache`,tC=e=>({algorithm:eC,value:e}),nC=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(Ide),this.#e);static isAvailable=()=>typeof navigator<`u`&&`crossOriginStorage`in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let[e]=await navigator.crossOriginStorage.requestFileHandles([tC(t)]),n=await e.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,t)=>{let n=await this._getFileHash(e);if(n){let e=await t.blob();await this._storeBlobInCOS(e,n)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let[n]=await navigator.crossOriginStorage.requestFileHandles([tC(t)],{create:!0}),r=await n.createWritable();await r.write(e),await r.close()};_processAndStore=async(e,t)=>{try{let n=[];for await(let e of t)n.push(e);let r=new Blob(n),i=await this._getBlobHash(r);await this._storeBlobInCOS(r,i);try{await(await this._getHashCache()).put(e,new Response(i))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),n=await t.match(e);if(n)return n.text();let r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes(`/resolve/`))return null;let t=e.replace(`/resolve/`,`/raw/`);try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),n=await crypto.subtle.digest(eC,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function rC(e=null){let t=null;if(jb.useCustomCache){if(!jb.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!jb.customCache.match||!jb.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=jb.customCache}if(!t&&jb.experimental_useCrossOriginStorage&&nC.isAvailable()&&(t=new nC),!t&&jb.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(jb.cacheKey)}catch(e){Wb.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&jb.useFSCache){if(!wb.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new JS(e??jb.cacheDir)}return t}async function Lde(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var iC=new class{#e;#t;constructor(e){this.#e=e,this.#t=new Map}get(e){if(!this.#t.has(e))return;let t=this.#t.get(e);return this.#t.delete(e),this.#t.set(e,t),t}put(e,t){this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e&&this.#t.delete(this.#t.keys().next().value)}delete(e){return this.#t.delete(e)}clear(){this.#t.clear()}}(100);function aC(e,t){let n=iC.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(iC.delete(e),Promise.reject(t)));return iC.put(e,r),r}async function Rde(e){if(!ZS(e,[`http:`,`https:`]))return null;let t=cC(e);return t.set(`Range`,`bytes=0-0`),jb.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function oC(e,t,n={}){return aC(JSON.stringify([e,t,n?.revision,n?.cache_dir,n?.local_files_only]),()=>zde(e,t,n))}async function zde(e,t,n){let r=await rC(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=lC(e,t,n,r),c=await uC(r,i,o);if(c!==void 0&&typeof c!=`string`){let e=c.headers.get(`content-length`),t=c.headers.get(`content-type`);return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if(jb.allowLocalModels&&!ZS(i,[`http:`,`https:`]))try{let e=await sC(i);if(typeof e!=`string`&&e.status!==404){let t=e.headers.get(`content-length`),n=e.headers.get(`content-type`);return{exists:!0,size:t?parseInt(t,10):void 0,contentType:n||void 0,fromCache:!1}}}catch{}if(jb.allowRemoteModels&&!n.local_files_only&&s)try{let e=await Rde(a);if(e&&e.status>=200&&e.status<300){let t,n=e.headers.get(`content-type`);if(e.status===206){let n=e.headers.get(`content-range`);if(n){let e=n.match(/bytes \d+-\d+\/(\d+)/);e&&(t=parseInt(e[1],10))}}else if(e.status===200)try{await e.body?.cancel()}catch{}if(t===void 0){let n=e.headers.get(`content-length`);t=n?parseInt(n,10):void 0}return{exists:!0,size:t,contentType:n||void 0,fromCache:!1}}}catch(e){Wb.warn(`Unable to fetch file metadata for "${a}": ${e}`)}return{exists:!1,fromCache:!1}}async function sC(e){return jb.useFS&&!ZS(e,[`http:`,`https:`,`blob:`])?new US(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):jb.fetch(e,{headers:cC(e)})}function cC(e){let t=typeof process<`u`&&process?.release?.name===`node`,n=new Headers;if(t){let t=!!{}.TESTING_REMOTELY,r=jb.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),ZS(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e={}.HF_TOKEN??{}.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function lC(e,t,n={},r=null){let i=n.revision??`main`,a=XS(e,t),o=Nde(e),s=o?XS(jb.localModelPath,a):a,c=XS(jb.remoteHost,jb.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof JS?i===`main`?a:XS(e,i,t):c,validModelId:o}}async function uC(e,t,n){if(e)return await Lde(e,t,n)}async function Bde(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0){if(!a){let a=o.progress_callback?n=>Pb(o.progress_callback,{status:`progress`,name:e,file:t,...n}):void 0;await n.put(r,i,a)}else if(typeof i!=`string`){let e=new Headers(i.headers);e.set(`content-length`,a.byteLength.toString()),await n.put(r,new Response(a,{headers:e})).catch(e=>{Wb.warn(`Unable to add response to browser cache: ${e}.`)})}}}async function Vde(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=lC(e,t,r,a),d,f=!1,p;p=await uC(a,s,l);let m=p!==void 0;if(m)d=l;else{if(jb.allowLocalModels){if(!ZS(o,[`http:`,`https:`]))try{p=await sC(s),d=s}catch(e){Wb.warn(`Unable to load from local path "${s}": "${e}"`)}else if(r.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);else if(!jb.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=`string`&&p.status===404){if(r.local_files_only||!jb.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${s}".`);return null}if(!u)throw Error(`Local file missing at "${s}" and download aborted due to invalid model ID "${e}".`);if(p=await sC(c),p.status!==200)return Pde(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}Pb(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(wb.IS_NODE_ENV&&i)){let n;if(typeof p!=`string`){if(!r.progress_callback)n=new Uint8Array(await p.arrayBuffer());else if(m&&typeof navigator<`u`&&/firefox/i.test(navigator.userAgent))n=new Uint8Array(await p.arrayBuffer()),Pb(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n.length,total:n.length});else{let i,a=p.headers.get(`content-length`);if(a)i=parseInt(a,10);else try{let n=await oC(e,t,r);n.size&&(i=n.size)}catch{}n=await Fde(p,n=>{Pb(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}}h=n}if(f&&d&&typeof p!=`string`&&await Bde(e,t,a,d,p,h,r),wb.IS_NODE_ENV&&i&&r.progress_callback&&typeof p!=`string`){let n=parseInt(p.headers.get(`content-length`),10)||0;Pb(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n,total:n})}if(Pb(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!wb.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof US)return p.filePath;let g=await a?.match(d);if(g instanceof US)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g==`string`)return g;throw Error(`Unable to get model file path or buffer.`)}var dC=new Map;async function fC(e,t,n=!0,r={},i=!1){if(!jb.allowLocalModels){if(r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!jb.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}Pb(r.progress_callback,{status:`initiate`,name:e,file:t});let a=`${e}::${t}`,o=dC.get(a);return o||(o=Vde(e,t,n,r,i,await rC(r?.cache_dir)).then(e=>(dC.delete(a),e),e=>{throw dC.delete(a),e}),dC.set(a,o)),await o}async function pC(e,t,n=!0,r={}){let i=await fC(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function mC(e,t,n=!0,r={}){let i=await pC(e,t,n,r);return i===null?{}:JSON.parse(i)}function Hde(e,[t,n,r],[i,a],o=`bilinear`,s=!1){let c=a/r,l=i/n,u=new e.constructor(i*a*t),d=n*r,f=i*a;for(let o=0;o=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];let a=n.map((e,t)=>i[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function hC(e){let t=_C(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}function Wde(e){let t=_C(e)[0],n=0;for(let r=0;re-t-r)}function gC(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[t,n]}function vC(e){return e>0&&!(e&e-1)}var yC=class{constructor(e){if(this.size=e|0,this.size<=1||!vC(this.size))throw Error(`FFT size must be a power of two larger than 1`);this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,-1);for(let t=0;t>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o>>1,i>>>1)}else for(o=0,s=0;o>>1,i>>>1,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>1,s=t>>>1,c=s>>>1;for(o=0;o>>1;for(let t=2;t>1;++t){let n=(t+1-e)**2/2,r=Math.sqrt(s**2+c**2)**n,o=n*Math.atan2(c,s),l=2*t;i[l]=r*Math.cos(o),i[l+1]=r*Math.sin(o),a[l]=i[l],a[l+1]=-i[l+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new yC(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){let r=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,s=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(n)for(let e=0;e>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function CC(e,t){let n=10**t;return Math.round(e*n)/n}function wC(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function TC(e){let t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));i[0][0]=0;let a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let t=1;t0||s>0;)switch(c.push(o-1),l.push(s-1),a[o][s]){case 0:--o,--s;break;case 1:--o;break;case 2:--s;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${s}]. Please file a bug report.`)}return c.reverse(),l.reverse(),[c,l]}var EC=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let t=new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t>10,s=t&1023;if(o===31)i=a|2139095040|s<<13;else if(o===0){if(s===0)i=a;else{let e=113;for(;!(s&1024);)s<<=1,--e;s&=-1025,i=a|e<<23|s<<13}}else i=a|o+112<<23|s<<13;n[0]=i,e[t]=r[0]}}let n=t.length,r=e,i=new Float32Array(n);for(let e=0;eOC});var OC={};async function kC(e){let t=e.split(`/`).pop(),n;try{if(n=await rC(),n){let t=await n.match(e);if(t)return t}}catch(e){Wb.warn(`Failed to load ${t} from cache:`,e)}let r=await jb.fetch(e);if(!r.ok)throw Error(`Failed to fetch ${t}: ${r.status} ${r.statusText}`);if(n)try{await n.put(e,r.clone())}catch(e){Wb.warn(`Failed to cache ${t}:`,e)}return r}async function AC(e){let t=await kC(e);if(!t||typeof t==`string`)return null;try{return await t.arrayBuffer()}catch(e){return Wb.warn(`Failed to read WASM binary:`,e),null}}async function jC(e){if(wb.IS_SERVICE_WORKER_ENV||wb.IS_CHROME_AVAILABLE)return e;let t=await kC(e);if(!t||typeof t==`string`)return null;try{let e=await t.text();e=e.replaceAll(`globalThis.process?.versions?.node`,`false`);let n=new Blob([e],{type:`text/javascript`});return URL.createObjectURL(n)}catch(e){return Wb.warn(`Failed to read WASM factory:`,e),null}}var MC=Object.freeze({auto:null,gpu:null,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:{name:`webnn`,deviceType:`cpu`},"webnn-npu":{name:`webnn`,deviceType:`npu`},"webnn-gpu":{name:`webnn`,deviceType:`gpu`},"webnn-cpu":{name:`webnn`,deviceType:`cpu`}});function NC(e){return e<=kb.DEBUG?0:e<=kb.INFO?2:e<=kb.WARNING||e<=kb.ERROR?3:4}var PC={0:`verbose`,1:`info`,2:`warning`,3:`error`,4:`fatal`},FC=[],IC,LC,RC=Symbol.for(`onnxruntime`);if(RC in globalThis)LC=globalThis[RC];else if(wb.IS_NODE_ENV){switch(LC=DC,process.platform){case`win32`:FC.push(`dml`);break;case`linux`:process.arch===`x64`&&FC.push(`cuda`);break;case`darwin`:FC.push(`coreml`)}FC.push(`webgpu`),FC.push(`cpu`),IC=[`cpu`]}else LC=Dle,wb.IS_WEBNN_AVAILABLE&&FC.push(`webnn-npu`,`webnn-gpu`,`webnn-cpu`,`webnn`),wb.IS_WEBGPU_AVAILABLE&&FC.push(`webgpu`),FC.push(`wasm`),IC=[`wasm`];var zC=LC.InferenceSession;function BC(e=null){if(!e)return IC;switch(e){case`auto`:return FC;case`gpu`:return FC.filter(e=>[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(FC.includes(e))return[MC[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${FC.join(`, `)}.`)}var VC=Promise.resolve(),HC=null;async function UC(){if(HC)return HC;if(!(jb.useWasmCache&&typeof JC?.wasm?.wasmPaths==`object`&&JC?.wasm?.wasmPaths?.wasm&&JC?.wasm?.wasmPaths?.mjs)){if(wb.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return HC=Promise.resolve(),HC}return HC=(async()=>{let e=JC.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!QS(e.wasm)?(async()=>{try{let n=await AC($S(e.wasm));n&&(JC.wasm.wasmBinary=n,t=!0)}catch(e){Wb.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!QS(e.mjs)?(async()=>{try{let t=await jC($S(e.mjs));t&&(JC.wasm.wasmPaths.mjs=t)}catch(e){Wb.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(JC.wasm.wasmPaths.mjs=e.mjs)})(),HC}async function WC(e,t,n){await UC();let r=NC(jb.logLevel??kb.WARNING),i=()=>zC.create(e,{logSeverityLevel:r,...t}),a=await(wb.IS_WEB_ENV?VC=VC.then(i):i());return a.config=n,a}var GC=Promise.resolve();async function KC(e,t){let n=()=>e.run(t);return wb.IS_WEB_ENV?GC=GC.then(n):n()}function qC(e){return e instanceof LC.Tensor}var JC=LC?.env;function YC(){return JC?.wasm?.proxy}if(JC){let e=function(e){JC.logLevel=PC[NC(e)]};if(JC.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&JC.versions?.web&&!JC.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${JC.versions.web}/dist/`;JC.wasm.wasmPaths=wb.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}JC.wasm.proxy=!1}JC.webgpu&&(JC.webgpu.powerPreference=`high-performance`),e(jb.logLevel??kb.WARNING),jb.backends.onnx={...JC,setLogLevel:e}}var XC=async(e,t,n)=>{let r=await WC(new Uint8Array(e),t);return(async e=>{let t=YC(),i=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])),a=await KC(r,i);return Array.isArray(n)?n.map(e=>new L(a[e])):new L(a[n])})},ZC=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=XC([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,`y`),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||=XC([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||=XC([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||=XC([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,`c`),this._matmul}static get stft(){return this._stft||=XC([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,`o`),this._stft}static get rfft(){return this._rfft||=XC([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,`y`),this._rfft}static get top_k(){return this._top_k||=XC([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,[`v`,`i`]),this._top_k}static get slice(){return this._slice||=XC([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,`y`),this._slice}},QC=Object.freeze({auto:`auto`,gpu:`gpu`,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:`webnn`,"webnn-npu":`webnn-npu`,"webnn-gpu":`webnn-gpu`,"webnn-cpu":`webnn-cpu`}),$C=wb.IS_NODE_ENV?`cpu`:`wasm`;function ew(e,t,{warn:n}={}){return e?typeof e==`string`?e:e.hasOwnProperty(t)?e[t]:(n&&n(`device not specified for "${t}". Using the default device (${$C}).`),$C):$C}var tw=(function(){let e;return async function(){if(e===void 0){if(!wb.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}}return e}})(),nw=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`,q2:`q2`,q2f16:`q2f16`,q1:`q1`,q1f16:`q1f16`}),rw=nw.fp32,iw=Object.freeze({[QC.wasm]:nw.q8}),aw=Object.freeze({[nw.fp32]:``,[nw.fp16]:`_fp16`,[nw.int8]:`_int8`,[nw.uint8]:`_uint8`,[nw.q8]:`_quantized`,[nw.q4]:`_q4`,[nw.q2]:`_q2`,[nw.q1]:`_q1`,[nw.q4f16]:`_q4f16`,[nw.q2f16]:`_q2f16`,[nw.q1f16]:`_q1f16`,[nw.bnb4]:`_bnb4`});function ow(e,t,n,{configDtype:r=null,warn:i}={}){let a,o=!1;e&&typeof e!=`string`?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let s;if(a===nw.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==nw.auto&&nw.hasOwnProperty(e))return e}s=iw[n]??rw}else s=a&&nw.hasOwnProperty(a)?a:iw[n]??rw;return o&&i&&i(`dtype not specified for "${t}". Using the default dtype (${s}) for this device (${n}).`),s}var sw=Object.freeze({float32:Float32Array,float16:typeof Float16Array<`u`?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),L=class e{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return this.ort_tensor=qC(e[0])?e[0]:new eue(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if(typeof t==`string`){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}return new e(this.type,[this.data[t]],r)}indexOf(e){let t=this.data;for(let n=0;na)throw Error(`Invalid slice: ${i}`);let o=[Math.max(t,0),Math.min(a,this.dims[e])];r.push(o),n.push(o[1]-o[0])}else throw Error(`Invalid slice: ${i}`)}let i=r.map(([e,t])=>t-e),a=i.reduce((e,t)=>e*t),o=this.data,s=new o.constructor(a),c=this.stride(),l=!0;for(let e=1;e=0;--n){let e=i[n];t+=(a%e+r[n][0])*c[n],a=Math.floor(a/e)}s[e]=o[t]}return new e(this.type,s,n)}permute(...e){return lw(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t=`fro`,n=null,r=!1){if(t===`fro`)t=2;else if(typeof t==`string`)throw Error(`Unsupported norm: ${t}`);let i=this.data,a=i instanceof BigInt64Array||i instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,s;if(a?(o=(e,t)=>e+t,s=0n):(o=(e,n)=>e+n**t,s=0),n===null){let n=i.reduce(o,s);return t!==1&&(n**=1/t),new e(this.type,[n],[])}let[c,l,u]=Sw(o,this,n,r);if(t!==1)for(let e=0;e=0;--r){let e=this.dims[r];if(r!==t){let t=i%e;n+=t*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return Tw(this.dims)}squeeze(t=null){return new e(this.type,this.data,_w(this.dims,t))}squeeze_(e=null){return this.dims=_w(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,vw(this.dims,t))}unsqueeze_(e){return this.dims=vw(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let n=-1;for(let e=0;er===n?e:e*t,1);t[n]=r.length/e}return new e(this.type,r,t)}neg_(){let e=this.data;for(let t=0;tt);return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;eMath.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=_C(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=Sw((e,t)=>Math.max(e,t),this,t,n,-1/0);return new e(r,i,a)}argmin(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=gC(this.data)[1];return new e(`int64`,[BigInt(r)],[])}argmax(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=_C(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.lengthe===1)){if(t.length===this.dims.length)return this.clone();let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),r)}let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims),i=r.map((e,n)=>e*t[n]),a=i.reduce((e,t)=>e*t,1),o=this.data,s=new o.constructor(a),c=Tw(r),l=Tw(i);for(let e=0;eBigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,EC(this.data),this.dims);return new e(t,sw[t].from(this.data,n),this.dims)}};function cw(e,t){let n=e.length;if(n!==t.reduce((e,t)=>e*t))throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce((n,r)=>{let i=n[n.length-1];return i.lengthnew L(`int64`,e,[e.length]);async function hw(e,t,n,r,i){return await(await ZC.slice)({x:e,s:mw(t),e:mw(n),a:mw(r),t:mw(i??Array(r.length).fill(1))})}function gw(e,t){let n=e.data,r=t.data,i=[e.dims[0],e.dims[2]],a=new n.constructor(i[0]*i[1]),[o,s,c]=e.dims,l=0;for(let e=0;ee!==1):typeof t==`number`?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>e!==1||!t.includes(n))),e}function vw(e,t){return t=yw(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function yw(e,t,n=null,r=!0){if(e<-t||e>=t){if(r)throw Error(`IndexError: index ${e} is out of bounds for dimension${n===null?``:` `+n} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function bw(e,t=0){t=yw(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let t=0;for(let n of e){let e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a=0;--i){let e=s[i],l=o%e;i===t&&(l+=r),a+=l*c,c*=n[i],o=Math.floor(o/e)}i[a]=o[e]}r+=s[t]}}return new L(a,i,n)}function xw(e,t=0){return bw(e.map(e=>e.unsqueeze(t)),t)}function Sw(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=yw(n,o.length);let s=o.slice();s[n]=1;let c=new a.constructor(a.length/o[n]);i!==null&&c.fill(i);for(let t=0;t=0;--e){let t=o[e];if(e!==n){let n=i%t;r+=n*a,a*=s[e]}i=Math.floor(i/t)}c[r]=e(c[r],a[t],t,r)}return r||s.splice(n,1),[t.type,c,s]}function Cw(e,t=null,n=1,r=!1){let i=e.data,a=e.dims;if(t===null){let t=i.reduce((e,t)=>e+t,0)/i.length,r=Math.sqrt(i.reduce((e,n)=>e+(n-t)**2,0)/(i.length-n)),a=new L(e.type,[t],[]);return[new L(e.type,[r],[]),a]}t=yw(t,a.length);let o=ww(e,t,r),s=o.data,[c,l,u]=Sw((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;ee+t,0);return new L(e.type,[t/i.length],[])}t=yw(t,r.length);let[a,o,s]=Sw((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e=0;--n)t[n]=r,r*=e[n];return t}function Ew(e,t,n,r){return new L(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function Dw(e,t){let n,r;if(typeof t==`number`)n=`float32`,r=Float32Array;else if(typeof t==`bigint`)n=`int64`,r=BigInt64Array;else if(typeof t==`boolean`)n=`bool`,r=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return Ew(e,t,n,r)}function Ow(e,t){return Dw(e.dims,t)}function kw(e){return Ew(e,1n,`int64`,BigInt64Array)}function Aw(e){return kw(e.dims)}function jw(e){return Ew(e,0n,`int64`,BigInt64Array)}function Mw(e){return jw(e.dims)}function Nw(e){let t=e.reduce((e,t)=>e*t,1);return new L(`float32`,Float32Array.from({length:t},()=>qS.gauss()),e)}function Pw(e,t){if(e.dims.length!==2)throw Error(`The tensor must have 2 dimensions`);if(e.dims.at(-1)%8!=0)throw Error(`The last dimension of the tensor must be a multiple of 8`);if(![`binary`,`ubinary`].includes(t))throw Error(`The precision must be either 'binary' or 'ubinary'`);let n=t===`binary`,r=n?`int8`:`uint8`,i=n?Int8Array:Uint8Array,a=e.data,o=new i(a.length/8);for(let e=0;e0),r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new L(r,o,[e.dims[0],e.dims[1]/8])}async function Fw(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await oC(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function Iw(e,t){let n=await Fw(e);return await Promise.all(n.map(n=>mC(e,n,!0,t)))}function Lw(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var Rw=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function zw(e,t,n,r){for(let i of Object.keys(e)){let a=t-e[i].length,o=n(i),s=Array(a).fill(o);e[i]=r===`right`?zb(e[i],s):zb(s,e[i])}}function Bw(e,t){for(let n of Object.keys(e))e[n].length=t}function Vw(e,...t){for(let n of t){if(!Object.hasOwn(e,n))continue;let t=e[n];if(t){if(typeof t==`object`){if(t.__type===`AddedToken`)return t.content;throw Error(`Unknown token: ${t}`)}return t}}return null}function Hw(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var Uw=class extends Nb{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new Mue(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Vw(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Vw(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Vw(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Vw(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Vw(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Vw(t,`eos_token`),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=Object.create(null);for(let{name:t,template:n}of this.chat_template){if(typeof t!=`string`||typeof n!=`string`)throw Error(`Chat template must be a list of objects with "name" and "template" properties`);e[t]=n}this.chat_template=e}this._compiled_template_cache=new Map;let n=Hw(this._tokenizer);this.all_special_ids=n.map(e=>e.id),this.all_special_tokens=n.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let o=await Iw(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e==`string`?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,t={}){let{text_pair:n=null,add_special_tokens:r=!0,padding:i=!1,return_token_type_ids:a=null}=t,{truncation:o=null,max_length:s=null}=t,c=t.return_tensor??!0,l=Array.isArray(e),u;if(l){if(e.length===0)throw Error(`text array must be non-empty`);if(n!==null){if(!Array.isArray(n))throw Error(`text_pair must also be an array`);if(e.length!==n.length)throw Error(`text and text_pair must have the same length`);u=e.map((e,t)=>this._encode_plus(e,{text_pair:n[t],add_special_tokens:r,return_token_type_ids:a}))}else u=e.map(e=>this._encode_plus(e,{add_special_tokens:r,return_token_type_ids:a}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:n,add_special_tokens:r,return_token_type_ids:a})]}if(s===null?s=this.model_max_length:o===null&&(i===!0?(Wb.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),s=this.model_max_length):i===!1&&(Wb.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),i===!0&&(s=Math.min(_C(u.map(e=>e.input_ids.length))[0],s??1/0)),s=Math.min(s,this.model_max_length??1/0),i||o)for(let e=0;es?o&&Bw(u[e],s):i&&zw(u[e],s,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let d={};if(c){if(!(i&&o)&&u.some(e=>{for(let t of Object.keys(e))if(e[t].length!==u[0][t]?.length)return!0;return!1}))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.`);let e=[u.length,u[0].input_ids.length];for(let t of Object.keys(u[0]))d[t]=new L(`int64`,BigInt64Array.from(u.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(u[0]))d[e]=u.map(t=>t[e]);if(!l)for(let e of Object.keys(d))d[e]=d[e][0]}return d}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{ids:i,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:i,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:n})}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof L&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof L&&(e=Lw(e)),!Array.isArray(e)||e.length===0||!Ib(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template==`object`){let n=this.chat_template;if(e!==null&&Object.hasOwn(n,e))e=n[e];else if(e===null){if(t!==null&&`tool_use`in n)e=n.tool_use;else if(`default`in n)e=n.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`)}}else if(e===null){if(this.chat_template)e=this.chat_template;else throw Error(`Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating`)}return e}apply_chat_template(e,t={}){let{tools:n=null,documents:r=null,chat_template:i=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:s=!1,truncation:c=!1,max_length:l=null,return_tensor:u=!0,return_dict:d=!0,tokenizer_kwargs:f={},...p}=t;if(i=this.get_chat_template({chat_template:i,tools:n}),typeof i!=`string`)throw Error(`chat_template must be a string, but got ${typeof i}`);let m=this._compiled_template_cache.get(i);m===void 0&&(m=new Dde(i),this._compiled_template_cache.set(i,m));let h=Object.create(null);for(let e of Rw){let t=Vw(this.config,e);t&&(h[e]=t)}let g=m.render({messages:e,add_generation_prompt:a,tools:n,documents:r,...h,...p});if(o){let e=this._call(g,{add_special_tokens:!1,padding:s,truncation:c,max_length:l,return_tensor:u,...f});return d?e:e.input_ids}return g}};function Ww(e,t,n,r){if(!(`language_codes`in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!(`languageRegex`in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!(`lang_to_token`in e)||typeof e.lang_to_token!=`function`)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);for(let t of e._tokenizer.post_processor.config.single)if(`SpecialToken`in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(i);break}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,n)}var Gw={};fb(Gw,{AlbertTokenizer:()=>Kw,AutoTokenizer:()=>WT,BartTokenizer:()=>qw,BertTokenizer:()=>Jw,BlenderbotSmallTokenizer:()=>Yw,BlenderbotTokenizer:()=>Xw,BloomTokenizer:()=>Zw,CLIPTokenizer:()=>$w,CamembertTokenizer:()=>Qw,CodeGenTokenizer:()=>tT,CodeLlamaTokenizer:()=>eT,CohereAsrTokenizer:()=>rT,CohereTokenizer:()=>nT,ConvBertTokenizer:()=>iT,DebertaTokenizer:()=>oT,DebertaV2Tokenizer:()=>aT,DistilBertTokenizer:()=>sT,ElectraTokenizer:()=>cT,EsmTokenizer:()=>lT,FalconTokenizer:()=>uT,GPT2Tokenizer:()=>pT,GPTNeoXTokenizer:()=>fT,GemmaTokenizer:()=>dT,HerbertTokenizer:()=>mT,LlamaTokenizer:()=>hT,M2M100Tokenizer:()=>gT,MBart50Tokenizer:()=>yT,MBartTokenizer:()=>vT,MPNetTokenizer:()=>ST,MarianTokenizer:()=>_T,MgpstrTokenizer:()=>bT,MobileBertTokenizer:()=>xT,NllbTokenizer:()=>CT,NougatTokenizer:()=>wT,PreTrainedTokenizer:()=>Uw,Qwen2Tokenizer:()=>TT,RoFormerTokenizer:()=>DT,RobertaTokenizer:()=>ET,SiglipTokenizer:()=>OT,SpeechT5Tokenizer:()=>kT,SqueezeBertTokenizer:()=>AT,T5Tokenizer:()=>jT,TokenizersBackend:()=>Uw,VitsTokenizer:()=>NT,Wav2Vec2CTCTokenizer:()=>PT,WhisperTokenizer:()=>VT,XLMRobertaTokenizer:()=>HT,XLMTokenizer:()=>UT});var Kw=class extends Uw{return_token_type_ids=!0},qw=class extends Uw{},Jw=class extends Uw{return_token_type_ids=!0},Yw=class extends Uw{},Xw=class extends Uw{},Zw=class extends Uw{},Qw=class extends Uw{},$w=class extends Uw{},eT=class extends Uw{},tT=class extends Uw{},nT=class extends Uw{},rT=class extends Uw{},iT=class extends Uw{return_token_type_ids=!0},aT=class extends Uw{return_token_type_ids=!0},oT=class extends Uw{return_token_type_ids=!0},sT=class extends Uw{},cT=class extends Uw{return_token_type_ids=!0},lT=class extends Uw{},uT=class extends Uw{},dT=class extends Uw{},fT=class extends Uw{},pT=class extends Uw{},mT=class extends Uw{return_token_type_ids=!0},hT=class extends Uw{padding_side=`left`},gT=class extends Uw{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return Ww(this,e,t,n)}},_T=class extends Uw{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),Wb.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[t,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(t);if(n.length===2){let[e,t]=n;return this.supported_language_codes.includes(e)||Wb.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),zb([e],super._encode_text(t))}}},vT=class extends Uw{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Ww(this,e,t,n)}},yT=class extends vT{},bT=class extends Uw{},xT=class extends Uw{return_token_type_ids=!0},ST=class extends Uw{},CT=class extends Uw{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Ww(this,e,t,n)}},wT=class extends Uw{},TT=class extends Uw{},ET=class extends Uw{},DT=class extends Uw{return_token_type_ids=!0},OT=class extends Uw{},kT=class extends Uw{},AT=class extends Uw{return_token_type_ids=!0},jT=class extends Uw{},MT=class extends iS{decode_chain(e){let t=``;for(let n=1;n[t,e]),[`burmese`,`my`],[`valencian`,`ca`],[`flemish`,`nl`],[`haitian`,`ht`],[`letzeburgesch`,`lb`],[`pushto`,`ps`],[`panjabi`,`pa`],[`moldavian`,`ro`],[`moldovan`,`ro`],[`sinhalese`,`si`],[`castilian`,`es`]]);function RT(e){e=e.toLowerCase();let t=LT.get(e);if(t===void 0){let n=e.match(/^<\|([a-z]{2})\|>$/);if(n&&(e=n[1]),IT.has(e))t=e;else{let t=e.length===2?IT.keys():IT.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var zT=RegExp(`^[\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]+$`,`gu`),BT=.1,VT=class extends Uw{get timestamp_begin(){return this._tokenizer.token_to_id(`<|notimestamps|>`)+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(r===null)throw Error(`Must specify time_precision`);let a=null,o=t===`word`;function s(){return{language:a,timestamp:[null,null],text:``}}let c=[],l=s(),u=0,d=this.timestamp_begin,f=d+1500,p=[],m=[],h=!1,g=null,_=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,i=o?n.token_timestamps:null,v=null,y=d;if(`stride`in n){let[t,i,a]=n.stride;if(u-=i,g=t-a,i&&(y=i/r+d),a)for(let t=e.length-1;t>=0;--t){let n=Number(e[t]);if(n>=d){if(v!==null&&(n-d)*r=d&&g<=f){let e=CC((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g0&&l.timestamp[1]!==null))for(let e of l.words)e.timestamp[1]>l.timestamp[1]&&l.timestamp[1]>=e.timestamp[0]&&(e.timestamp[1]=l.timestamp[1]);c.push(l),p=[],b=[],m=[],x=[],l=s()}}else if(b.push(g),o){let e=CC(i[n]+u,2),t;if(n+10?(p.push(b),o&&m.push(x)):p.every(e=>e.length===0)&&(l=s(),p=[],b=[],m=[],x=[])}if(p.length>0){if(i&&t)throw Error(`Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.`);let[e,n]=this.findLongestCommonSequence(p,m),r=this.decode(e);l.text=r,o&&(l.words=this.collateWordTimestamps(e,n,a)),c.push(l)}let v=Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e0,o=a?[]:null,s=a?t[0]:null;for(let c=1;ce===g[n]&&s[i+n][0]-BT<=t[c][m+n][0]).length:p.filter((e,t)=>e===g[t]).length;let v=e/1e4,y=_/e+v;_>1&&y>u&&(u=y,d=[i,o,m,h])}let[p,m,h,g]=d,_=Math.floor((m+p)/2),v=Math.floor((g+h)/2);if(a&&u===0&&r>0){let e=s[r-1][0],n=t[c].findIndex(t=>t[0]>=e);v=n===-1?l.length:n}i.push(...n.slice(0,_)),n=l.slice(v),r=n.length,a&&(o.push(...s.slice(0,_)),s=t[c].slice(v))}return i.push(...n),a?(o.push(...s),[i,o]):[i,[]]}collateWordTimestamps(e,t,n){let[r,i,a]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e=r){let e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map(e=>typeof e==`string`?e:super.decode(e,t)),i.join(``)}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[],a=[],o=[],s=0;for(let c=0;c=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=zT.test(f);if(u||d||p||i.length===0)i.push(s),a.push(c),o.push(l);else{let e=i.length-1;i[e]+=s,a[e].push(...c),o[e].push(...l)}}return[i,a,o]}mergePunctuations(e,t,n,r,i){let a=structuredClone(e),o=structuredClone(t),s=structuredClone(n),c=a.length-2,l=a.length-1;for(;c>=0;)a[c].startsWith(` `)&&r.includes(a[c].trim())?(a[l]=a[c]+a[l],o[l]=zb(o[c],o[l]),s[l]=zb(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;le),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},HT=class extends Uw{},UT=class extends Uw{return_token_type_ids=!0;constructor(e,t){super(e,t),Wb.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},WT=class{static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let[o,s]=await Iw(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=Gw[c];return l||=(Wb.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),Uw),new l(o,s)}},GT=`https://github.com/huggingface/transformers.js/issues/new/choose`,KT=`preprocessor_config.json`,qT=KT,JT=`processor_config.json`,YT=`chat_template.jinja`,XT=class extends Nb{static classes=[`image_processor_class`,`tokenizer_class`,`feature_extractor_class`];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,n){super(),this.config=e,this.components=t,this.chat_template=n}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw Error(`Unable to apply chat template without a tokenizer.`);return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.decode(...e)}async _call(e,...t){for(let n of[this.image_processor,this.feature_extractor,this.tokenizer])if(n)return n(e,...t);throw Error(`No image processor, feature extractor, or tokenizer found.`)}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([this.uses_processor_config?mC(e,JT,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async n=>{let r=await this[n].from_pretrained(e,t);return[n.replace(/_class$/,``),r]})).then(Object.fromEntries),this.uses_chat_template_file?pC(e,YT,!0,t):null]);return new this(n,r,i)}};fb({},{ChatterboxProcessor:()=>WE,CohereAsrProcessor:()=>KE,Florence2Processor:()=>Bfe,Gemma3Processor:()=>Vfe,Gemma3nProcessor:()=>Hfe,Gemma4Processor:()=>Ufe,Glm46VProcessor:()=>Wfe,GraniteSpeechProcessor:()=>Gfe,GroundingDinoProcessor:()=>qfe,Idefics3Processor:()=>VD,JinaCLIPProcessor:()=>Qfe,Lfm2VlProcessor:()=>$fe,LlavaProcessor:()=>epe,MgpstrProcessor:()=>tpe,MoonshineProcessor:()=>npe,OwlViTProcessor:()=>rpe,PaliGemmaProcessor:()=>ape,Phi3VProcessor:()=>spe,PixtralProcessor:()=>cpe,Processor:()=>XT,PyAnnoteProcessor:()=>lpe,Qwen2VLProcessor:()=>BD,Qwen2_5_VLProcessor:()=>GD,Qwen3VLProcessor:()=>upe,Sam2Processor:()=>qD,Sam2VideoProcessor:()=>dpe,SamProcessor:()=>KD,SmolVLMProcessor:()=>VD,SpeechT5Processor:()=>fpe,UltravoxProcessor:()=>ppe,VLChatProcessor:()=>Zfe,VoxtralProcessor:()=>_pe,VoxtralRealtimeProcessor:()=>bpe,Wav2Vec2Processor:()=>xpe,Wav2Vec2ProcessorWithLM:()=>Spe,WhisperProcessor:()=>Cpe});var ZT=class extends Nb{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await mC(e,KT,!0,t);return new this(n)}};function QT(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var $T={};fb($T,{ASTFeatureExtractor:()=>CE,ChatterboxFeatureExtractor:()=>TE,ClapFeatureExtractor:()=>EE,CohereAsrFeatureExtractor:()=>kE,DacFeatureExtractor:()=>AE,EncodecFeatureExtractor:()=>wE,FeatureExtractor:()=>ZT,Gemma3nAudioFeatureExtractor:()=>jE,Gemma4AudioFeatureExtractor:()=>ME,GraniteSpeechFeatureExtractor:()=>NE,MoonshineFeatureExtractor:()=>PE,ParakeetFeatureExtractor:()=>OE,PyAnnoteFeatureExtractor:()=>FE,SeamlessM4TFeatureExtractor:()=>IE,SnacFeatureExtractor:()=>LE,SpeechT5FeatureExtractor:()=>RE,VoxtralRealtimeFeatureExtractor:()=>VE,Wav2Vec2FeatureExtractor:()=>zE,WeSpeakerFeatureExtractor:()=>BE,WhisperFeatureExtractor:()=>HE});var eE={fromWeb:()=>{}};async function tE(e,t){if(wb.IS_BROWSER_ENV){if(wb.IS_WEBWORKER_ENV)throw Error(`Unable to save a file from a Web Worker.`);let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(n)}else if(wb.IS_FS_AVAILABLE){let n=t.stream();eE.fromWeb(n),pb.createWriteStream(e),await void 0}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function nE(e,t){if(typeof AudioContext>`u`)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let n=await(await sC(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&Wb.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let i=await r.decodeAudioData(n),a;if(i.numberOfChannels===2){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);a=new Float32Array(t.length);for(let r=0;r2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function cE(e,t=`htk`){let n=sE[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}var lE={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function uE(e,t=`htk`){let n=lE[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}function dE(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),r=Array.from({length:e.length},()=>Array(t.length));for(let n=0;nArray(e.length));for(let t=0;te+r*n)}function pE(e,t,n,r,i,a=null,o=`htk`,s=!1){if(a!==null&&a!==`slaney`)throw Error(`norm must be one of null or "slaney"`);if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(n>r)throw Error(`Require min_frequency: ${n} <= max_frequency: ${r}`);let c=fE(cE(n,o),cE(r,o),t+2),l=uE(c,o),u;if(s){let t=i/((e-1)*2);u=cE(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=fE(0,Math.floor(i/2),e);let d=dE(u,l);if(a!==null&&a===`slaney`)for(let n=0;ni)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(T!==n)throw Error(`Length of the window (${T}) must equal frame_length (${n})`);if(r<=0)throw Error(`hop_length must be greater than zero`);if(a===null&&d!==null)throw Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){let t=Math.floor(n/2);switch(s){case`reflect`:e=mE(e,t,t);break;case`constant`:{let n=new e.constructor(e.length+2*t);n.set(e,t),e=n;break}case`semicausal`:{let n=new e.constructor(e.length+t);n.set(e,t),e=n;break}default:throw Error(`pad_mode="${s}" not implemented yet.`)}}let E=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&EE?x&&(k=b):k=O=b);let A=new xC(i),j=new Float64Array(i),M=new Float64Array(A.outputBufferSize),ee=new Float32Array(D*k);for(let i=0;i=1;--e)j[e]-=l*j[e-1];j[0]*=1-l}for(let e=0;ee**.85);break;default:throw Error(`Unknown window type ${t}.`)}if(n&&(o=o.subarray(0,e)),r===null||e===r)return o;if(e>r)throw Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);let s=new Float64Array(r),c=i?Math.floor((r-e)/2):0;return s.set(o,c),s}function bE(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=new ArrayBuffer(44),i=new DataView(r);return xE(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),xE(i,8,`WAVE`),xE(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),xE(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer)],{type:`audio/wav`})}function xE(e,t,n){for(let r=0;re+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),bE(e,this.sampling_rate)}async save(e){return tE(e,this.toBlob())}},CE=class extends ZT{constructor(e){super(e);let t=this.config.sampling_rate,n=pE(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=yE(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return vE(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){QT(e,`ASTFeatureExtractor`);let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=this.std*2,n=t.data;for(let t=0;t0){if(n===`rand_trunc`){let n=Math.floor(qS.random()*(a+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${n}" not implemented`)}else{if(a<0){let n=new Float64Array(t);if(n.set(e),r===`repeat`)for(let r=e.length;r=1;--n)e[n]-=t*e[n-1];return await vE(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:`log`,mel_floor:-1/0,pad_mode:`constant`,center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){QT(e,`ParakeetFeatureExtractor`);let t=await this._extract_fbank_features(e),n=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,n*t.dims[1]);let[i,a]=t.dims,o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e1?n-1:1;for(let e=0;e=l){s.push(e.slice(c,l));break}let t=Math.max(c,c+a-o),n=Math.min(c+a,l),i;i=n<=t?c+a:this._find_split_point_energy(e,t,n,r),i=Math.max(c+1,Math.min(i,l)),s.push(e.slice(c,i)),c=i}return s}_find_split_point_energy(e,t,n,r){let i=n-t;if(i<=r)return Math.floor((t+n)/2);let a=1/0,o=t,s=i-r;for(let n=0;n<=s;n+=r){let i=0;for(let a=0;at&&(e=e.slice(0,t)),r&&e.length%i!==0){let t=i-e.length%i,n=new Float64Array(e.length+t);n.set(e),this.config.padding_value!==0&&n.fill(this.config.padding_value,e.length),e=n}let a=await this._extract_fbank_features(e,this.config.max_length),o=Dw([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},ME=class extends jE{async _extract_fbank_features(e,t){let{frame_length:n,hop_length:r,fft_length:i}=this.config,a=Math.floor(n/2),o=Math.floor((e.length+a-(n+1))/r)+1;return vE(e,this.window,n,r,{fft_length:i,center:!0,pad_mode:`semicausal`,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,mel_floor_mode:`add`,remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){QT(e,`Gemma4AudioFeatureExtractor`);let n=e.length,r=await super._call(e,t),{input_features:i}=r,[,a,o]=i.dims,{frame_length:s,hop_length:c}=this.config,l=Math.floor(s/2),u=s+1,d=new Uint8Array(n+l+(t.pad_to_multiple_of??128));d.fill(1,l,l+n);let f=new Uint8Array(a);for(let e=0;e({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},IE=class extends ZT{constructor(e){super(e);let t=this.config.sampling_rate,n=pE(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=yE(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),vE(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){QT(e,`SeamlessM4TFeatureExtractor`);let a=await this._extract_fbank_features(e,this.config.max_length);if(r){let[e,t]=a.dims,n=a.data;for(let r=0;r0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new L(a.type,n,[c,t]),i&&(o=new L(`int64`,new BigInt64Array(c),[1,c]),o.data.fill(1n,0,e))}}let[s,c]=a.dims,l=this.config.stride;if(s%l!==0)throw Error(`The number of frames (${s}) must be a multiple of the stride (${l}).`);let u=a.view(1,Math.floor(s/l),c*l),d={input_features:u};if(i){let e=u.dims[1],t=new BigInt64Array(e);if(o){let e=o.data;for(let n=1,r=0;ne+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(n+1e-7))}async _call(e){QT(e,`Wav2Vec2FeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let n=[1,t.length];return{input_values:new L(`float32`,t,n),attention_mask:new L(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},BE=class extends ZT{constructor(e){super(e);let t=this.config.sampling_rate,n=pE(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=yE(400,`hamming`,{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(e=>e*32768),vE(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){QT(e,`WeSpeakerFeatureExtractor`);let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;tr?(e.length>this.config.n_samples&&Wb.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),n=e.slice(0,r)):(n=new Float32Array(r),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}},UE=class{static async from_pretrained(e,t={}){let n=await mC(e,KT,!0,t),r=n.feature_extractor_type,i=$T[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${GT}.`);return new i(n)}},WE=class extends XT{static tokenizer_class=WT;static feature_extractor_class=UE;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},GE=new Set([`ja`,`zh`]),KE=class extends XT{static tokenizer_class=WT;static feature_extractor_class=UE;static uses_processor_config=!0;get_decoder_prompt_ids(e=`en`){let t=[`▁`,`<|startofcontext|>`,`<|startoftranscript|>`,`<|emo:undefined|>`,`<|${e}|>`,`<|${e}|>`,`<|pnc|>`,`<|noitn|>`,`<|notimestamp|>`,`<|nodiarize|>`];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t=`en`){let n=e.filter(e=>e&&e.trim());if(n.length===0)return``;let r=GE.has(t)?``:` `;return[n[0].trimEnd(),...n.slice(1).map(e=>e.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},qE={},JE,YE,XE;if(wb.IS_WEB_ENV)JE=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},XE=self.createImageBitmap,YE=self.ImageData;else if(qE)XE=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new $E(new Uint8ClampedArray(n),r.width,r.height,r.channels);return t!==void 0&&t!==r.channels&&i.convert(t),i};else throw Error(`Unable to load image processing library.`);var ZE={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},QE=new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),$E=class e{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)return t;if(typeof t==`string`||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!wb.IS_WEB_ENV)throw Error(`fromCanvas() is only supported in browser environments.`);let n=t.getContext(`2d`).getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(e){let t=await sC(e);if(t.status!==200)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(wb.IS_WEB_ENV){let t=await XE(e),n=JE(t.width,t.height).getContext(`2d`);return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=qE(await e.arrayBuffer());return await XE(t)}}static fromTensor(t,n=`CHW`){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(n===`CHW`)t=t.transpose(1,2,0);else if(n!==`HWC`)throw Error(`Unsupported channel format: ${n}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t=0?c=r:u=-r,i>=0?l=i:d=-i,s.drawImage(o,c,l,t,n,u,d,t,n),new e(s.getImageData(0,0,t,n).data,t,n,4).convert(a)}{let e=this.toSharp();if(r>=0&&i>=0)e=e.extract({left:Math.floor(r),top:Math.floor(i),width:t,height:n});else if(r<=0&&i<=0){let a=Math.floor(-i),o=Math.floor(-r);e=e.extend({top:a,left:o,right:t-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;i<0?(a[0]=Math.floor(-i),a[1]=n-this.height-a[0]):o=Math.floor(i);let s=[0,0],c=0;r<0?(s[0]=Math.floor(-r),s[1]=t-this.width-s[0]):c=Math.floor(r),e=e.extend({top:a[0],bottom:a[1],left:s[0],right:s[1]}).extract({left:c,top:o,width:t,height:n})}return await XE(e)}}async toBlob(e=`image/png`,t=1){if(!wb.IS_WEB_ENV)throw Error(`toBlob() is only supported in browser environments.`);return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e=`CHW`){let t=new L(`uint8`,new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!==`HWC`){if(e===`CHW`)t=t.permute(2,0,1);else throw Error(`Unsupported channel format: ${e}`)}return t}toCanvas(){if(!wb.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=JE(e.width,e.height),n=new YE(e.data,e.width,e.height);return t.getContext(`2d`).putImageData(n,0,0),t}split(){let{data:t,width:n,height:r,channels:i}=this,a=t.constructor,o=t.length/i,s=Array.from({length:i},()=>new a(o));for(let e=0;enew e(t,n,r,1))}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,r!==null&&(this.channels=r),this}clone(){return new e(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(wb.IS_WEB_ENV){if(wb.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=QE.get(t)??`image/png`;return tE(e,await this.toBlob(n))}if(wb.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw Error(`Unable to save the image because filesystem is disabled in this environment.`)}toSharp(){if(wb.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return qE(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};$E.read.bind($E);function eD(e,t,n=0,r=null){let i=e/t,a=wC(i)*t;return r!==null&&a>r&&(a=Math.floor(i)*t),at&&i.push(e)}else{let e=_C(n.data)[1];if(e===c-1||(a=hC(n.data),a[e]e*o[(t+1)%2])),u.boxes.push(n),u.classes.push(t),u.scores.push(a[t])}}l.push(u)}return l}function iD(e,t=null){let n=e.logits,r=n.dims[0];if(t!==null&&t.length!==r)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let i=[];for(let e=0;el[n]&&(l[n]=t[n],u[n]=e)}let d=Array(a.dims[0]);for(let e=0;ee!==void 0);i.push({segmentation:c,labels:f})}return i}function aD(e,t,n,r){let i=[],a=[],o=[];for(let s=0;sn&&(i.push(l),a.push(d),o.push(u))}return[i,a,o]}function oD(e,t,n,r=.5,i=.8){let a=[],o=0,s=0,c=t[n].data;for(let t=0;t=r&&++s;let l=o>0&&s>0;return l&&=o/s>i,[l,a]}function sD(e,t,n,r,i,a=null,o=null){let[s,c]=o??e[0].dims,l=new L(`int32`,new Int32Array(s*c),[s,c]),u=[];if(o!==null)for(let t=0;tf[e]&&(d[e]=n,f[e]=i[e])}let p=0,m=l.data;for(let a=0;a200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/n)*n,s=Math.round(t/n)*n;if(a*o*s>i){let r=Math.sqrt(a*e*t/i);o=Math.max(n,Math.floor(e/r/n)*n),s=Math.max(n,Math.floor(t/r/n)*n)}else if(a*o*si?c=Math.floor(i*s/r):i>r&&(s=Math.floor(r*c/i)),await e.resize(c,s,{resample:n}))}async crop_margin(e,t=200){let n=e.clone().grayscale(),r=gC(n.data)[0],i=_C(n.data)[0]-r;if(i===0)return e;let a=t/255,o=n.width,s=n.height,c=0,l=0,u=n.data;for(let e=0;ethis.preprocess(e)));return{pixel_values:xw(n.map(e=>e.pixel_values),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}static async from_pretrained(e,t={}){let n=await mC(e,qT,!0,t);return new this(n)}},fD={};fb(fD,{BeitFeatureExtractor:()=>Gde,BitImageProcessor:()=>Kde,CHMv2ImageProcessor:()=>Jde,CLIPFeatureExtractor:()=>Yde,CLIPImageProcessor:()=>pD,ChineseCLIPFeatureExtractor:()=>qde,ConvNextFeatureExtractor:()=>Xde,ConvNextImageProcessor:()=>mD,DINOv3ViTImageProcessor:()=>$de,DPTFeatureExtractor:()=>tfe,DPTImageProcessor:()=>vD,DeiTFeatureExtractor:()=>Zde,DeiTImageProcessor:()=>hD,DetrFeatureExtractor:()=>Qde,DetrImageProcessor:()=>gD,DonutFeatureExtractor:()=>efe,DonutImageProcessor:()=>_D,EfficientNetImageProcessor:()=>nfe,GLPNFeatureExtractor:()=>sfe,Gemma3ImageProcessor:()=>rfe,Gemma4ImageProcessor:()=>yD,Glm46VImageProcessor:()=>ofe,GroundingDinoImageProcessor:()=>cfe,Idefics3ImageProcessor:()=>xD,ImageFeatureExtractor:()=>dD,ImageProcessor:()=>dD,JinaCLIPImageProcessor:()=>ufe,Lfm2VlImageProcessor:()=>hfe,LlavaOnevisionImageProcessor:()=>gfe,Mask2FormerImageProcessor:()=>vfe,MaskFormerFeatureExtractor:()=>_fe,MaskFormerImageProcessor:()=>CD,MobileNetV1FeatureExtractor:()=>yfe,MobileNetV1ImageProcessor:()=>wD,MobileNetV2FeatureExtractor:()=>bfe,MobileNetV2ImageProcessor:()=>TD,MobileNetV3FeatureExtractor:()=>xfe,MobileNetV3ImageProcessor:()=>ED,MobileNetV4FeatureExtractor:()=>Sfe,MobileNetV4ImageProcessor:()=>DD,MobileViTFeatureExtractor:()=>Cfe,MobileViTImageProcessor:()=>OD,NougatImageProcessor:()=>wfe,OwlViTFeatureExtractor:()=>Tfe,OwlViTImageProcessor:()=>kD,Owlv2ImageProcessor:()=>Efe,Phi3VImageProcessor:()=>Ofe,PixtralImageProcessor:()=>kfe,PvtImageProcessor:()=>Afe,Qwen2VLImageProcessor:()=>bD,RTDetrImageProcessor:()=>jfe,Sam2ImageProcessor:()=>PD,Sam3ImageProcessor:()=>PD,SamImageProcessor:()=>PD,SapiensFeatureExtractor:()=>Mfe,SapiensImageProcessor:()=>FD,SegformerFeatureExtractor:()=>Nfe,SegformerImageProcessor:()=>ID,SiglipImageProcessor:()=>Pfe,SmolVLMImageProcessor:()=>xD,Swin2SRImageProcessor:()=>Ffe,VLMImageProcessor:()=>lfe,ViTFeatureExtractor:()=>Ife,ViTImageProcessor:()=>LD,VitMatteImageProcessor:()=>Lfe,VitPoseImageProcessor:()=>Rfe,YolosFeatureExtractor:()=>zfe,YolosImageProcessor:()=>RD});var Gde=class extends dD{},Kde=class extends dD{},qde=class extends dD{},Jde=class extends dD{},pD=class extends dD{},Yde=class extends pD{},mD=class extends dD{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw Error(`Size dictionary must contain 'shortest_edge' key.`);if(t<384){let n=Math.floor(t/this.crop_pct),[r,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,i,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},Xde=class extends mD{},hD=class extends dD{},Zde=class extends hD{},gD=class extends dD{async _call(e){let t=await super._call(e),n=Dw([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return rD(...e)}post_process_panoptic_segmentation(...e){return lD(...e)}post_process_instance_segmentation(...e){return uD(...e)}},Qde=class extends gD{},$de=class extends dD{},_D=class extends dD{pad_image(e,t,n,r={}){let[i,a,o]=t,s=this.image_mean;Array.isArray(this.image_mean)||(s=Array(o).fill(s));let c=this.image_std;Array.isArray(c)||(c=Array(o).fill(s));let l=s.map((e,t)=>-e/c[t]);return super.pad_image(e,t,n,{center:!0,constant_values:l,...r})}},efe=class extends _D{},vD=class extends dD{},tfe=class extends vD{},nfe=class extends dD{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(e=>e*e))}},rfe=class extends dD{};function ife(e,t,n,r,i){let a=r*n**2,o=Math.sqrt(a/(e*t)),s=i*n,c=Math.floor(o*e/s)*s,l=Math.floor(o*t/s)*s;if(c===0&&l===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${s}.`);let u=Math.floor(r/i**2)*s;return c===0?(c=s,l=Math.min(Math.floor(t/e)*s,u)):l===0&&(l=s,c=Math.min(Math.floor(e/t)*s,u)),[c,l]}function afe(e,t,n,r,i,a,o){let s=Math.floor(t/i),c=Math.floor(n/i),l=s*c,u=i*i*r,d=new Float32Array(a*u),f=0;for(let t=0;ta),0));let l=a.dims[0]/o,u=a.dims[1],d=Math.floor(a.dims[2]/c),f=Math.floor(a.dims[3]/c);return{pixel_values:a.view(l,o,u,Math.floor(d/s),s,c,Math.floor(f/s),s,c).permute(0,3,6,4,7,2,1,5,8).view(l*d*f,u*o*c*c),image_grid_thw:new L(`int64`,[l,d,f],[1,3]),original_sizes:r,reshaped_input_sizes:i}}},ofe=class extends bD{get_resize_output_image_size(e,t){let n=this.patch_size*this.merge_size,r=this.config.temporal_patch_size??2;return cD(e.height,e.width,n,this.min_pixels,this.max_pixels,r)}},sfe=class extends dD{},cfe=class extends dD{async _call(e){let t=await super._call(e),n=t.pixel_values.dims,r=kw([n[0],n[2],n[3]]);return{...t,pixel_mask:r}}},xD=class extends dD{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[n,r]=e.dims.slice(-2),i=r/n;return r>=n?(r=Math.ceil(r/t)*t,n=Math.floor(r/i),n=Math.ceil(n/t)*t):(n=Math.ceil(n/t)*t,r=Math.floor(n*i),r=Math.ceil(r/t)*t),{height:n,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:n=!1}={}){let r;if(!Array.isArray(e))r=[[e]];else{if(e.length===0||!e[0])throw Error(`No images provided.`);r=Array.isArray(e[0])?e:[e]}let i=[],a=[],o=[],s=[],c=[];for(let e of r){let n=await Promise.all(e.map(e=>this.preprocess(e)));s.push(...n.map(e=>e.original_size)),c.push(...n.map(e=>e.reshaped_input_size)),n.forEach(e=>e.pixel_values.unsqueeze_(0));let{longest_edge:r}=this.max_image_size,l;if(t??this.do_image_splitting){let e=Array(n.length),t=Array(n.length);l=await Promise.all(n.map(async(n,i)=>{let a=this.get_resize_for_vision_encoder(n.pixel_values,r),o=await dw(n.pixel_values,{size:[a.height,a.width]}),{frames:s,num_splits_h:c,num_splits_w:l}=await this.split_image(o,this.max_image_size);return e[i]=c,t[i]=l,bw(s,0)})),a.push(e),o.push(t)}else{let e=[r,r];l=await Promise.all(n.map(t=>dw(t.pixel_values,{size:e}))),a.push(Array(n.length).fill(0)),o.push(Array(n.length).fill(0))}i.push(bw(l,0))}let l=i.length,[u,d,f,p]=i[0].dims,m,h;if(l===1)m=i[0].unsqueeze_(0),h=Dw([l,u,f,p],!0);else{let e=Math.max(...i.map(e=>e.dims.at(0)));h=Dw([l,e,f,p],!0);let t=h.data,n=e*f*p;for(let r=0;rn||o>r){s=Math.ceil(a/n),c=Math.ceil(o/r);let t=Math.ceil(a/s),l=Math.ceil(o/c);for(let n=0;ne*this.rescale_factor)}pad_image(e,t,n,r){return super.pad_image(e,t,n,{constant_values:this.constant_values,center:!0,...r})}},ufe=class extends dD{constructor(e){let{resize_mode:t,fill_color:n,interpolation:r,size:i,...a}=e,o=t===`squash`?{width:i,height:i}:t===`shortest`?{shortest_edge:i}:{longest_edge:i},s=r===`bicubic`?3:2;super({...a,size:o,resample:s,do_center_crop:!0,crop_size:i,do_normalize:!0})}};function SD(e,t){return Math.round(e/t)*t}function dfe(e,t,n,r,i){let a=1/0,o=[1,1],s=n*r;for(let n of t){let t=Math.abs(e-n[0]/n[1]);t.5*i*i*n[0]*n[1]&&(o=n)}return o}function ffe(e,t){let n=[],r=new Set;for(let i=e;i<=t;++i)for(let a=1;a<=i;++a)for(let o=1;o<=i;++o){let i=a*o;if(i>=e&&i<=t){let e=a<<16|o;r.has(e)||(r.add(e),n.push([a,o]))}}return n.sort((e,t)=>e[0]*e[1]-t[0]*t[1])}function pfe(e,t){let[n,r,i,a]=e.dims,o=Math.floor(i/t),s=Math.floor(a/t),c=t*t*r,l=e.data,u=new Float32Array(n*o*s*c),d=i*a;for(let e=0;ethis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let n=ffe(this.min_tiles,this.max_tiles),[r,i]=dfe(t/e,n,t,e,this.tile_size);return{grid_width:r,grid_height:i,target_width:this.tile_size*r,target_height:this.tile_size*i}}async _call(e,{return_row_col_info:t=null}={}){let n;n=Array.isArray(e)?Array.isArray(e[0])?e:[e]:[[e]];let r=[],i=[],a=[],o=[],s=[],c=[];for(let e of n){let t=await Promise.all(e.map(e=>this.preprocess(e,{do_pad:!1})));for(let{pixel_values:e}of t){let[,t,n]=e.dims,l=e.unsqueeze_(0),u=this.encoder_patch_size*this.downsample_factor,d=u**2,[f,p]=cD(Math.max(u,t),Math.max(u,n),u,this.min_image_tokens*d,this.max_image_tokens*d).map(e=>Math.max(u,e)),m,h=1,g=1,_=this._is_image_too_large(t,n),v=this.do_image_splitting&&(this.min_tiles!==1||this.max_tiles!==1);if(_&&v){let{grid_width:e,grid_height:r,target_width:i,target_height:a}=this._get_grid_layout(t,n);h=r,g=e;let o=await dw(l,{size:[a,i]});m=[];for(let t=0;t(e-this.image_mean[t])/this.image_std[t]);return super.pad_image(e,t,{width:s,height:o},{center:!0,constant_values:c,...r})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||ND(t)%1!=0)throw Error(`num_crops must be a square number >= 4`);Array.isArray(e)||(e=[e]);let n=e.length,r=await Promise.all(e.map(e=>this.preprocess(e))),i=r.map(e=>e.original_size),a=r.map(e=>e.reshaped_input_size),o=[];for(let{pixel_values:e}of r){e.unsqueeze_(0);let[n,r]=e.dims.slice(-2),i=await dw(e,{size:[AD,AD],mode:`bicubic`});if(t>0){let a=[],s=ND(t),c=MD(r/s),l=MD(n/s);for(let t=0;te.map(e=>AD*jD(e/AD)));return{pixel_values:s,original_sizes:i,reshaped_input_sizes:a,image_sizes:new L(`int64`,c.flat(),[n,2]),num_img_tokens:c.map(([e,t])=>this.calc_num_image_tokens_from_image_size(t,e))}}},kfe=class extends dD{get_resize_output_image_size(e,t){let{longest_edge:n}=t;if(n===void 0)throw Error(`size must contain 'longest_edge'`);let[r,i]=e.size,a=Math.max(r,i)/n,o=r,s=i;a>1&&(o=Math.floor(r/a),s=Math.floor(i/a));let{patch_size:c,spatial_merge_size:l}=this.config;if(!l)throw Error(`config must contain 'spatial_merge_size'`);let u=c*l,d=Math.floor((o-1)/u)+1,f=Math.floor((s-1)/u)+1;return[d*u,f*u]}},Afe=class extends dD{},jfe=class extends dD{post_process_object_detection(...e){return rD(...e)}},PD=class extends dD{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let i=Rb(e);if(i.length===3)r||(i=[1,...i]),e=[e];else if(i.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let r=0;re!==t.dims[n]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new L(`int64`,e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:t=null,input_labels:n=null,input_boxes:r=null}={}){let i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(n,i.input_points)}return r&&(i.input_boxes=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:i=!0,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let s=[a.height,a.width];for(let a=0;ar&&(t[n]=1);u=new L(`bool`,t,u.dims)}o.push(u)}return o}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}},FD=class extends dD{post_process_semantic_segmentation(...e){return iD(...e)}},Mfe=class extends FD{},ID=class extends dD{post_process_semantic_segmentation(...e){return iD(...e)}},Nfe=class extends ID{},Pfe=class extends dD{},Ffe=class extends dD{pad_image(e,t,n,r={}){let[i,a,o]=t;return super.pad_image(e,t,{width:a+(n-a%n)%n,height:i+(n-i%n)%n},{mode:`symmetric`,center:!1,constant_values:-1,...r})}},LD=class extends dD{},Ife=class extends LD{},Lfe=class extends dD{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let n=await Promise.all(e.map(e=>this.preprocess(e))),r=await Promise.all(t.map(e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:xw(n.map((e,t)=>bw([e.pixel_values,r[t].pixel_values],0)),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}},Rfe=class extends dD{post_process_pose_estimation(e,t,{threshold:n=null}={}){let r=e.tolist(),[i,a,o,s]=e.dims,c=[];for(let e=0;e/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e==`string`&&(e=[e]);let t=[];for(let n of e)if(this.task_prompts_without_inputs.has(n))t.push(this.task_prompts_without_inputs.get(n));else{for(let[e,r]of this.task_prompts_with_input)if(n.includes(e)){t.push(r.replaceAll(`{input}`,n).replaceAll(e,``));break}t.length!==e.length&&t.push(n)}return t}post_process_generation(e,t,n){let r=this.tasks_answer_post_processing_type.get(t)??`pure_text`;e=e.replaceAll(``,``).replaceAll(``,``);let i;switch(r){case`pure_text`:i=e;break;case`description_with_bboxes`:case`bboxes`:case`phrase_grounding`:case`ocr`:let a=r===`ocr`?`quad_boxes`:`bboxes`,o=e.matchAll(this.regexes[a]),s=[],c=[];for(let[e,t,...r]of o)s.push(t?t.trim():s.at(-1)??``),c.push(r.map((e,t)=>(Number(e)+.5)/this.size_per_bin*n[t%2]));i={labels:s,[a]:c};break;default:throw Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:i}}async _call(e,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=await this.image_processor(e,n),i=t?this.tokenizer(this.construct_prompts(t),n):{};return{...r,...i}}},Vfe=class extends XT{static tokenizer_class=WT;static image_processor_class=zD;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.image_seq_length=this.config.image_seq_length;let{boi_token:r,image_token:i,eoi_token:a}=this.tokenizer.config;this.boi_token=r,this.image_token=i,this.eoi_token=a;let o=i.repeat(this.image_seq_length);this.full_image_sequence=` + +${r}${o}${a} + +`}async _call(e,t=null,n={}){typeof e==`string`&&(e=[e]);let r;return t&&(r=await this.image_processor(t,n),e=e.map(e=>e.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,n),...r}}},Hfe=class extends XT{static image_processor_class=zD;static feature_extractor_class=UE;static tokenizer_class=WT;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:r,boa_token:i,audio_token:a,eoa_token:o,image_token_id:s,boi_token:c,image_token:l,eoi_token:u}=this.tokenizer.config;this.audio_token_id=r,this.boa_token=i,this.audio_token=a;let d=a.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${i}${d}${o} + +`,this.image_token_id=s,this.boi_token=c,this.image_token=l;let f=l.repeat(this.image_seq_length);this.full_image_sequence=` + +${c}${f}${u} + +`}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;n&&(i=await this.feature_extractor(n,r),e=e.map(e=>e.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,r),e=e.map(e=>e.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,r),...a,...i}}},Ufe=class extends XT{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:r,boa_token:i,eoa_token:a,image_token:o,boi_token:s,eoi_token:c}=this.tokenizer.config;this.audio_token=r,this.boa_token=i,this.eoa_token=a,this.image_token=o,this.boi_token=s,this.eoi_token=c}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([mC(e,JT,!0,t),WT.from_pretrained(e,t),pC(e,YT,!1,t)]),a={tokenizer:r};return n.image_processor&&(a.image_processor=new yD(n.image_processor)),n.feature_extractor&&(a.feature_extractor=new ME(n.feature_extractor)),new this(n,a,i)}_compute_audio_num_tokens(e,t){let n=Math.round(t*20/1e3),r=Math.round(t*10/1e3),i=Math.floor(n/2),a=Math.floor((e+i-n-1)/r)+1;if(a<=0)return 0;for(let e=0;e<2;++e)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;if(t){i=await this.image_processor(t,r);let n=i.num_soft_tokens_per_image,a=0;e=e.map(e=>e.replaceAll(this.image_token,()=>` + +${this.boi_token}${this.image_token.repeat(n[a++])}${this.eoi_token} + +`))}let a;if(n){let t=Array.isArray(n)?n:[n];a=await this.feature_extractor(t[0],r);let i=this.feature_extractor.config.sampling_rate??16e3,o=0;e=e.map(e=>e.replaceAll(this.audio_token,()=>` + +${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(t[o++].length,i))}${this.eoa_token} + +`))}return{...this.tokenizer(e,r),...i,...a}}},BD=class extends XT{static image_processor_class=zD;static tokenizer_class=WT;static image_token=`<|image_pad|>`;async _call(e,t=null,...n){Array.isArray(e)||(e=[e]);let r,i;if(t&&(r=await this.image_processor(t),i=r.image_grid_thw),i){let t=this.image_processor.config.merge_size**2,n=0,r=this.constructor.image_token,a=i.tolist();e=e.map(e=>{for(;e.includes(r);){let i=Number(a[n++].reduce((e,t)=>e*t,1n));e=e.replace(r,`<|placeholder|>`.repeat(Math.floor(i/t)))}return e.replaceAll(`<|placeholder|>`,r)})}return{...this.tokenizer(e),...r}}},Wfe=class extends BD{static image_token=`<|image|>`},Gfe=class extends XT{static tokenizer_class=WT;static feature_extractor_class=UE;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:n,projector_downsample_rate:r}=this.feature_extractor.config,i=Math.floor(n/r),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/n)*i}async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let{input_features:n}=await this.feature_extractor(t);r.input_features=n;let i=this._get_num_audio_features(t.length);r.input_features_mask=new L(`bool`,new Uint8Array(i).fill(1),[1,i]);let a=this.config.audio_token??`<|audio|>`;if(!e.includes(a))throw Error(`The input text does not contain the audio token ${a}.`);e=e.replaceAll(a,a.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}};function Kfe(e,t){let n=e.dims.at(-1)-1,r=e.tolist();r.fill(!1,0,1),r.fill(!1,n);let i=t.tolist();return r.map((e,t)=>e?t:null).filter(e=>e!==null).map(e=>i[e])}var qfe=class extends XT{static tokenizer_class=WT;static image_processor_class=zD;async _call(e,t,n={}){let r=e?await this.image_processor(e,n):{};return{...t?this.tokenizer(t,n):{},...r}}post_process_grounded_object_detection(e,t,{box_threshold:n=.25,text_threshold:r=.25,target_sizes:i=null}={}){let{logits:a,pred_boxes:o}=e,s=a.dims[0];if(i!==null&&i.length!==s)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let c=a.dims.at(1),l=a.sigmoid(),u=l.max(-1).tolist(),d=o.tolist().map(e=>e.map(e=>nD(e))),f=[];for(let e=0;ee.map((e,t)=>e*a[(t+1)%2])));let o=u[e],s=[],p=[],m=[];for(let i=0;i`+i.repeat(e);o+=` +`}return o+=` +${r}${a}`+i.repeat(e)+`${r}`,o}function Yfe(e,t,n,r){return`${t}${r}`+n.repeat(e)+`${t}`}function Xfe(e,t,n,r,i,a){return e===0&&t===0?Yfe(n,r,i,a):Jfe(n,e,t,r,i,a)}var VD=class extends XT{static image_processor_class=zD;static tokenizer_class=WT;static uses_processor_config=!0;fake_image_token=``;image_token=``;global_img_token=``;async _call(e,t=null,n={}){n.return_row_col_info??=!0;let r;t&&(r=await this.image_processor(t,n)),Array.isArray(e)||(e=[e]);let i=r.rows??[Array(e.length).fill(0)],a=r.cols??[Array(e.length).fill(0)],o=this.config.image_seq_len,s=[],c=[];for(let t=0;tXfe(e,l[t],o,this.fake_image_token,this.image_token,this.global_img_token)),d=n.split(this.image_token);if(d.length===0)throw Error(`The image token should be present in the text.`);let f=d[0];for(let e=0;ee.images).flatMap(e=>e.images).map(e=>$E.read(e)));let r=this.tokenizer,i=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:n}),a=e=>r.encode(e,{add_special_tokens:!1}),o=i.split(this.image_tag),s=o.length-1;if(t.length!==s)throw Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${s})`);let[c,l,u]=r.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),d=a(o[0]),f=Array(d.length).fill(!1);for(let e=1;e0){let e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...m,...e}}return m}},Qfe=class extends XT{static tokenizer_class=WT;static image_processor_class=zD;async _call(e=null,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=e?this.tokenizer(e,n):{},i=t?await this.image_processor(t,n):{};return{...r,...i}}},$fe=class extends XT{static tokenizer_class=WT;static image_processor_class=zD;async _call(e,t=null,n={}){let{image_rows:r,image_cols:i,image_sizes:a,...o}=await this.image_processor(e,{...n,return_row_col_info:!0});if(t){let e=this.config.image_token??``,{tile_size:n=512,downsample_factor:o=2,encoder_patch_size:s=16,use_thumbnail:c=!0}=this.image_processor.config,l=e=>Math.ceil(Math.floor(e/s)/o),u=l(n)**2,d=this.config.image_start_token??`<|image_start|>`,f=this.config.image_end_token??`<|image_end|>`,p=this.config.image_thumbnail??`<|img_thumbnail|>`;Array.isArray(t)||(t=[t]);let m=0;t=t.map(t=>{let n=t.split(e);return n[0]+n.slice(1).map(t=>{let n=m++,[o,s]=a[n],h=r[n],g=i[n],_=l(o)*l(s),v=d;if(h>1||g>1){let t=e.repeat(u);for(let e=0;e`+t;c&&(v+=p+e.repeat(_))}else v+=e.repeat(_);return v+f+t}).join(``)})}return{...o,...t?this.tokenizer(t,n):{}}}},epe=class extends XT{static tokenizer_class=WT;static image_processor_class=zD;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,patch_size:a,num_additional_image_tokens:o}=this.config,s=Math.floor(e/a)*Math.floor(n/a)+o;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e0?i.reduce((e,t)=>e*t,1):0;c.push(n),s.push(a)}return[i(c),s]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}batch_decode([e,t,n]){let[r,i]=this._decode_helper(e,`char`),[a,o]=this._decode_helper(t,`bpe`),[s,c]=this._decode_helper(n,`wp`),l=[],u=[];for(let e=0;e`;function ipe(e,t,n,r,i){return`${r.repeat(n*i)}${t}${e} +`}var ape=class extends XT{static tokenizer_class=WT;static image_processor_class=zD;static uses_processor_config=!1;async _call(e,t=null,n={}){t||=(Wb.warn(`You are using PaliGemma without a text prefix. It will perform as a picture-captioning model.`),``),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=this.tokenizer.bos_token,i=this.image_processor.config.image_seq_length,a;t.some(e=>e.includes(UD))?a=t.map(e=>{let t=e.replaceAll(UD,UD.repeat(i)),n=t.lastIndexOf(UD),a=n===-1?0:n+UD.length;return t.slice(0,a)+r+t.slice(a)+` +`}):(Wb.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(t=>ipe(t,r,i,UD,e.length)));let o=this.tokenizer(a,n);return{...await this.image_processor(e,n),...o}}},WD=`<|image|>`,ope=/<\|image_\d+\|>/g,spe=class extends XT{static image_processor_class=zD;static tokenizer_class=WT;async _call(e,t=null,{padding:n=!0,truncation:r=!0,num_crops:i=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:i});let{num_img_tokens:s}=o,c=e.map((e,t)=>e.split(ope).join(WD.repeat(s[t])));a=this.tokenizer(c,{padding:n,truncation:r});let l=this.tokenizer._tokenizer.token_to_id(WD);a.input_ids.map_(e=>e==l?-e:e)}else a=this.tokenizer(e);return{...a,...o}}},cpe=class extends XT{static tokenizer_class=WT;static image_processor_class=zD;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,image_break_token:a,image_end_token:o,patch_size:s,spatial_merge_size:c}=this.config,l=s*c,u=Math.floor(e/l),d=Math.floor(n/l);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;egpe(e,o)),c=s.map(e=>e.length),l=s.flat(),u=(await Promise.all(l.map(e=>this.feature_extractor(e,n)))).map(e=>e.input_features);r.audio_values=u.length>1?bw(u,0):u[0];let d=i[0];for(let e=0;e0){if(l>YS)throw Error(`The number of external data chunks (${l}) exceeds the maximum allowed value (${YS}).`);let t=rO(o,l);for(let n of t){let t=`${r.subfolder??``}/${n}`;c.push(new Promise(async(i,a)=>{let o=await fC(e,t,!0,r,s);i(o instanceof Uint8Array?{path:n,data:o}:n)}))}}else a.externalData!==void 0&&(c=a.externalData.map(async t=>{if(typeof t.data==`string`){let n=await fC(e,t.data,!0,r);return{...t,data:n}}return t}));return Promise.all(c)}async function Ope(e,t,n,r=!1,i=void 0){let a=n.config?.[`transformers.js_config`]??{},o=ew(n.device??a.device,t,{warn:e=>Wb.info(e)}),s=BC(o),c=a.device_config??{};c.hasOwnProperty(o)&&(a={...a,...c[o]});let l=ow(n.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:e=>Wb.info(e)});if(!aw.hasOwnProperty(l))throw Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(nw).join(`, `)}`);if(o===`webgpu`&&!wb.IS_NODE_ENV&&l===nw.fp16&&!await tw())throw Error(`The device (${o}) does not support fp16.`);let u=aw[l],d={...n.session_options};d.executionProviders??=s;let f=a.free_dimension_overrides;f?d.freeDimensionOverrides??=f:o.startsWith(`webnn`)&&!d.freeDimensionOverrides&&Wb.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let p=Epe(e,t,n,u),m=await Dpe(e,t,u,n,n.use_external_data_format??a.use_external_data_format,d);if(m.length>0&&(!wb.IS_NODE_ENV||m.some(e=>typeof e!=`string`))&&(d.externalData=m),r&&o===`webgpu`){let e=$D(n.config,{prefix:`present`,session_name:i});if(e.size>0&&!YC()){let t={};for(let n of e)t[n]=`gpu-buffer`;d.preferredOutputLocation=t}}return{buffer_or_path:await p,session_options:d,session_config:{dtype:l,device:o}}}async function kpe(e,t,n,r=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async i=>{let a=r?.[i]??!1,{buffer_or_path:o,session_options:s,session_config:c}=await Ope(e,t[i],n,a,i);return[i,await WC(o,s,c)]})))}function iO(e){for(let t in e)qC(e[t])?e[t]=new L(e[t]):typeof e[t]==`object`&&iO(e[t]);return e}async function aO(e,t){let n=Ape(e,t);try{return iO(await KC(e,Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=t.ort_tensor;return wb.IS_NODE_ENV&&typeof Float16Array<`u`&&n.cpuData instanceof Float16Array&&(n.cpuData=new Uint16Array(n.cpuData.buffer)),[e,n]}))))}catch(e){let t=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n={type:t.type,dims:t.dims,location:t.location};return n.location!==`gpu-buffer`&&(n.data=t.data),[e,n]}));throw Wb.error(`An error occurred during model execution: "${e}".`),Wb.error(`Inputs given to model:`,t),e}}function Ape(e,t){let n=Object.create(null),r=[];for(let i of e.inputNames){let e=t[i];if(!(e instanceof L)){r.push(i);continue}n[i]=YC()?e.clone():e}if(r.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(`, `)}.`);let i=Object.keys(t).length,a=e.inputNames.length;if(i>a){let n=Object.keys(t).filter(t=>!e.inputNames.includes(t));Wb.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: "${n.join(`, `)}".`)}return n}var oO=class{},sO=class extends oO{constructor({logits:e,...t}){super(),this.logits=e;let n=Object.values(t);n.length>0&&(this.attentions=n)}},cO=class extends oO{constructor({logits:e}){super(),this.logits=e}},lO=class extends oO{constructor({logits:e}){super(),this.logits=e}},uO=class extends oO{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},dO=class extends oO{constructor({logits:e}){super(),this.logits=e}},jpe=class extends oO{constructor({alphas:e}){super(),this.alphas=e}},fO=class extends Nb{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Mpe=class extends Nb{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},pO=class extends Nb{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(let t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}},Npe=class extends fO{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(a&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&this.max_initial_timestamp_index!==null){let e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}let s=Wde(r);Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>_C(s.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},Lpe=class extends fO{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let n=e.length,r=t.slice([0,n],null),i=t.slice([n,t.dims[0]],null);for(let e=0;ee.length>=this.max_length)}},Gpe=class extends gO{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(e=>{let t=e.at(-1);return this.eos_token_id.some(e=>t==e)})}},Kpe=class extends gO{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return Array(e.length).fill(this.interrupted)}},vO=class extends Nb{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error(`sample should be implemented in subclasses.`)}getLogits(e,t){let n=e.dims.at(-1),r=e.data;if(t===-1)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return r}randomSelect(e){return kde(e)}static getSampler(e){if(e.do_sample)return new Jpe(e);if(e.num_beams>1)return new Ype(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new qpe(e)}},qpe=class extends vO{async sample(e){let t=_C(e.data)[1];return[[BigInt(t),0]]}},Jpe=class extends vO{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await pw(e,t),i=hC(n.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]})}},Ype=class extends vO{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await pw(e,t),i=hC(n.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[r.data[t],Math.log(i[t])])}},yO=class{constructor(e){if(e)for(let t in e){if(t in this)throw TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let n=e[t];if(!(n instanceof L))throw TypeError(`Expected a Tensor for key "${t}", got ${typeof n}`);this[t]=n}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith(`past_key_values.`))return e[t].dims.at(-2);throw Error(`Unable to determine sequence length from the cache.`)}update(e){for(let t in e){let n=this[t],r=e[t];n&&n!==r&&n.location===`gpu-buffer`&&n.dispose(),this[t]=r}}async dispose(){let e=[];for(let t of Object.values(this))t.location===`gpu-buffer`&&e.push(t.dispose());await Promise.all(e)}},R={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},bO={[R.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??`model`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[R.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??`model`})},[R.Seq2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[R.Vision2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[R.Musicgen]:{sessions:()=>({model:`text_encoder`,decoder_model_merged:`decoder_model_merged`,encodec_decode:`encodec_decode`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[R.EncoderDecoder]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0}},[R.MaskGeneration]:{sessions:()=>({model:`vision_encoder`,prompt_encoder_mask_decoder:`prompt_encoder_mask_decoder`})},[R.ImageTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...bO[R.ImageTextToText].text_only_sessions};return n||(r.vision_encoder=`vision_encoder`),e.is_encoder_decoder&&(r.model=`encoder_model`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[R.AudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...bO[R.AudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[R.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...bO[R.ImageAudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`,r.vision_encoder=`vision_encoder`),r},optional_configs:{generation_config:`generation_config.json`}},[R.Phi3V]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`model`,vision_encoder:`vision_encoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[R.MultiModality]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`language_model`,lm_head:`lm_head`,gen_head:`gen_head`,gen_img_embeds:`gen_img_embeds`,image_decode:`image_decode`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[R.AutoEncoder]:{sessions:()=>({encoder_model:`encoder_model`,decoder_model:`decoder_model`})},[R.Supertonic]:{sessions:()=>({text_encoder:`text_encoder`,latent_denoiser:`latent_denoiser`,voice_decoder:`voice_decoder`})},[R.Chatterbox]:{sessions:()=>({embed_tokens:`embed_tokens`,speech_encoder:`speech_encoder`,model:`language_model`,conditional_decoder:`conditional_decoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[R.VoxtralRealtime]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...bO[R.VoxtralRealtime].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:`generation_config.json`}},default:{sessions:(e,t)=>({model:t.model_file_name??`model`})}};function Xpe(e,t,n={}){let r=bO[e]??bO.default;return{sessions:r.sessions(t,n,n.textOnly??!1),cache_sessions:r.cache_sessions,optional_configs:r.optional_configs}}function Zpe(e,{warn:t=!0}={}){let n=e.architectures||[];for(let e of n){let t=EO.get(e);if(t!==void 0)return t}if(e.model_type){let t=EO.get(e.model_type);if(t!==void 0)return t;for(let t of Object.values(xO))if(t.has(e.model_type)){let n=EO.get(t.get(e.model_type));if(n!==void 0)return n}}if(t){let t=n.length>0?n.join(`, `):`(none)`;Wb.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${t}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${GT}`)}return R.EncoderOnly}function Qpe(e,{config:t=null,cache_dir:n=null,local_files_only:r=!1,revision:i=`main`}={}){return t===null?aC(JSON.stringify([e,n,r,i]),()=>tO.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})):tO.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})}async function $pe(e,{config:t=null,dtype:n=null,device:r=null,model_file_name:i=null}={}){t=await Qpe(e,{config:t});let a=[`config.json`],o=t[`transformers.js_config`]??{},s=o.use_external_data_format,c=`onnx`,l=r??o.device,u=n??o.dtype,d=Zpe(t),f=(e,t=null)=>{t??=e;let n=ew(l,e),r=aw[ow(u,e,n)]??``,i=`${t}${r}.onnx`,o=`${c}/${i}`;a.push(o);let d=nO(s,i,e);for(let e of rO(i,d)){let t=`${c}/${e}`;a.push(t)}},{sessions:p,optional_configs:m}=Xpe(d,t,{model_file_name:i});for(let[e,t]of Object.entries(p))f(e,t);if(m)for(let e of Object.values(m))a.push(e);return a}var xO=null;function eme(e){xO=e}function SO(e){if(e instanceof L)return e;if(e.length===0)throw Error(`items must be non-empty`);if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.`);return new L(`int64`,BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}return new L(`int64`,BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length])}function CO(e){return new L(`bool`,[e],[1])}var wO={[R.DecoderOnly]:{can_generate:!0,forward:PO,prepare_inputs:LO},[R.DecoderOnlyWithoutHead]:{can_generate:!1,forward:PO,prepare_inputs:LO},[R.Seq2Seq]:{can_generate:!0,forward:kO,prepare_inputs:RO},[R.Vision2Seq]:{can_generate:!0,forward:kO,prepare_inputs:RO},[R.Musicgen]:{can_generate:!0,forward:kO},[R.EncoderDecoder]:{can_generate:!1,forward:kO},[R.ImageTextToText]:{can_generate:!0,forward:ime,prepare_inputs:zO},[R.AudioTextToText]:{can_generate:!0,forward:rme,prepare_inputs:zO},[R.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:zO},[R.Phi3V]:{can_generate:!0,prepare_inputs:zO},[R.MultiModality]:{can_generate:!0},[R.AutoEncoder]:{can_generate:!1,forward:tme},[R.Chatterbox]:{can_generate:!0,forward:AO},[R.VoxtralRealtime]:{can_generate:!0,prepare_inputs:LO},default:{can_generate:!1,forward:AO}};function TO(e,t){let n=EO.get(e),r=!1,i=t?.architectures?.[0];if(i&&i!==e&&e?.endsWith(`ForCausalLM`)&&i.endsWith(`ForConditionalGeneration`)){let e=EO.get(i);e!==void 0&&(n=e,r=!0)}let a=wO[n]??wO.default,o=bO[n]??bO.default;return{typeConfig:{...a,...o},textOnly:r,modelType:n}}var EO=new Map,DO=new Map,OO=new Map,z=class extends Nb{main_input_name=`input_ids`;forward_params=[`input_ids`,`attention_mask`];_return_dict_in_generate_keys=null;constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;let{typeConfig:r}=TO(OO.get(this.constructor),e);this.can_generate=r.can_generate,this._forward=r.forward,this._prepare_inputs_for_generation=r.prepare_inputs,this.can_generate&&this.forward_params.push(`past_key_values`),this.custom_config=this.config[`transformers.js_config`]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d},p=OO.get(this);n=f.config=await tO.from_pretrained(e,f);let{typeConfig:m,textOnly:h,modelType:g}=TO(p,n);if(g===void 0){let e=p??n?.model_type;e!==`custom`&&Wb.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${GT}.`)}if(t&&!(t instanceof Fb)){let r={};try{let t=await $pe(e,{config:n,dtype:l,device:c,model_file_name:o});(await Promise.all(t.map(t=>oC(e,t,f)))).forEach((e,n)=>{if(e.exists){let i=t[n]===`config.json`;r[t[n]]={loaded:i?e.size??0:0,total:e.size??0}}})}catch(e){Wb.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}Object.keys(r).length>0&&(f.progress_callback=new Fb(t,r))}let _=[kpe(e,m.sessions(n,f,h),f,m.cache_sessions)];m.optional_configs&&_.push(ome(e,m.optional_configs,f));let v=await Promise.all(_);return new this(n,...v)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,n=null){let r=new pO;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new Rpe(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new Lpe(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new Vpe(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new zpe(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&r.push(new Bpe(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new Npe(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new Ppe(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&r.push(new Fpe(e.suppress_tokens)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new mO(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new Hpe(e.guidance_scale)),e.temperature===0&&e.do_sample&&(Wb.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&r.push(new Upe(e.temperature)),n!==null&&r.extend(n),r}_prepare_generation_config(e,t,n=hO){let r={...this.config};for(let e of[`decoder`,`generator`,`text_config`])e in r&&Object.assign(r,r[e]);let i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,Hb(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){let n=new _O;return e.max_length!==null&&n.push(new Wpe(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new Gpe(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){let e=[xO.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,xO.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,xO.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,xO.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=OO.get(this.constructor),n=new Set,r=this.config.model_type;for(let t of e){let e=t?.get(r);e&&n.add(e)}let i=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(`, `)}`),Error(i)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw Error(`prepare_inputs_for_generation is not implemented for this model.`);return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=jO(t,n.past_key_values),n.input_ids=new L(`int64`,e.flat(),[e.length,1]),r?`decoder_attention_mask`in n&&(n.decoder_attention_mask=bw([n.decoder_attention_mask,kw([n.decoder_attention_mask.dims[0],1])],1)):n.attention_mask=bw([n.attention_mask,kw([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){let r=Hb(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes(`inputs_embeds`)&&!t.inputs_embeds&&`_prepare_inputs_embeds`in this){let{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...Hb(a,[`inputs_embeds`,`attention_mask`])}}let{last_hidden_state:i}=await AO(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)i=bw([i,Ow(i,0)],0),`attention_mask`in t&&(t.attention_mask=bw([t.attention_mask,Mw(t.attention_mask)],0));else if(t.decoder_input_ids){let e=SO(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(i.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=bw(Array.from({length:e},()=>i),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:o,...s}=n;if(!(o instanceof L)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(r??=i,this.config.model_type===`musicgen`)o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[r]);else if(Array.isArray(r)){if(r.length!==e)throw Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=SO(o)}return s.decoder_attention_mask=Aw(o),{input_ids:o,model_inputs:s}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:s,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),l=this.config.is_encoder_decoder;l&&(`encoder_outputs`in s||(s=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:s,model_input_name:c,generation_config:t})));let u;l?{input_ids:u,model_inputs:s}=this._prepare_decoder_input_ids_for_generation({batch_size:s[c].dims.at(0),model_input_name:c,model_kwargs:s,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):u=s[c];let d=u.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=d+t.max_new_tokens);let f=this._get_logits_processor(t,d,n),p=this._get_stopping_criteria(t,r),m=s[c].dims.at(0),h=vO.getSampler(t),g=Array(m).fill(0),_=u.tolist();i&&i.put(_);let v,y={},b={};for(;;){if(s=this.prepare_inputs_for_generation(_,s,t),v=await this.forward(s),t.return_dict_in_generate){if(t.output_attentions){let e=nme(v);for(let t in e)t in y||(y[t]=[]),y[t].push(e[t])}else this._return_dict_in_generate_keys&&Object.assign(b,Hb(v,this._return_dict_in_generate_keys))}let e=f(_,v.logits.slice(null,-1,null).to(`float32`)),n=[];for(let t=0;te))break;s=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:v,model_inputs:s,is_encoder_decoder:l})}i&&i.end();let x=new L(`int64`,_.flat(),[_.length,_[0].length]),S=jO(v,s.past_key_values),C=new Set(Object.values(S));for(let e of Object.values(v))e.location===`gpu-buffer`&&!C.has(e)&&e.dispose();return`past_key_values`in a||t.return_dict_in_generate||await S.dispose(),t.return_dict_in_generate?{sequences:x,past_key_values:S,...y,...b}:x}async _encode_input(e,t,n){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let r=this.sessions[e];return(await aO(r,Hb(t,r.inputNames)))[n]}async encode_image(e){return this._encode_input(`vision_encoder`,e,`image_features`)}async encode_text(e){return this._encode_input(`embed_tokens`,e,`inputs_embeds`)}async encode_audio(e){return this._encode_input(`audio_encoder`,e,`audio_features`)}};async function kO(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,decoder_attention_mask:a,...o}=t;return n||=(await AO(e,Hb(t,e.sessions.model.inputNames))).last_hidden_state,o.input_ids=i,o.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes(`encoder_attention_mask`)&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await PO(e,o,!0)}async function AO(e,t){let n=e.sessions.model,r=Hb(t,n.inputNames);if(n.inputNames.includes(`inputs_embeds`)&&!r.inputs_embeds){if(!t.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(n.inputNames.includes(`token_type_ids`)&&!r.token_type_ids){if(!r.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");r.token_type_ids=Mw(r.input_ids)}if(n.inputNames.includes(`pixel_mask`)&&!r.pixel_mask){if(!r.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let e=r.pixel_values.dims;r.pixel_mask=kw([e[0],e[2],e[3]])}return await aO(n,r)}async function tme(e,t){let n=await e.encode(t);return await e.decode(n)}function jO(e,t){let n=Object.create(null);for(let r in e)if(r.startsWith(`present`)){let i=r.replace(`present_ssm`,`past_ssm`).replace(`present_conv`,`past_conv`).replace(`present_recurrent`,`past_recurrent`).replace(`present`,`past_key_values`);n[i]=r.includes(`encoder`)&&t?t[i]:e[r]}return t?(t.update(n),t):new yO(n)}function nme(e){let t={};for(let n of[`cross_attentions`,`encoder_attentions`,`decoder_attentions`])for(let r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}function MO(e,t){return e.map(e=>typeof e==`number`?e:t[e]??0)}function NO(e,t,n){if(n&&Object.keys(n).length>0)return Object.assign(t,n),n;let r=e.sessions.decoder_model_merged??e.sessions.model,i=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=$D(e.config),o=e.config?.normalized_config?.num_heads,s={batch_size:i};typeof o==`number`&&(s[`batch_size x num_heads`]=i*o);let c=Object.create(null);for(let e of r.inputMetadata){if(!a.has(e.name))continue;let n=MO(e.shape,s),r=n.reduce((e,t)=>e*t,1),i=sw[e.type],o=new L(e.type,new i(r),n);t[e.name]=o,c[e.name]=o}return n?(n.update(c),n):new yO(c)}async function PO(e,t,n=!1){let r=e.sessions[n?`decoder_model_merged`:`model`],{past_key_values:i,...a}=t;return r.inputNames.includes(`use_cache_branch`)&&(a.use_cache_branch=CO(i!=null&&Object.keys(i).length>0)),r.inputNames.includes(`position_ids`)&&a.attention_mask&&!a.position_ids&&(a.position_ids=ame(a,i,+!![`paligemma`,`gemma3_text`,`gemma3`].includes(e.config.model_type))),r.inputNames.includes(`num_logits_to_keep`)&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new L(`int64`,[0n],[])),NO(e,a,i),await aO(r,Hb(a,r.inputNames))}async function FO(e,{encode_function:t,merge_function:n,modality_input_names:r,modality_output_name:i,input_ids:a=null,attention_mask:o=null,position_ids:s=null,inputs_embeds:c=null,past_key_values:l=null,generation_config:u=null,logits_processor:d=null,...f}){if(!c){c=await e.encode_text({input_ids:a,...f});let s=Hb(f,r);if(Object.keys(s).length>0){if(a.dims[1]!==1){let e=await t({...s,...f});({inputs_embeds:c,attention_mask:o}=n({[i]:e,inputs_embeds:c,input_ids:a,attention_mask:o}))}else if(l&&a.dims[1]===1){let e=a.dims[1],t=l.get_seq_length();o=bw([kw([a.dims[0],t]),o.slice(null,[o.dims[1]-e,o.dims[1]])],1)}}}if(!s&&[`qwen2_vl`,`qwen2_vl_text`,`qwen2_5_vl`,`qwen2_5_vl_text`,`qwen3_vl`,`qwen3_vl_text`,`qwen3_vl_moe`,`qwen3_vl_moe_text`,`qwen3_5`,`qwen3_5_text`,`qwen3_5_moe`,`qwen3_5_moe_text`,`glm_ocr`,`glm_ocr_text`].includes(e.config.model_type)){let{image_grid_thw:t,video_grid_thw:n}=f;[s]=e.get_rope_index(a,t,n,o)}return await PO(e,{inputs_embeds:c,past_key_values:l,attention_mask:o,position_ids:s,generation_config:u,logits_processor:d},!0)}async function rme(e,t){return await FO(e,{...t,modality_input_names:[`audio_values`,`input_features`],modality_output_name:`audio_features`,encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function ime(e,t){return await FO(e,{...t,modality_input_names:[`pixel_values`],modality_output_name:`image_features`,encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function IO(e,t=0){let[n,r]=e.dims,i=e.data,a=new BigInt64Array(i.length);for(let e=0;ee.dims[1]||i[e.at(-1)])),{...n,decoder_input_ids:SO(t)}}function zO(e,...t){return e.config.is_encoder_decoder?RO(e,...t):LO(e,...t)}function BO({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i}){let a=r.tolist().map(t=>t.reduce((t,n,r)=>(n==e&&t.push(r),t),[])),o=a.reduce((e,t)=>e+t.length,0),s=n.dims[0];if(o!==s)throw Error(`Number of tokens and features do not match: tokens: ${o}, features ${s}`);let c=0;for(let e=0;e[r,await mC(e,t[r],!1,n)])))}var UO={};fb(UO,{ASTForAudioClassification:()=>vme,ASTModel:()=>_me,ASTPreTrainedModel:()=>JO,AfmoeForCausalLM:()=>mme,AfmoeModel:()=>pme,AfmoePreTrainedModel:()=>KO,AlbertForMaskedLM:()=>ume,AlbertForQuestionAnswering:()=>lme,AlbertForSequenceClassification:()=>cme,AlbertModel:()=>sme,AlbertPreTrainedModel:()=>WO,ApertusForCausalLM:()=>fme,ApertusModel:()=>dme,ApertusPreTrainedModel:()=>GO,ArceeForCausalLM:()=>gme,ArceeModel:()=>hme,ArceePreTrainedModel:()=>qO,BartForConditionalGeneration:()=>bme,BartForSequenceClassification:()=>xme,BartModel:()=>yme,BartPretrainedModel:()=>YO,BeitForImageClassification:()=>Cme,BeitModel:()=>Sme,BeitPreTrainedModel:()=>XO,BertForMaskedLM:()=>Tme,BertForQuestionAnswering:()=>Ome,BertForSequenceClassification:()=>Eme,BertForTokenClassification:()=>Dme,BertModel:()=>wme,BertPreTrainedModel:()=>ZO,BlenderbotForConditionalGeneration:()=>Ame,BlenderbotModel:()=>kme,BlenderbotPreTrainedModel:()=>QO,BlenderbotSmallForConditionalGeneration:()=>Mme,BlenderbotSmallModel:()=>jme,BlenderbotSmallPreTrainedModel:()=>$O,BloomForCausalLM:()=>Pme,BloomModel:()=>Nme,BloomPreTrainedModel:()=>ek,CHMv2ForDepthEstimation:()=>Hme,CHMv2PreTrainedModel:()=>ok,CLIPModel:()=>Wme,CLIPPreTrainedModel:()=>uk,CLIPSegForImageSegmentation:()=>Yme,CLIPSegModel:()=>Jme,CLIPSegPreTrainedModel:()=>fk,CLIPTextModel:()=>Gme,CLIPTextModelWithProjection:()=>dk,CLIPVisionModel:()=>Kme,CLIPVisionModelWithProjection:()=>qme,CamembertForMaskedLM:()=>Ime,CamembertForQuestionAnswering:()=>zme,CamembertForSequenceClassification:()=>Lme,CamembertForTokenClassification:()=>Rme,CamembertModel:()=>Fme,CamembertPreTrainedModel:()=>tk,ChatterboxModel:()=>ik,ChatterboxPreTrainedModel:()=>rk,ChineseCLIPModel:()=>Vme,ChineseCLIPPreTrainedModel:()=>ak,ClapAudioModelWithProjection:()=>lk,ClapModel:()=>Ume,ClapPreTrainedModel:()=>sk,ClapTextModelWithProjection:()=>ck,CodeGenForCausalLM:()=>Zme,CodeGenModel:()=>Xme,CodeGenPreTrainedModel:()=>pk,Cohere2ForCausalLM:()=>the,Cohere2Model:()=>ehe,Cohere2PreTrainedModel:()=>hk,CohereAsrForConditionalGeneration:()=>rhe,CohereAsrModel:()=>nhe,CohereAsrPreTrainedModel:()=>gk,CohereForCausalLM:()=>$me,CohereModel:()=>Qme,CoherePreTrainedModel:()=>mk,ConvBertForMaskedLM:()=>ahe,ConvBertForQuestionAnswering:()=>che,ConvBertForSequenceClassification:()=>ohe,ConvBertForTokenClassification:()=>she,ConvBertModel:()=>ihe,ConvBertPreTrainedModel:()=>_k,ConvNextForImageClassification:()=>uhe,ConvNextModel:()=>lhe,ConvNextPreTrainedModel:()=>vk,ConvNextV2ForImageClassification:()=>fhe,ConvNextV2Model:()=>dhe,ConvNextV2PreTrainedModel:()=>yk,DFineForObjectDetection:()=>ghe,DFineModel:()=>hhe,DFinePreTrainedModel:()=>Sk,DINOv3ConvNextModel:()=>Hhe,DINOv3ConvNextPreTrainedModel:()=>Bk,DINOv3ViTModel:()=>Uhe,DINOv3ViTPreTrainedModel:()=>Vk,DPTForDepthEstimation:()=>Zhe,DPTModel:()=>Xhe,DPTPreTrainedModel:()=>Wk,DacDecoderModel:()=>Dk,DacDecoderOutput:()=>wk,DacEncoderModel:()=>Ek,DacEncoderOutput:()=>Ck,DacModel:()=>_he,DacPreTrainedModel:()=>Tk,DebertaForMaskedLM:()=>yhe,DebertaForQuestionAnswering:()=>She,DebertaForSequenceClassification:()=>bhe,DebertaForTokenClassification:()=>xhe,DebertaModel:()=>vhe,DebertaPreTrainedModel:()=>Ok,DebertaV2ForMaskedLM:()=>Ehe,DebertaV2ForQuestionAnswering:()=>khe,DebertaV2ForSequenceClassification:()=>Dhe,DebertaV2ForTokenClassification:()=>Ohe,DebertaV2Model:()=>The,DebertaV2PreTrainedModel:()=>Ak,DecisionTransformerModel:()=>Ahe,DecisionTransformerPreTrainedModel:()=>jk,DeepseekV3ForCausalLM:()=>whe,DeepseekV3Model:()=>Che,DeepseekV3PreTrainedModel:()=>kk,DeiTForImageClassification:()=>Mhe,DeiTModel:()=>jhe,DeiTPreTrainedModel:()=>Mk,DepthAnythingForDepthEstimation:()=>Nhe,DepthAnythingPreTrainedModel:()=>Nk,DepthProForDepthEstimation:()=>Phe,DepthProPreTrainedModel:()=>Pk,DetrForObjectDetection:()=>Ihe,DetrForSegmentation:()=>Lhe,DetrModel:()=>Fhe,DetrObjectDetectionOutput:()=>Ik,DetrPreTrainedModel:()=>Fk,DetrSegmentationOutput:()=>Lk,Dinov2ForImageClassification:()=>zhe,Dinov2Model:()=>Rhe,Dinov2PreTrainedModel:()=>Rk,Dinov2WithRegistersForImageClassification:()=>Vhe,Dinov2WithRegistersModel:()=>Bhe,Dinov2WithRegistersPreTrainedModel:()=>zk,DistilBertForMaskedLM:()=>Jhe,DistilBertForQuestionAnswering:()=>qhe,DistilBertForSequenceClassification:()=>Ghe,DistilBertForTokenClassification:()=>Khe,DistilBertModel:()=>Whe,DistilBertPreTrainedModel:()=>Hk,DonutSwinModel:()=>Yhe,DonutSwinPreTrainedModel:()=>Uk,EdgeTamModel:()=>cbe,EfficientNetForImageClassification:()=>$he,EfficientNetModel:()=>Qhe,EfficientNetPreTrainedModel:()=>Gk,ElectraForMaskedLM:()=>tge,ElectraForQuestionAnswering:()=>ige,ElectraForSequenceClassification:()=>nge,ElectraForTokenClassification:()=>rge,ElectraModel:()=>ege,ElectraPreTrainedModel:()=>Kk,Ernie4_5ForCausalLM:()=>oge,Ernie4_5Model:()=>age,Ernie4_5PretrainedModel:()=>qk,EsmForMaskedLM:()=>cge,EsmForSequenceClassification:()=>lge,EsmForTokenClassification:()=>uge,EsmModel:()=>sge,EsmPreTrainedModel:()=>Jk,EuroBertForMaskedLM:()=>fge,EuroBertForSequenceClassification:()=>pge,EuroBertForTokenClassification:()=>mge,EuroBertModel:()=>dge,EuroBertPreTrainedModel:()=>Yk,ExaoneForCausalLM:()=>gge,ExaoneModel:()=>hge,ExaonePreTrainedModel:()=>Xk,FalconForCausalLM:()=>vge,FalconH1ForCausalLM:()=>bge,FalconH1Model:()=>yge,FalconH1PreTrainedModel:()=>Qk,FalconModel:()=>_ge,FalconPreTrainedModel:()=>Zk,FastViTForImageClassification:()=>Sge,FastViTModel:()=>xge,FastViTPreTrainedModel:()=>$k,Florence2ForConditionalGeneration:()=>Cge,Florence2PreTrainedModel:()=>eA,GLPNForDepthEstimation:()=>Bge,GLPNModel:()=>zge,GLPNPreTrainedModel:()=>_A,GPT2LMHeadModel:()=>Xge,GPT2Model:()=>Yge,GPT2PreTrainedModel:()=>SA,GPTBigCodeForCausalLM:()=>Hge,GPTBigCodeModel:()=>Vge,GPTBigCodePreTrainedModel:()=>vA,GPTJForCausalLM:()=>Qge,GPTJModel:()=>Zge,GPTJPreTrainedModel:()=>CA,GPTNeoForCausalLM:()=>Wge,GPTNeoModel:()=>Uge,GPTNeoPreTrainedModel:()=>yA,GPTNeoXForCausalLM:()=>Kge,GPTNeoXModel:()=>Gge,GPTNeoXPreTrainedModel:()=>bA,Gemma2ForCausalLM:()=>Dge,Gemma2Model:()=>Ege,Gemma2PreTrainedModel:()=>nA,Gemma3ForCausalLM:()=>jge,Gemma3ForConditionalGeneration:()=>oA,Gemma3Model:()=>Age,Gemma3PreTrainedModel:()=>aA,Gemma3nForCausalLM:()=>Mge,Gemma3nForConditionalGeneration:()=>cA,Gemma3nPreTrainedModel:()=>sA,Gemma4ForCausalLM:()=>Nge,Gemma4ForConditionalGeneration:()=>lA,GemmaForCausalLM:()=>Tge,GemmaModel:()=>wge,GemmaPreTrainedModel:()=>tA,GlmForCausalLM:()=>Fge,GlmModel:()=>Pge,GlmMoeDsaForCausalLM:()=>Lge,GlmMoeDsaModel:()=>Ige,GlmMoeDsaPreTrainedModel:()=>dA,GlmOcrForConditionalGeneration:()=>Rge,GlmPreTrainedModel:()=>uA,GptOssForCausalLM:()=>Jge,GptOssModel:()=>qge,GptOssPreTrainedModel:()=>xA,GraniteForCausalLM:()=>e_e,GraniteModel:()=>$ge,GraniteMoeHybridForCausalLM:()=>n_e,GraniteMoeHybridModel:()=>t_e,GraniteMoeHybridPreTrainedModel:()=>TA,GranitePreTrainedModel:()=>wA,GraniteSpeechForConditionalGeneration:()=>r_e,GroundingDinoForObjectDetection:()=>i_e,GroundingDinoPreTrainedModel:()=>OA,GroupViTModel:()=>a_e,GroupViTPreTrainedModel:()=>kA,HeliumForCausalLM:()=>s_e,HeliumModel:()=>o_e,HeliumPreTrainedModel:()=>AA,HieraForImageClassification:()=>l_e,HieraModel:()=>c_e,HieraPreTrainedModel:()=>jA,HubertForCTC:()=>g_e,HubertForSequenceClassification:()=>__e,HubertModel:()=>h_e,HubertPreTrainedModel:()=>m_e,HunYuanDenseV1ForCausalLM:()=>y_e,HunYuanDenseV1Model:()=>v_e,HunYuanDenseV1PreTrainedModel:()=>NA,IJepaForImageClassification:()=>x_e,IJepaModel:()=>b_e,IJepaPreTrainedModel:()=>FA,Idefics3ForConditionalGeneration:()=>PA,JAISLMHeadModel:()=>C_e,JAISModel:()=>S_e,JAISPreTrainedModel:()=>IA,JinaCLIPModel:()=>w_e,JinaCLIPPreTrainedModel:()=>LA,JinaCLIPTextModel:()=>RA,JinaCLIPVisionModel:()=>T_e,Lfm2ForCausalLM:()=>D_e,Lfm2Model:()=>E_e,Lfm2MoeForCausalLM:()=>A_e,Lfm2MoeModel:()=>k_e,Lfm2MoePreTrainedModel:()=>BA,Lfm2PreTrainedModel:()=>zA,Lfm2VlForConditionalGeneration:()=>j_e,LightOnOcrForConditionalGeneration:()=>O_e,LiteWhisperForConditionalGeneration:()=>HN,Llama4ForCausalLM:()=>P_e,Llama4PreTrainedModel:()=>HA,LlamaForCausalLM:()=>N_e,LlamaModel:()=>M_e,LlamaPreTrainedModel:()=>VA,LlavaForConditionalGeneration:()=>iA,LlavaOnevisionForConditionalGeneration:()=>iA,LlavaPreTrainedModel:()=>rA,LlavaQwen2ForCausalLM:()=>kge,LongT5ForConditionalGeneration:()=>I_e,LongT5Model:()=>F_e,LongT5PreTrainedModel:()=>UA,M2M100ForConditionalGeneration:()=>R_e,M2M100Model:()=>L_e,M2M100PreTrainedModel:()=>WA,MBartForCausalLM:()=>K_e,MBartForConditionalGeneration:()=>W_e,MBartForSequenceClassification:()=>G_e,MBartModel:()=>U_e,MBartPreTrainedModel:()=>qA,MPNetForMaskedLM:()=>Mve,MPNetForQuestionAnswering:()=>Fve,MPNetForSequenceClassification:()=>Nve,MPNetForTokenClassification:()=>Pve,MPNetModel:()=>jve,MPNetPreTrainedModel:()=>gj,MT5ForConditionalGeneration:()=>zve,MT5Model:()=>Rve,MT5PreTrainedModel:()=>vj,MarianMTModel:()=>B_e,MarianModel:()=>z_e,MarianPreTrainedModel:()=>GA,MaskFormerForInstanceSegmentation:()=>H_e,MaskFormerModel:()=>V_e,MaskFormerPreTrainedModel:()=>KA,Metric3DForDepthEstimation:()=>q_e,Metric3DPreTrainedModel:()=>JA,Metric3Dv2ForDepthEstimation:()=>J_e,Metric3Dv2PreTrainedModel:()=>YA,MgpstrForSceneTextRecognition:()=>Y_e,MgpstrModelOutput:()=>XA,MgpstrPreTrainedModel:()=>ZA,MimiDecoderModel:()=>nj,MimiDecoderOutput:()=>$A,MimiEncoderModel:()=>tj,MimiEncoderOutput:()=>QA,MimiModel:()=>X_e,MimiPreTrainedModel:()=>ej,Mistral4ForCausalLM:()=>eve,Mistral4Model:()=>$_e,Mistral4PreTrainedModel:()=>ij,MistralForCausalLM:()=>Q_e,MistralModel:()=>Z_e,MistralPreTrainedModel:()=>rj,MobileBertForMaskedLM:()=>nve,MobileBertForQuestionAnswering:()=>ive,MobileBertForSequenceClassification:()=>rve,MobileBertModel:()=>tve,MobileBertPreTrainedModel:()=>aj,MobileLLMForCausalLM:()=>ove,MobileLLMModel:()=>ave,MobileLLMPreTrainedModel:()=>oj,MobileNetV1ForImageClassification:()=>cve,MobileNetV1ForSemanticSegmentation:()=>lve,MobileNetV1Model:()=>sve,MobileNetV1PreTrainedModel:()=>sj,MobileNetV2ForImageClassification:()=>dve,MobileNetV2ForSemanticSegmentation:()=>fve,MobileNetV2Model:()=>uve,MobileNetV2PreTrainedModel:()=>cj,MobileNetV3ForImageClassification:()=>mve,MobileNetV3ForSemanticSegmentation:()=>hve,MobileNetV3Model:()=>pve,MobileNetV3PreTrainedModel:()=>lj,MobileNetV4ForImageClassification:()=>_ve,MobileNetV4ForSemanticSegmentation:()=>vve,MobileNetV4Model:()=>gve,MobileNetV4PreTrainedModel:()=>uj,MobileViTForImageClassification:()=>bve,MobileViTModel:()=>yve,MobileViTPreTrainedModel:()=>dj,MobileViTV2ForImageClassification:()=>Sve,MobileViTV2Model:()=>xve,MobileViTV2PreTrainedModel:()=>fj,ModernBertDecoderForCausalLM:()=>Ove,ModernBertDecoderModel:()=>Dve,ModernBertDecoderPreTrainedModel:()=>mj,ModernBertForMaskedLM:()=>wve,ModernBertForSequenceClassification:()=>Tve,ModernBertForTokenClassification:()=>Eve,ModernBertModel:()=>Cve,ModernBertPreTrainedModel:()=>pj,Moondream1ForConditionalGeneration:()=>Oge,MoonshineForConditionalGeneration:()=>Ave,MoonshineModel:()=>kve,MoonshinePreTrainedModel:()=>hj,MptForCausalLM:()=>Lve,MptModel:()=>Ive,MptPreTrainedModel:()=>_j,MultiModalityCausalLM:()=>Bve,MultiModalityPreTrainedModel:()=>yj,MusicgenForCausalLM:()=>Hve,MusicgenForConditionalGeneration:()=>xj,MusicgenModel:()=>Vve,MusicgenPreTrainedModel:()=>bj,NanoChatForCausalLM:()=>Wve,NanoChatModel:()=>Uve,NanoChatPreTrainedModel:()=>Sj,NemotronHForCausalLM:()=>Kve,NemotronHModel:()=>Gve,NemotronHPreTrainedModel:()=>Cj,NeoBertForMaskedLM:()=>Jve,NeoBertForQuestionAnswering:()=>Zve,NeoBertForSequenceClassification:()=>Yve,NeoBertForTokenClassification:()=>Xve,NeoBertModel:()=>qve,NeoBertPreTrainedModel:()=>wj,NomicBertModel:()=>Qve,NomicBertPreTrainedModel:()=>Tj,OPTForCausalLM:()=>fye,OPTModel:()=>dye,OPTPreTrainedModel:()=>Mj,Olmo2ForCausalLM:()=>nye,Olmo2Model:()=>tye,Olmo2PreTrainedModel:()=>Dj,Olmo3ForCausalLM:()=>iye,Olmo3Model:()=>rye,Olmo3PreTrainedModel:()=>Oj,OlmoForCausalLM:()=>eye,OlmoHybridForCausalLM:()=>oye,OlmoHybridModel:()=>aye,OlmoHybridPreTrainedModel:()=>kj,OlmoModel:()=>$ve,OlmoPreTrainedModel:()=>Ej,OpenAIPrivacyFilterForTokenClassification:()=>cye,OpenAIPrivacyFilterModel:()=>sye,OpenAIPrivacyFilterPreTrainedModel:()=>Aj,OpenELMForCausalLM:()=>uye,OpenELMModel:()=>lye,OpenELMPreTrainedModel:()=>jj,OwlViTForObjectDetection:()=>gye,OwlViTModel:()=>hye,OwlViTPreTrainedModel:()=>Pj,Owlv2ForObjectDetection:()=>mye,Owlv2Model:()=>pye,Owlv2PreTrainedModel:()=>Nj,PaliGemmaForConditionalGeneration:()=>_ye,ParakeetForCTC:()=>vye,ParakeetPreTrainedModel:()=>Fj,PatchTSMixerForPrediction:()=>bye,PatchTSMixerModel:()=>yye,PatchTSMixerPreTrainedModel:()=>Ij,PatchTSTForPrediction:()=>Sye,PatchTSTModel:()=>xye,PatchTSTPreTrainedModel:()=>Lj,Phi3ForCausalLM:()=>Eye,Phi3Model:()=>Tye,Phi3PreTrainedModel:()=>zj,Phi3VForCausalLM:()=>Vj,Phi3VPreTrainedModel:()=>Bj,PhiForCausalLM:()=>wye,PhiModel:()=>Cye,PhiPreTrainedModel:()=>Rj,PreTrainedModel:()=>z,PvtForImageClassification:()=>Oye,PvtModel:()=>Dye,PvtPreTrainedModel:()=>Hj,PyAnnoteForAudioFrameClassification:()=>Aye,PyAnnoteModel:()=>kye,PyAnnotePreTrainedModel:()=>Uj,Qwen2ForCausalLM:()=>Mye,Qwen2Model:()=>jye,Qwen2MoeForCausalLM:()=>Pye,Qwen2MoeModel:()=>Nye,Qwen2MoePreTrainedModel:()=>Gj,Qwen2PreTrainedModel:()=>Wj,Qwen2VLForCausalLM:()=>mA,Qwen2VLForConditionalGeneration:()=>pA,Qwen2VLPreTrainedModel:()=>fA,Qwen2_5_VLForCausalLM:()=>gA,Qwen2_5_VLForConditionalGeneration:()=>hA,Qwen3ForCausalLM:()=>Iye,Qwen3Model:()=>Fye,Qwen3MoeForCausalLM:()=>Rye,Qwen3MoeModel:()=>Lye,Qwen3MoePreTrainedModel:()=>qj,Qwen3NextForCausalLM:()=>Bye,Qwen3NextModel:()=>zye,Qwen3NextPreTrainedModel:()=>Jj,Qwen3PreTrainedModel:()=>Kj,Qwen3VLForCausalLM:()=>Xj,Qwen3VLForConditionalGeneration:()=>Yj,Qwen3VLMoeForCausalLM:()=>Hye,Qwen3VLMoeForConditionalGeneration:()=>Vye,Qwen3_5ForCausalLM:()=>Qj,Qwen3_5ForConditionalGeneration:()=>Zj,Qwen3_5MoeForCausalLM:()=>Wye,Qwen3_5MoeForConditionalGeneration:()=>Uye,RFDetrForObjectDetection:()=>Jye,RFDetrModel:()=>qye,RFDetrObjectDetectionOutput:()=>tM,RFDetrPreTrainedModel:()=>eM,RTDetrForObjectDetection:()=>mhe,RTDetrModel:()=>phe,RTDetrObjectDetectionOutput:()=>xk,RTDetrPreTrainedModel:()=>bk,RTDetrV2ForObjectDetection:()=>obe,RTDetrV2Model:()=>abe,RTDetrV2ObjectDetectionOutput:()=>aM,RTDetrV2PreTrainedModel:()=>iM,ResNetForImageClassification:()=>Kye,ResNetModel:()=>Gye,ResNetPreTrainedModel:()=>$j,RoFormerForMaskedLM:()=>tbe,RoFormerForQuestionAnswering:()=>ibe,RoFormerForSequenceClassification:()=>nbe,RoFormerForTokenClassification:()=>rbe,RoFormerModel:()=>ebe,RoFormerPreTrainedModel:()=>rM,RobertaForMaskedLM:()=>Xye,RobertaForQuestionAnswering:()=>$ye,RobertaForSequenceClassification:()=>Zye,RobertaForTokenClassification:()=>Qye,RobertaModel:()=>Yye,RobertaPreTrainedModel:()=>nM,Sam2ImageSegmentationOutput:()=>cM,Sam2Model:()=>uM,Sam2PreTrainedModel:()=>lM,Sam3TrackerModel:()=>lbe,SamImageSegmentationOutput:()=>oM,SamModel:()=>sbe,SamPreTrainedModel:()=>sM,SapiensForDepthEstimation:()=>dbe,SapiensForNormalEstimation:()=>fbe,SapiensForSemanticSegmentation:()=>ube,SapiensPreTrainedModel:()=>dM,SegformerForImageClassification:()=>mbe,SegformerForSemanticSegmentation:()=>hbe,SegformerModel:()=>pbe,SegformerPreTrainedModel:()=>fM,SiglipModel:()=>gbe,SiglipPreTrainedModel:()=>pM,SiglipTextModel:()=>mM,SiglipVisionModel:()=>_be,SmolLM3ForCausalLM:()=>ybe,SmolLM3Model:()=>vbe,SmolLM3PreTrainedModel:()=>hM,SmolVLMForConditionalGeneration:()=>bbe,SnacDecoderModel:()=>vM,SnacEncoderModel:()=>_M,SnacModel:()=>xbe,SnacPreTrainedModel:()=>gM,SolarOpenForCausalLM:()=>Cbe,SolarOpenModel:()=>Sbe,SolarOpenPreTrainedModel:()=>yM,SpeechT5ForSpeechToText:()=>Tbe,SpeechT5ForTextToSpeech:()=>Ebe,SpeechT5HifiGan:()=>Dbe,SpeechT5Model:()=>wbe,SpeechT5PreTrainedModel:()=>bM,SqueezeBertForMaskedLM:()=>kbe,SqueezeBertForQuestionAnswering:()=>jbe,SqueezeBertForSequenceClassification:()=>Abe,SqueezeBertModel:()=>Obe,SqueezeBertPreTrainedModel:()=>xM,StableLmForCausalLM:()=>Nbe,StableLmModel:()=>Mbe,StableLmPreTrainedModel:()=>SM,Starcoder2ForCausalLM:()=>Fbe,Starcoder2Model:()=>Pbe,Starcoder2PreTrainedModel:()=>CM,StyleTextToSpeech2Model:()=>Ibe,StyleTextToSpeech2PreTrainedModel:()=>wM,SupertonicForConditionalGeneration:()=>EM,SupertonicPreTrainedModel:()=>TM,Swin2SRForImageSuperResolution:()=>AM,Swin2SRModel:()=>kM,Swin2SRPreTrainedModel:()=>OM,SwinForImageClassification:()=>Rbe,SwinForSemanticSegmentation:()=>zbe,SwinModel:()=>Lbe,SwinPreTrainedModel:()=>DM,T5ForConditionalGeneration:()=>NM,T5Model:()=>MM,T5PreTrainedModel:()=>jM,TableTransformerForObjectDetection:()=>IM,TableTransformerModel:()=>FM,TableTransformerObjectDetectionOutput:()=>LM,TableTransformerPreTrainedModel:()=>PM,TrOCRForCausalLM:()=>zM,TrOCRPreTrainedModel:()=>RM,UltravoxModel:()=>DA,UltravoxPreTrainedModel:()=>EA,UniSpeechForCTC:()=>HM,UniSpeechForSequenceClassification:()=>UM,UniSpeechModel:()=>VM,UniSpeechPreTrainedModel:()=>BM,UniSpeechSatForAudioFrameClassification:()=>JM,UniSpeechSatForCTC:()=>KM,UniSpeechSatForSequenceClassification:()=>qM,UniSpeechSatModel:()=>GM,UniSpeechSatPreTrainedModel:()=>WM,VaultGemmaForCausalLM:()=>ZM,VaultGemmaModel:()=>XM,VaultGemmaPreTrainedModel:()=>YM,ViTForImageClassification:()=>tN,ViTMAEModel:()=>rN,ViTMAEPreTrainedModel:()=>nN,ViTMSNForImageClassification:()=>oN,ViTMSNModel:()=>aN,ViTMSNPreTrainedModel:()=>iN,ViTModel:()=>eN,ViTPreTrainedModel:()=>$M,VisionEncoderDecoderModel:()=>QM,VitMatteForImageMatting:()=>cN,VitMattePreTrainedModel:()=>sN,VitPoseForPoseEstimation:()=>uN,VitPosePreTrainedModel:()=>lN,VitsModel:()=>pN,VitsModelOutput:()=>dN,VitsPreTrainedModel:()=>fN,VoxtralForConditionalGeneration:()=>mN,VoxtralRealtimeForConditionalGeneration:()=>wN,VoxtralRealtimePreTrainedModel:()=>CN,Wav2Vec2BertForCTC:()=>DN,Wav2Vec2BertForSequenceClassification:()=>ON,Wav2Vec2BertModel:()=>EN,Wav2Vec2BertPreTrainedModel:()=>TN,Wav2Vec2ForAudioFrameClassification:()=>p_e,Wav2Vec2ForCTC:()=>d_e,Wav2Vec2ForSequenceClassification:()=>f_e,Wav2Vec2Model:()=>u_e,Wav2Vec2PreTrainedModel:()=>MA,WavLMForAudioFrameClassification:()=>FN,WavLMForCTC:()=>MN,WavLMForSequenceClassification:()=>NN,WavLMForXVector:()=>PN,WavLMModel:()=>jN,WavLMPreTrainedModel:()=>AN,WeSpeakerResNetModel:()=>LN,WeSpeakerResNetPreTrainedModel:()=>IN,WhisperForConditionalGeneration:()=>VN,WhisperModel:()=>BN,WhisperPreTrainedModel:()=>zN,XLMForQuestionAnswering:()=>JN,XLMForSequenceClassification:()=>KN,XLMForTokenClassification:()=>qN,XLMModel:()=>WN,XLMPreTrainedModel:()=>UN,XLMRobertaForMaskedLM:()=>ZN,XLMRobertaForQuestionAnswering:()=>eP,XLMRobertaForSequenceClassification:()=>QN,XLMRobertaForTokenClassification:()=>$N,XLMRobertaModel:()=>XN,XLMRobertaPreTrainedModel:()=>YN,XLMWithLMHeadModel:()=>GN,XVectorOutput:()=>kN,YolosForObjectDetection:()=>rP,YolosModel:()=>nP,YolosObjectDetectionOutput:()=>iP,YolosPreTrainedModel:()=>tP,YoutuForCausalLM:()=>sP,YoutuModel:()=>oP,YoutuPreTrainedModel:()=>aP});var WO=class extends z{},sme=class extends WO{},cme=class extends WO{async _call(e){return new sO(await super._call(e))}},lme=class extends WO{async _call(e){return new uO(await super._call(e))}},ume=class extends WO{async _call(e){return new lO(await super._call(e))}},GO=class extends z{},dme=class extends GO{},fme=class extends GO{},KO=class extends z{},pme=class extends KO{},mme=class extends KO{},qO=class extends z{},hme=class extends qO{},gme=class extends qO{},JO=class extends z{},_me=class extends JO{},vme=class extends JO{},YO=class extends z{},yme=class extends YO{},bme=class extends YO{},xme=class extends YO{async _call(e){return new sO(await super._call(e))}},XO=class extends z{},Sme=class extends XO{},Cme=class extends XO{async _call(e){return new sO(await super._call(e))}},ZO=class extends z{},wme=class extends ZO{},Tme=class extends ZO{async _call(e){return new lO(await super._call(e))}},Eme=class extends ZO{async _call(e){return new sO(await super._call(e))}},Dme=class extends ZO{async _call(e){return new cO(await super._call(e))}},Ome=class extends ZO{async _call(e){return new uO(await super._call(e))}},QO=class extends z{},kme=class extends QO{},Ame=class extends QO{},$O=class extends z{},jme=class extends $O{},Mme=class extends $O{},ek=class extends z{},Nme=class extends ek{},Pme=class extends ek{},tk=class extends z{},Fme=class extends tk{},Ime=class extends tk{async _call(e){return new lO(await super._call(e))}},Lme=class extends tk{async _call(e){return new sO(await super._call(e))}},Rme=class extends tk{async _call(e){return new cO(await super._call(e))}},zme=class extends tk{async _call(e){return new uO(await super._call(e))}},Bme=4299n,nk=6561n,rk=class extends z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`audio_values`,`exaggeration`,`audio_features`,`audio_tokens`,`speaker_embeddings`,`speaker_features`,`past_key_values`];main_input_name=`input_ids`;_return_dict_in_generate_keys=[`audio_tokens`,`speaker_embeddings`,`speaker_features`]},ik=class extends rk{async encode_speech(e){return aO(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:n=null,exaggeration:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,audio_features:l=null,audio_tokens:u=null,speaker_embeddings:d=null,speaker_features:f=null,...p}){let m;if(!a){let s=this.sessions.embed_tokens.inputNames,c={input_ids:e};if(s.includes(`exaggeration`)){if(!(r instanceof L)){let t=e.dims[0];if(r==null)r=Dw([t],.5);else if(typeof r==`number`)r=Dw([t],r);else if(Array.isArray(r))r=new L(`float32`,r,[t]);else throw Error("Unsupported type for `exaggeration` input")}c.exaggeration=r}if(s.includes(`position_ids`)&&(c.position_ids=i),{inputs_embeds:a}=await aO(this.sessions.embed_tokens,c),l&&u&&d&&f&&(m={audio_features:l,audio_tokens:u,speaker_embeddings:d,speaker_features:f}),m||n)m??=await this.encode_speech(n),a=bw([m.audio_features,a],1),t=kw([a.dims[0],a.dims[1]]);else{let e=a.dims[1];if(!o||e!==1)throw Error(`Incorrect state encountered during generation.`);let n=o.get_seq_length();t=kw([a.dims[0],n+e])}}return{...await PO(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:s,logits_processor:c},!1),...m}}prepare_inputs_for_generation(e,t,n){return!t.position_ids&&this.sessions.embed_tokens.inputNames.includes(`position_ids`)&&(t.position_ids=t.input_ids.dims[1]===1?new L(`int64`,Array.from({length:e.length},(t,n)=>e[n].length-e[n].findLastIndex(e=>e==nk)-1),[e.length,1]):new L(`int64`,t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=nk?0:t++)}).flat(),t.input_ids.dims)),t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),LO(this,e,t,n)}async generate(e){let{sequences:t,audio_tokens:n,speaker_embeddings:r,speaker_features:i}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=bw([n,a,Dw([a.dims[0],3],Bme)],1),{waveform:s}=await aO(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:i,speaker_embeddings:r});return s}},ak=class extends z{},Vme=class extends ak{},ok=class extends z{},Hme=class extends ok{},sk=class extends z{},Ume=class extends sk{},ck=class extends sk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},lk=class extends sk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`audio_model`})}},uk=class extends z{},Wme=class extends uk{},Gme=class extends uk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},dk=class extends uk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Kme=class extends uk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},qme=class extends uk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},fk=class extends z{},Jme=class extends fk{},Yme=class extends fk{},pk=class extends z{},Xme=class extends pk{},Zme=class extends pk{},mk=class extends z{},Qme=class extends mk{},$me=class extends mk{},hk=class extends z{},ehe=class extends hk{},the=class extends hk{},gk=class extends z{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},nhe=class extends gk{},rhe=class extends gk{},_k=class extends z{},ihe=class extends _k{},ahe=class extends _k{async _call(e){return new lO(await super._call(e))}},ohe=class extends _k{async _call(e){return new sO(await super._call(e))}},she=class extends _k{async _call(e){return new cO(await super._call(e))}},che=class extends _k{async _call(e){return new uO(await super._call(e))}},vk=class extends z{},lhe=class extends vk{},uhe=class extends vk{async _call(e){return new sO(await super._call(e))}},yk=class extends z{},dhe=class extends yk{},fhe=class extends yk{async _call(e){return new sO(await super._call(e))}},bk=class extends z{},phe=class extends bk{},mhe=class extends bk{async _call(e){return new xk(await super._call(e))}},xk=class extends oO{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Sk=class extends z{},hhe=class extends Sk{},ghe=class extends Sk{async _call(e){return new xk(await super._call(e))}},Ck=class extends oO{constructor({audio_codes:e}){super(),this.audio_codes=e}},wk=class extends oO{constructor({audio_values:e}){super(),this.audio_values=e}},Tk=class extends z{main_input_name=`input_values`;forward_params=[`input_values`]},_he=class extends Tk{async encode(e){return new Ck(await aO(this.sessions.encoder_model,e))}async decode(e){return new wk(await aO(this.sessions.decoder_model,e))}},Ek=class extends Tk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},Dk=class extends Tk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},Ok=class extends z{},vhe=class extends Ok{},yhe=class extends Ok{async _call(e){return new lO(await super._call(e))}},bhe=class extends Ok{async _call(e){return new sO(await super._call(e))}},xhe=class extends Ok{async _call(e){return new cO(await super._call(e))}},She=class extends Ok{async _call(e){return new uO(await super._call(e))}},kk=class extends z{},Che=class extends kk{},whe=class extends kk{},Ak=class extends z{},The=class extends Ak{},Ehe=class extends Ak{async _call(e){return new lO(await super._call(e))}},Dhe=class extends Ak{async _call(e){return new sO(await super._call(e))}},Ohe=class extends Ak{async _call(e){return new cO(await super._call(e))}},khe=class extends Ak{async _call(e){return new uO(await super._call(e))}},jk=class extends z{},Ahe=class extends jk{},Mk=class extends z{},jhe=class extends Mk{},Mhe=class extends Mk{async _call(e){return new sO(await super._call(e))}},Nk=class extends z{},Nhe=class extends Nk{},Pk=class extends z{},Phe=class extends Pk{},Fk=class extends z{},Fhe=class extends Fk{},Ihe=class extends Fk{async _call(e){return new Ik(await super._call(e))}},Lhe=class extends Fk{async _call(e){return new Lk(await super._call(e))}},Ik=class extends oO{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Lk=class extends oO{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}},Rk=class extends z{},Rhe=class extends Rk{},zhe=class extends Rk{async _call(e){return new sO(await super._call(e))}},zk=class extends z{},Bhe=class extends zk{},Vhe=class extends zk{async _call(e){return new sO(await super._call(e))}},Bk=class extends z{},Hhe=class extends Bk{},Vk=class extends z{},Uhe=class extends Vk{},Hk=class extends z{},Whe=class extends Hk{},Ghe=class extends Hk{async _call(e){return new sO(await super._call(e))}},Khe=class extends Hk{async _call(e){return new cO(await super._call(e))}},qhe=class extends Hk{async _call(e){return new uO(await super._call(e))}},Jhe=class extends Hk{async _call(e){return new lO(await super._call(e))}},Uk=class extends z{},Yhe=class extends Uk{},Wk=class extends z{},Xhe=class extends Wk{},Zhe=class extends Wk{},Gk=class extends z{},Qhe=class extends Gk{},$he=class extends Gk{async _call(e){return new sO(await super._call(e))}},Kk=class extends z{},ege=class extends Kk{},tge=class extends Kk{async _call(e){return new lO(await super._call(e))}},nge=class extends Kk{async _call(e){return new sO(await super._call(e))}},rge=class extends Kk{async _call(e){return new cO(await super._call(e))}},ige=class extends Kk{async _call(e){return new uO(await super._call(e))}},qk=class extends z{},age=class extends qk{},oge=class extends qk{},Jk=class extends z{},sge=class extends Jk{},cge=class extends Jk{async _call(e){return new lO(await super._call(e))}},lge=class extends Jk{async _call(e){return new sO(await super._call(e))}},uge=class extends Jk{async _call(e){return new cO(await super._call(e))}},Yk=class extends z{},dge=class extends Yk{},fge=class extends Yk{async _call(e){return new lO(await super._call(e))}},pge=class extends Yk{async _call(e){return new sO(await super._call(e))}},mge=class extends Yk{async _call(e){return new cO(await super._call(e))}},Xk=class extends z{},hge=class extends Xk{},gge=class extends Xk{},Zk=class extends z{},_ge=class extends Zk{},vge=class extends Zk{},Qk=class extends z{},yge=class extends Qk{},bge=class extends Qk{},$k=class extends z{},xge=class extends $k{},Sge=class extends $k{async _call(e){return new sO(await super._call(e))}},eA=class extends z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`pixel_values`,`encoder_outputs`,`decoder_input_ids`,`decoder_inputs_embeds`,`decoder_attention_mask`,`past_key_values`];main_input_name=`inputs_embeds`},Cge=class extends eA{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:n,attention_mask:r}){return{inputs_embeds:bw([t,e],1),attention_mask:bw([kw(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:n,attention_mask:r}){if(!e&&!t)throw Error("Either `input_ids` or `pixel_values` should be provided.");let i,a;return e&&(i=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),i&&a?{inputs_embeds:n,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:i,image_features:a,input_ids:e,attention_mask:r}):n=i||a,{inputs_embeds:n,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:n,decoder_input_ids:r,decoder_attention_mask:i,encoder_outputs:a,past_key_values:o,inputs_embeds:s,decoder_inputs_embeds:c}){if(s||({inputs_embeds:s,attention_mask:n}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n})),!a){let{last_hidden_state:e}=await AO(this,{inputs_embeds:s,attention_mask:n});a=e}if(!c){if(!r)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:r})}let l={inputs_embeds:c,attention_mask:i,encoder_attention_mask:n,encoder_hidden_states:a,past_key_values:o};return await PO(this,l,!0)}},tA=class extends z{},wge=class extends tA{},Tge=class extends tA{},nA=class extends z{},Ege=class extends nA{},Dge=class extends nA{},rA=class extends z{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`position_ids`,`past_key_values`]},iA=class extends rA{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return VO({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:n})}},Oge=class extends iA{},kge=class extends iA{},aA=class extends z{},Age=class extends aA{},oA=class extends iA{},jge=class extends oA{},sA=class extends z{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`input_features`,`input_features_mask`,`past_key_values`]},cA=class extends sA{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,input_features:r=null,input_features_mask:i=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:s=null,past_key_values:c=null,generation_config:l=null,logits_processor:u=null,...d}){if((!o||!s)&&({inputs_embeds:o,per_layer_inputs:s}=await aO(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(n){let{image_features:r}=await this._encode_vision({pixel_values:n,...d});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:r,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(r){let{audio_features:n}=await aO(this.sessions.audio_encoder,{input_features:r,input_features_mask:i});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:n,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await PO(this,{inputs_embeds:o,per_layer_inputs:s,past_key_values:c,attention_mask:t,position_ids:a,generation_config:l,logits_processor:u},!0)}_encode_vision(e){return aO(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return VO({image_token_id:this.config.image_token_id,...e,image_features:n})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return HO({audio_token_id:this.config.audio_token_id,...e,audio_features:n})}},Mge=class extends cA{},lA=class extends cA{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`image_position_ids`,`input_features`,`input_features_mask`,`past_key_values`];_encode_vision(e){return aO(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},Nge=class extends lA{},uA=class extends z{},Pge=class extends uA{},Fge=class extends uA{},dA=class extends z{},Ige=class extends dA{},Lge=class extends dA{},fA=class extends z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`,`pixel_values`,`image_grid_thw`]},pA=class extends fA{image_grid_thw_name=`grid_thw`;_get_text_only_rope_index(e,t){if(t){let{data:e,dims:n}=IO(t),r=BigInt64Array.from({length:3*e.length},(t,n)=>e[n%e.length]),i=Array.from({length:n[0]},(t,r)=>_C(e.subarray(n[1]*r,n[1]*(r+1)))[0]+1n+BigInt(n[1]));return[new L(`int64`,r,[3,...n]),new L(`int64`,i,[i.length,1])]}{let[t,n]=e.dims;return[new L(`int64`,BigInt64Array.from({length:3*t*n},(e,r)=>BigInt(Math.floor(r%n/t))),[3,...e.dims]),jw([t,1])]}}_reorder_and_write_positions(e,t,n,r){let i=e.reduce((e,t)=>e+t.length,0),a=Array(i),o=0;for(let t=0;t<3;++t)for(let n of e){let e=n.length/3;for(let r=t*e;r<(t+1)*e;++r)a[o++]=n[r]}let s=0;for(let e=0;e(t==s&&e.push(n),e),[]).map(e=>c[e+1]),u=l.filter(e=>e==a).length,d=l.filter(e=>e==o).length,f=[],p=0,m=u,h=d;for(let e=0;et>p&&e==a),s=c.findIndex((e,t)=>t>p&&e==o),l=m>0&&e!==-1?e:c.length+1,u=h>0&&s!==-1?s:c.length+1,d,g,_,v;l0?_C(f.at(-1))[0]+1:0;f.push(Array.from({length:3*S},(e,t)=>C+t%S));let w=S+C,T=y*b*x,E=Array.from({length:T},(e,t)=>w+Math.floor(t/(b*x))),D=Array.from({length:T},(e,t)=>w+Math.floor(t/x)%b),O=Array.from({length:T},(e,t)=>w+t%x);f.push([E,D,O].flat()),p=d+T}if(p0?_C(f.at(-1))[0]+1:0,t=c.length-p;f.push(Array.from({length:3*t},(n,r)=>e+r%t))}return f}get_rope_index(e,t,n,r){let{vision_config:i}=this.config,a=i.spatial_merge_size??2;if(t||n){let i=e.tolist();r||=Aw(e);let o=r.tolist(),s=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),c=t?t.tolist():[],l=n?n.tolist():[],u={image_index:0,video_index:0},d=[];for(let e=0;eo[e][n]==1),n=this._get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:c,video_grid_thw_list:l,spatial_merge_size:a,state:u}),r=this._reorder_and_write_positions(n,o[e],s,e);d.push(_C(r)[0]+1-i[e].length)}return[new L(`int64`,s.flat(1/0),[3,e.dims[0],e.dims[1]]),new L(`int64`,d,[d.length,1])]}return this._get_text_only_rope_index(e,r)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await aO(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return VO({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,n){if(!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes(`position_ids`))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(en+e);t.position_ids=xw([r,r,r],0)}}return t}},mA=class extends pA{},hA=class extends pA{image_grid_thw_name=`image_grid_thw`},gA=class extends mA{image_grid_thw_name=`image_grid_thw`},Rge=class extends hA{get_vision_position_ids(e,t,n,r){let i=Math.floor(t[0]/n),a=Math.floor(t[1]/r),o=Math.floor(t[2]/r),s=a*o*i,c=Array.from({length:s},()=>e),l=Array.from({length:s},(t,n)=>e+Math.floor(n/(o*i))),u=Array.from({length:s},(t,n)=>e+n%o);return[...c,...l,...u]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a}=this.config,o=[],s=0,c=+(e[0]==a);for(let t=1;t<=e.length;++t){let n=tl+n%e)),l+=e}else{let e=t[i.image_index++].map(Number),n=e[0];u.push(this.get_vision_position_ids(l,e,n,r)),l+=Math.max(e[1],e[2])/r}return u}},_A=class extends z{},zge=class extends _A{},Bge=class extends _A{},vA=class extends z{},Vge=class extends vA{},Hge=class extends vA{},yA=class extends z{},Uge=class extends yA{},Wge=class extends yA{},bA=class extends z{},Gge=class extends bA{},Kge=class extends bA{},xA=class extends z{},qge=class extends xA{},Jge=class extends xA{},SA=class extends z{},Yge=class extends SA{},Xge=class extends SA{},CA=class extends z{},Zge=class extends CA{},Qge=class extends CA{},wA=class extends z{},$ge=class extends wA{},e_e=class extends wA{},TA=class extends z{},t_e=class extends TA{},n_e=class extends TA{},EA=class extends z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`audio_values`,`past_key_values`]},DA=class extends EA{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return HO({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:n})}},r_e=class extends DA{forward_params=[`input_ids`,`attention_mask`,`input_features`,`past_key_values`]},OA=class extends z{},i_e=class extends OA{},kA=class extends z{},a_e=class extends kA{},AA=class extends z{},o_e=class extends AA{},s_e=class extends AA{},jA=class extends z{},c_e=class extends jA{},l_e=class extends jA{async _call(e){return new sO(await super._call(e))}},MA=class extends z{},u_e=class extends MA{},d_e=class extends MA{async _call(e){return new dO(await super._call(e))}},f_e=class extends MA{async _call(e){return new sO(await super._call(e))}},p_e=class extends MA{async _call(e){return new cO(await super._call(e))}},m_e=class extends z{},h_e=class extends MA{},g_e=class extends MA{async _call(e){return new dO(await super._call(e))}},__e=class extends MA{async _call(e){return new sO(await super._call(e))}},NA=class extends z{},v_e=class extends NA{},y_e=class extends NA{},PA=class extends iA{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`position_ids`,`past_key_values`]},FA=class extends z{},b_e=class extends FA{},x_e=class extends FA{async _call(e){return new sO(await super._call(e))}},IA=class extends z{},S_e=class extends IA{},C_e=class extends IA{},LA=class extends z{},w_e=class extends LA{async forward(e){let t=!e.input_ids,n=!e.pixel_values;if(t&&n)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=kw([e.pixel_values.dims[0],1])),n){let{image_size:t}=this.config.vision_config;e.pixel_values=Dw([0,3,t,t],0)}let{text_embeddings:r,image_embeddings:i,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),s={};return t||(s.text_embeddings=r,s.l2norm_text_embeddings=a),n||(s.image_embeddings=i,s.l2norm_image_embeddings=o),s}},RA=class extends LA{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},T_e=class extends LA{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},zA=class extends z{},E_e=class extends zA{},D_e=class extends zA{},O_e=class extends iA{},BA=class extends z{},k_e=class extends BA{},A_e=class extends BA{},j_e=class extends iA{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`spatial_shapes`,`position_ids`,`past_key_values`]},VA=class extends z{},M_e=class extends VA{},N_e=class extends VA{},HA=class extends z{},P_e=class extends HA{},UA=class extends z{},F_e=class extends UA{},I_e=class extends UA{},WA=class extends z{},L_e=class extends WA{},R_e=class extends WA{},GA=class extends z{},z_e=class extends GA{},B_e=class extends GA{},KA=class extends z{},V_e=class extends KA{},H_e=class extends KA{},qA=class extends z{},U_e=class extends qA{},W_e=class extends qA{},G_e=class extends qA{async _call(e){return new sO(await super._call(e))}},K_e=class extends qA{},JA=class extends z{},q_e=class extends JA{},YA=class extends z{},J_e=class extends YA{},XA=class extends oO{constructor({char_logits:e,bpe_logits:t,wp_logits:n}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=n}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},ZA=class extends z{},Y_e=class extends ZA{async _call(e){return new XA(await super._call(e))}},QA=class extends oO{constructor({audio_codes:e}){super(),this.audio_codes=e}},$A=class extends oO{constructor({audio_values:e}){super(),this.audio_values=e}},ej=class extends z{main_input_name=`input_values`;forward_params=[`input_values`]},X_e=class extends ej{async encode(e){return new QA(await aO(this.sessions.encoder_model,e))}async decode(e){return new $A(await aO(this.sessions.decoder_model,e))}},tj=class extends ej{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},nj=class extends ej{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},rj=class extends z{},Z_e=class extends rj{},Q_e=class extends rj{},ij=class extends z{},$_e=class extends ij{},eve=class extends ij{},aj=class extends z{},tve=class extends aj{},nve=class extends aj{async _call(e){return new lO(await super._call(e))}},rve=class extends aj{async _call(e){return new sO(await super._call(e))}},ive=class extends aj{async _call(e){return new uO(await super._call(e))}},oj=class extends z{},ave=class extends oj{},ove=class extends oj{},sj=class extends z{},sve=class extends sj{},cve=class extends sj{async _call(e){return new sO(await super._call(e))}},lve=class extends sj{},cj=class extends z{},uve=class extends cj{},dve=class extends cj{async _call(e){return new sO(await super._call(e))}},fve=class extends cj{},lj=class extends z{},pve=class extends lj{},mve=class extends lj{async _call(e){return new sO(await super._call(e))}},hve=class extends lj{},uj=class extends z{},gve=class extends uj{},_ve=class extends uj{async _call(e){return new sO(await super._call(e))}},vve=class extends uj{},dj=class extends z{},yve=class extends dj{},bve=class extends dj{async _call(e){return new sO(await super._call(e))}},fj=class extends z{},xve=class extends fj{},Sve=class extends fj{async _call(e){return new sO(await super._call(e))}},pj=class extends z{},Cve=class extends pj{},wve=class extends pj{async _call(e){return new lO(await super._call(e))}},Tve=class extends pj{async _call(e){return new sO(await super._call(e))}},Eve=class extends pj{async _call(e){return new cO(await super._call(e))}},mj=class extends z{},Dve=class extends mj{},Ove=class extends mj{},hj=class extends z{requires_attention_mask=!1;main_input_name=`input_values`;forward_params=[`input_values`,`decoder_input_ids`,`past_key_values`]},kve=class extends hj{},Ave=class extends hj{},gj=class extends z{},jve=class extends gj{},Mve=class extends gj{async _call(e){return new lO(await super._call(e))}},Nve=class extends gj{async _call(e){return new sO(await super._call(e))}},Pve=class extends gj{async _call(e){return new cO(await super._call(e))}},Fve=class extends gj{async _call(e){return new uO(await super._call(e))}},_j=class extends z{},Ive=class extends _j{},Lve=class extends _j{},vj=class extends z{},Rve=class extends vj{},zve=class extends vj{},yj=class extends z{},Bve=class extends yj{forward_params=[`input_ids`,`pixel_values`,`images_seq_mask`,`images_emb_mask`,`attention_mask`,`position_ids`,`past_key_values`];constructor(...e){super(...e),this._generation_mode=`text`}async forward(e){let t=this._generation_mode??`text`,n;if(t===`text`||!e.past_key_values){let t=this.sessions.prepare_inputs_embeds;n=await aO(t,Hb(e,t.inputNames))}else{let t=this.sessions.gen_img_embeds;n=await aO(t,Hb({image_ids:e.input_ids},t.inputNames))}let r={...e,...n},i=await PO(this,r),a=this.sessions[t===`text`?`lm_head`:`gen_head`];if(!a)throw Error(`Unable to find "${a}" generation head`);let o=await aO(a,Hb(i,a.inputNames));return{...n,...i,...o}}prepare_inputs_for_generation(e,t,n){let r=!!t.past_key_values;return n.guidance_scale!==null&&n.guidance_scale>1&&(r?t.input_ids=bw([t.input_ids,t.input_ids],0):(t.input_ids=bw([t.input_ids,Ow(t.input_ids,BigInt(n.pad_token_id))],0),t.attention_mask=bw([t.attention_mask,Ow(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=Dw([0,0,3,384,384],1)),r&&(t.images_seq_mask=new L(`bool`,[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new L(`bool`,[].fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode=`text`,super.generate(e)}async generate_images(e){this._generation_mode=`image`;let t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),r=this.sessions.image_decode,{decoded_image:i}=await aO(r,{generated_tokens:n}),a=i.add_(1).mul_(255/2).clamp_(0,255).to(`uint8`),o=[];for(let e of a){let t=$E.fromTensor(e);o.push(t)}return o}},bj=class extends z{},Vve=class extends bj{},Hve=class extends bj{},xj=class extends z{forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`];_apply_and_filter_by_delay_pattern_mask(e){let[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r,a=0;for(let t=0;t0&&o<=i&&(e.data[a++]=e.data[t])}let o=Math.floor(t/r),s=a/(o*r);return new L(e.type,e.data.slice(0,a),[o,r,s])}prepare_inputs_for_generation(e,t,n){let r=BigInt(this.config.decoder.pad_token_id),i=structuredClone(e);for(let e=0;e=t&&(i[e][t]=r);return n.guidance_scale!==null&&n.guidance_scale>1&&(i=i.concat(i)),RO(this,i,t,n)}async generate(e){let t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await aO(this.sessions.encodec_decode,{audio_codes:n});return r}},Sj=class extends z{},Uve=class extends Sj{},Wve=class extends Sj{},Cj=class extends z{},Gve=class extends Cj{},Kve=class extends Cj{},wj=class extends z{},qve=class extends wj{},Jve=class extends wj{async _call(e){return new lO(await super._call(e))}},Yve=class extends wj{async _call(e){return new sO(await super._call(e))}},Xve=class extends wj{async _call(e){return new cO(await super._call(e))}},Zve=class extends wj{async _call(e){return new uO(await super._call(e))}},Tj=class extends z{},Qve=class extends Tj{},Ej=class extends z{},$ve=class extends Ej{},eye=class extends Ej{},Dj=class extends z{},tye=class extends Dj{},nye=class extends Dj{},Oj=class extends z{},rye=class extends Oj{},iye=class extends Oj{},kj=class extends z{},aye=class extends kj{},oye=class extends kj{},Aj=class extends z{},sye=class extends Aj{},cye=class extends Aj{async _call(e){return new sO(await super._call(e))}},jj=class extends z{},lye=class extends jj{},uye=class extends jj{},Mj=class extends z{},dye=class extends Mj{},fye=class extends Mj{},Nj=class extends z{},pye=class extends Nj{},mye=class extends Nj{},Pj=class extends z{},hye=class extends Pj{},gye=class extends Pj{},_ye=class extends iA{},Fj=class extends z{},vye=class extends Fj{async _call(e){return new dO(await super._call(e))}},Ij=class extends z{},yye=class extends Ij{},bye=class extends Ij{},Lj=class extends z{},xye=class extends Lj{},Sye=class extends Lj{},Rj=class extends z{},Cye=class extends Rj{},wye=class extends Rj{},zj=class extends z{},Tye=class extends zj{},Eye=class extends zj{},Bj=class extends z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`pixel_values`,`image_sizes`,`past_key_values`]},Vj=class extends Bj{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,image_sizes:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,...l}){if(!a){let t;if(n&&e.dims[1]!==1){if(!r)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:t}=await aO(this.sessions.vision_encoder,{pixel_values:n,image_sizes:r}))}else{let e=this.config.normalized_config.hidden_size;t=new L(`float32`,[],[0,e])}({inputs_embeds:a}=await aO(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await PO(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:i,generation_config:s,logits_processor:c},!1)}},Hj=class extends z{},Dye=class extends Hj{},Oye=class extends Hj{async _call(e){return new sO(await super._call(e))}},Uj=class extends z{},kye=class extends Uj{},Aye=class extends Uj{async _call(e){return new cO(await super._call(e))}},Wj=class extends z{},jye=class extends Wj{},Mye=class extends Wj{},Gj=class extends z{},Nye=class extends Gj{},Pye=class extends Gj{},Kj=class extends z{},Fye=class extends Kj{},Iye=class extends Kj{},qj=class extends z{},Lye=class extends qj{},Rye=class extends qj{},Jj=class extends z{},zye=class extends Jj{},Bye=class extends Jj{},Yj=class extends hA{},Xj=class extends gA{},Vye=class extends Yj{},Hye=class extends Xj{},Zj=class extends Yj{},Qj=class extends Zj{},Uye=class extends Zj{},Wye=class extends Qj{},$j=class extends z{},Gye=class extends $j{},Kye=class extends $j{async _call(e){return new sO(await super._call(e))}},eM=class extends z{},qye=class extends eM{},Jye=class extends eM{async _call(e){return new tM(await super._call(e))}},tM=class extends xk{},nM=class extends z{},Yye=class extends nM{},Xye=class extends nM{async _call(e){return new lO(await super._call(e))}},Zye=class extends nM{async _call(e){return new sO(await super._call(e))}},Qye=class extends nM{async _call(e){return new cO(await super._call(e))}},$ye=class extends nM{async _call(e){return new uO(await super._call(e))}},rM=class extends z{},ebe=class extends rM{},tbe=class extends rM{async _call(e){return new lO(await super._call(e))}},nbe=class extends rM{async _call(e){return new sO(await super._call(e))}},rbe=class extends rM{async _call(e){return new cO(await super._call(e))}},ibe=class extends rM{async _call(e){return new uO(await super._call(e))}},iM=class extends z{},abe=class extends iM{},obe=class extends iM{async _call(e){return new aM(await super._call(e))}},aM=class extends xk{},oM=class extends oO{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},sM=class extends z{},sbe=class extends sM{async get_image_embeddings({pixel_values:e}){return await AO(this,{pixel_values:e})}async forward(e){e=!e.image_embeddings||!e.image_positional_embeddings?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_labels??=kw(e.input_points.dims.slice(0,-1));let t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await aO(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new oM(await super._call(e))}},cM=class extends oO{constructor({iou_scores:e,pred_masks:t,object_score_logits:n}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=n}},lM=class extends z{},uM=class extends lM{async get_image_embeddings({pixel_values:e}){return await AO(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(e=Array.from({length:t},(e,t)=>`image_embeddings.${t}`).some(t=>!e[t])?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let t=e.input_points.dims;e.input_labels??=kw(t.slice(0,-1)),e.input_boxes??=Dw([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=Dw([t[0],t[1],0],-1n),e.input_points=Dw([t[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder;return await aO(n,Hb(e,n.inputNames))}async _call(e){return new cM(await super._call(e))}},cbe=class extends uM{},lbe=class extends uM{},dM=class extends z{},ube=class extends dM{},dbe=class extends dM{},fbe=class extends dM{},fM=class extends z{},pbe=class extends fM{},mbe=class extends fM{},hbe=class extends fM{},pM=class extends z{},gbe=class extends pM{},mM=class extends pM{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},_be=class extends uk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},hM=class extends z{},vbe=class extends hM{},ybe=class extends hM{},bbe=class extends PA{},gM=class extends z{main_input_name=`input_values`;forward_params=[`input_values`]},xbe=class extends gM{async encode(e){return await aO(this.sessions.encoder_model,e)}async decode(e){return await aO(this.sessions.decoder_model,e)}},_M=class extends gM{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},vM=class extends gM{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},yM=class extends z{},Sbe=class extends yM{},Cbe=class extends yM{},bM=class extends z{},wbe=class extends bM{},Tbe=class extends bM{},Ebe=class extends bM{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){let o={input_ids:e},{encoder_outputs:s,encoder_attention_mask:c}=await AO(this,o),l=s.dims[1]/this.config.reduction_factor,u=Math.floor(l*i),d=Math.floor(l*r),f=this.config.num_mel_bins,p=[],m=null,h=null,g=0;for(;;){++g;let e=CO(!!h),r;r=h?h.output_sequence_out:new L(`float32`,new Float32Array(f),[1,1,f]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:c,speaker_embeddings:t,encoder_hidden_states:s};NO(this,i,m),h=await aO(this.sessions.decoder_model_merged,i),m=jO(h,m);let{prob:a,spectrum:o}=h;if(p.push(o),g>=d&&(Array.from(a.data).filter(e=>e>=n).length>0||g>=u))break}let _=bw(p),{waveform:v}=await aO(a.sessions.model,{spectrogram:_});return{spectrogram:_,waveform:v}}},Dbe=class extends z{main_input_name=`spectrogram`},xM=class extends z{},Obe=class extends xM{},kbe=class extends xM{async _call(e){return new lO(await super._call(e))}},Abe=class extends xM{async _call(e){return new sO(await super._call(e))}},jbe=class extends xM{async _call(e){return new uO(await super._call(e))}},SM=class extends z{},Mbe=class extends SM{},Nbe=class extends SM{},CM=class extends z{},Pbe=class extends CM{},Fbe=class extends CM{},wM=class extends z{},Ibe=class extends wM{},TM=class extends z{},EM=class extends TM{async generate_speech({input_ids:e,attention_mask:t,style:n,num_inference_steps:r=5,speed:i=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:s,latent_dim:c}=this.config,{last_hidden_state:l,durations:u}=await aO(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:n}),d=u.div(i).mul_(a),f=s*o,p=d.data,m=Int32Array.from(p,e=>Math.ceil(e/f)),h=Math.max(...m),g=e.dims[0],_=new BigInt64Array(g*h);for(let e=0;ee*t,1),r=sw[e.type];c[e.name]=new L(e.type,new r(n),t)}let f=sw[d],p=new L(d,new f(s*hN),[1,s,hN]),m=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!m)throw Error(`input_features must be iterable or async iterable`);return{encoder_session:i,enc_kv_cache:c,enc_padding_cache:p,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:m,text_hidden_size:n.hidden_size}}async function yN(e,t){let n=t.dims[2],r=Math.floor((gN+n-3)/2)+1,i=new L(`int64`,BigInt64Array.from({length:r},(t,n)=>BigInt(e.enc_past_seq_len+n)),[1,r]),a=e.enc_past_seq_len+r,o=kw([1,a]),{audio_embeds:s,present_padding_cache:c,...l}=await aO(e.encoder_session,{input_features:t,attention_mask:o,position_ids:i,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location===`gpu-buffer`&&e.enc_padding_cache.dispose(),e.enc_padding_cache=c;for(let t in l)if(t.startsWith(`present.`)){let n=t.replace(`present`,`past_key_values`),r=e.enc_kv_cache[n];r?.location===`gpu-buffer`&&r.dispose(),e.enc_kv_cache[n]=l[t]}return e.enc_past_seq_len=a,s}async function bN(e,t){for(;e.audio_embed_total_tokens0&&e.audio_embed_queue.length>0;){let t=e.audio_embed_queue[0],n=t.tokens-e.audio_queue_offset,o=Math.min(a,n),s=e.audio_queue_offset*e.text_hidden_size;for(let n=0;n=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=n-a}var SN=class extends gO{constructor(e){super(),this._s=e}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},CN=class extends z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`]},wN=class extends CN{async forward({input_ids:e,past_key_values:t,...n}){let r=e.dims[1],i=_N.get(this);i&&await bN(i,i.audio_consumed+r);let{inputs_embeds:a}=await aO(this.sessions.embed_tokens,{input_ids:e});i&&xN(i,a,r);let o={inputs_embeds:a,...n};NO(this,o,t);let s=this.sessions.decoder_model_merged;return await aO(s,Hb(o,s.inputNames))}async generate({input_features:e,stopping_criteria:t,...n}){if(!e)throw Error(`input_features (generator/iterable) must be provided`);let r=vN(this,e);_N.set(this,r);let i=new _O;i.push(new SN(r)),t&&i.extend(t);try{return await super.generate({...n,stopping_criteria:i})}finally{r.enc_kv_cache.dispose(),_N.delete(this)}}},TN=class extends z{},EN=class extends TN{},DN=class extends TN{async _call(e){return new dO(await super._call(e))}},ON=class extends TN{async _call(e){return new sO(await super._call(e))}},kN=class extends oO{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},AN=class extends z{},jN=class extends AN{},MN=class extends AN{async _call(e){return new dO(await super._call(e))}},NN=class extends AN{async _call(e){return new sO(await super._call(e))}},PN=class extends AN{async _call(e){return new kN(await super._call(e))}},FN=class extends AN{async _call(e){return new cO(await super._call(e))}},IN=class extends z{},LN=class extends IN{},RN=class extends hO{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},zN=class extends z{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`attention_mask`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},BN=class extends zN{},VN=class extends zN{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,RN)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],n=e.language,r=e.task;if(e.is_multilingual){n||=(Wb.warn(`No language specified - defaulting to English (en).`),`en`);let i=`<|${RT(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??`transcribe`])}else if(n||r)throw Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(Wb.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(e=>e!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);let a=i.decoder_input_ids instanceof L?Lw(i.decoder_input_ids):i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new pO,n.push(new Ipe(t,a))),t.begin_suppress_tokens&&(n??=new pO,n.push(new mO(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task===`translate`&&Wb.warn(`Token-level timestamps may not be reliable for task 'translate'.`),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!i.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:a,kwargs:i});let o=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:r,kwargs:i}){let a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,s=t.return_token_timestamps,c=e,l=c.dims[2],u=2*this.config.max_source_positions,d=0,f=[],p=[];for(;de+n)}if(v.length>0&&v.at(-1)===o&&v.pop(),v.length===0)break;let b=v.map(e=>e>=a),x=v.length>=2&&b[v.length-1]&&!b[v.length-2],S=[];for(let e=0;e0){if(x)C=e-d;else{let e=S.at(-1);C=(v[e-1]-a)*2,w=e}}else C=e-d;let T=Math.floor(d/2),E=a+1500;for(let e=0;e=a&&(v[e]=Math.min(v[e]+T,E));f.push(...v.slice(0,w)),y&&p.push(...y.slice(0,w)),d+=C}f.push(o);let m=[...r,...f];if(s){let e=new L(`int64`,m.map(BigInt),[1,m.length]),t=[...Array(r.length).fill(0),...p,0];return{sequences:e,token_timestamps:new L(`float32`,new Float32Array(t),[1,t.length])}}return new L(`int64`,m.map(BigInt),[1,m.length])}_extract_token_timestamps(e,t,n=null,r=.02,i=0){if(!e.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");n??Wb.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(Wb.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let o=e.cross_attentions,s=Array.from({length:this.config.decoder_layers},(e,t)=>bw(o.map(e=>e[t]),2)),c=xw(t.map(([e,t])=>{if(e>=s.length)throw Error(`Layer index ${e} is out of bounds for cross attentions (length ${s.length}).`);return n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t)})).transpose(1,0,2,3),[l,u]=Cw(c,-2,0,!0),d=c.clone();for(let e=0;e0?d.slice(null,null,[i,d.dims[2]],null):d,1)],p=e.sequences.dims,m=new L(`float32`,new Float32Array(p[0]*p[1]),p);for(let e=0;et[n+1]-t[n])).map(e=>!!e),o=[];for(let e=0;e0&&s.push(o.at(-1)),m[e].data.set(s)}return m}},HN=class extends VN{},UN=class extends z{},WN=class extends UN{},GN=class extends UN{async _call(e){return new lO(await super._call(e))}},KN=class extends UN{async _call(e){return new sO(await super._call(e))}},qN=class extends UN{async _call(e){return new cO(await super._call(e))}},JN=class extends UN{async _call(e){return new uO(await super._call(e))}},YN=class extends z{},XN=class extends YN{},ZN=class extends YN{async _call(e){return new lO(await super._call(e))}},QN=class extends YN{async _call(e){return new sO(await super._call(e))}},$N=class extends YN{async _call(e){return new cO(await super._call(e))}},eP=class extends YN{async _call(e){return new uO(await super._call(e))}},tP=class extends z{},nP=class extends tP{},rP=class extends tP{async _call(e){return new iP(await super._call(e))}},iP=class extends oO{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},aP=class extends z{},oP=class extends aP{},sP=class extends aP{},cP=new Map([[`bert`,`BertModel`],[`eurobert`,`EuroBertModel`],[`neobert`,`NeoBertModel`],[`modernbert`,`ModernBertModel`],[`nomic_bert`,`NomicBertModel`],[`roformer`,`RoFormerModel`],[`electra`,`ElectraModel`],[`esm`,`EsmModel`],[`convbert`,`ConvBertModel`],[`camembert`,`CamembertModel`],[`deberta`,`DebertaModel`],[`deberta-v2`,`DebertaV2Model`],[`mpnet`,`MPNetModel`],[`albert`,`AlbertModel`],[`distilbert`,`DistilBertModel`],[`roberta`,`RobertaModel`],[`xlm`,`XLMModel`],[`xlm-roberta`,`XLMRobertaModel`],[`clap`,`ClapModel`],[`clip`,`CLIPModel`],[`clipseg`,`CLIPSegModel`],[`chinese_clip`,`ChineseCLIPModel`],[`siglip`,`SiglipModel`],[`jina_clip`,`JinaCLIPModel`],[`mobilebert`,`MobileBertModel`],[`squeezebert`,`SqueezeBertModel`],[`wav2vec2`,`Wav2Vec2Model`],[`wav2vec2-bert`,`Wav2Vec2BertModel`],[`unispeech`,`UniSpeechModel`],[`unispeech-sat`,`UniSpeechSatModel`],[`hubert`,`HubertModel`],[`wavlm`,`WavLMModel`],[`audio-spectrogram-transformer`,`ASTModel`],[`vits`,`VitsModel`],[`pyannote`,`PyAnnoteModel`],[`wespeaker-resnet`,`WeSpeakerResNetModel`],[`detr`,`DetrModel`],[`rt_detr`,`RTDetrModel`],[`rt_detr_v2`,`RTDetrV2Model`],[`rf_detr`,`RFDetrModel`],[`d_fine`,`DFineModel`],[`table-transformer`,`TableTransformerModel`],[`vit`,`ViTModel`],[`ijepa`,`IJepaModel`],[`pvt`,`PvtModel`],[`vit_msn`,`ViTMSNModel`],[`vit_mae`,`ViTMAEModel`],[`groupvit`,`GroupViTModel`],[`fastvit`,`FastViTModel`],[`mobilevit`,`MobileViTModel`],[`mobilevitv2`,`MobileViTV2Model`],[`owlvit`,`OwlViTModel`],[`owlv2`,`Owlv2Model`],[`beit`,`BeitModel`],[`deit`,`DeiTModel`],[`hiera`,`HieraModel`],[`convnext`,`ConvNextModel`],[`convnextv2`,`ConvNextV2Model`],[`dinov2`,`Dinov2Model`],[`dinov2_with_registers`,`Dinov2WithRegistersModel`],[`dinov3_vit`,`DINOv3ViTModel`],[`dinov3_convnext`,`DINOv3ConvNextModel`],[`resnet`,`ResNetModel`],[`swin`,`SwinModel`],[`swin2sr`,`Swin2SRModel`],[`donut-swin`,`DonutSwinModel`],[`yolos`,`YolosModel`],[`dpt`,`DPTModel`],[`glpn`,`GLPNModel`],[`hifigan`,`SpeechT5HifiGan`],[`efficientnet`,`EfficientNetModel`],[`decision_transformer`,`DecisionTransformerModel`],[`patchtst`,`PatchTSTModel`],[`patchtsmixer`,`PatchTSMixerModel`],[`mobilenet_v1`,`MobileNetV1Model`],[`mobilenet_v2`,`MobileNetV2Model`],[`mobilenet_v3`,`MobileNetV3Model`],[`mobilenet_v4`,`MobileNetV4Model`],[`maskformer`,`MaskFormerModel`],[`mgp-str`,`MgpstrForSceneTextRecognition`],[`style_text_to_speech_2`,`StyleTextToSpeech2Model`],[`openai_privacy_filter`,`OpenAIPrivacyFilterModel`]]),lP=new Map([[`t5`,`T5Model`],[`longt5`,`LongT5Model`],[`mt5`,`MT5Model`],[`bart`,`BartModel`],[`mbart`,`MBartModel`],[`marian`,`MarianModel`],[`whisper`,`WhisperModel`],[`cohere_asr`,`CohereAsrModel`],[`m2m_100`,`M2M100Model`],[`blenderbot`,`BlenderbotModel`],[`blenderbot-small`,`BlenderbotSmallModel`]]),uP=new Map([[`mimi`,`MimiModel`],[`dac`,`DacModel`],[`snac`,`SnacModel`]]),dP=new Map([[`bloom`,`BloomModel`],[`jais`,`JAISModel`],[`gpt2`,`GPT2Model`],[`gpt_oss`,`GptOssModel`],[`gptj`,`GPTJModel`],[`gpt_bigcode`,`GPTBigCodeModel`],[`gpt_neo`,`GPTNeoModel`],[`gpt_neox`,`GPTNeoXModel`],[`codegen`,`CodeGenModel`],[`llama`,`LlamaModel`],[`apertus`,`ApertusModel`],[`nanochat`,`NanoChatModel`],[`arcee`,`ArceeModel`],[`afmoe`,`AfmoeModel`],[`lfm2`,`Lfm2Model`],[`lfm2_moe`,`Lfm2MoeModel`],[`smollm3`,`SmolLM3Model`],[`exaone`,`ExaoneModel`],[`olmo`,`OlmoModel`],[`olmo2`,`Olmo2Model`],[`olmo3`,`Olmo3Model`],[`olmo_hybrid`,`OlmoHybridModel`],[`mobilellm`,`MobileLLMModel`],[`granite`,`GraniteModel`],[`granitemoehybrid`,`GraniteMoeHybridModel`],[`cohere`,`CohereModel`],[`cohere2`,`Cohere2Model`],[`gemma`,`GemmaModel`],[`gemma2`,`Gemma2Model`],[`vaultgemma`,`VaultGemmaModel`],[`gemma3_text`,`Gemma3Model`],[`helium`,`HeliumModel`],[`glm`,`GlmModel`],[`glm_moe_dsa`,`GlmMoeDsaModel`],[`openelm`,`OpenELMModel`],[`qwen2`,`Qwen2Model`],[`qwen2_moe`,`Qwen2MoeModel`],[`qwen3`,`Qwen3Model`],[`qwen3_moe`,`Qwen3MoeModel`],[`qwen3_next`,`Qwen3NextModel`],[`phi`,`PhiModel`],[`phi3`,`Phi3Model`],[`mpt`,`MptModel`],[`opt`,`OPTModel`],[`mistral`,`MistralModel`],[`mistral4`,`Mistral4Model`],[`ministral`,`MinistralModel`],[`ministral3`,`Ministral3Model`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2Model`],[`deepseek_v3`,`DeepseekV3Model`],[`falcon`,`FalconModel`],[`falcon_h1`,`FalconH1Model`],[`nemotron_h`,`NemotronHModel`],[`solar_open`,`SolarOpenModel`],[`stablelm`,`StableLmModel`],[`modernbert-decoder`,`ModernBertDecoderModel`],[`hunyuan_v1_dense`,`HunYuanDenseV1Model`],[`youtu`,`YoutuModel`]]),fP=new Map([[`speecht5`,`SpeechT5ForSpeechToText`],[`whisper`,`WhisperForConditionalGeneration`],[`lite-whisper`,`LiteWhisperForConditionalGeneration`],[`moonshine`,`MoonshineForConditionalGeneration`],[`cohere_asr`,`CohereAsrForConditionalGeneration`]]),pP=new Map([[`speecht5`,`SpeechT5ForTextToSpeech`]]),mP=new Map([[`vits`,`VitsModel`],[`musicgen`,`MusicgenForConditionalGeneration`],[`supertonic`,`SupertonicForConditionalGeneration`]]),hP=new Map([[`bert`,`BertForSequenceClassification`],[`eurobert`,`EuroBertForSequenceClassification`],[`neobert`,`NeoBertForSequenceClassification`],[`modernbert`,`ModernBertForSequenceClassification`],[`roformer`,`RoFormerForSequenceClassification`],[`electra`,`ElectraForSequenceClassification`],[`esm`,`EsmForSequenceClassification`],[`convbert`,`ConvBertForSequenceClassification`],[`camembert`,`CamembertForSequenceClassification`],[`deberta`,`DebertaForSequenceClassification`],[`deberta-v2`,`DebertaV2ForSequenceClassification`],[`mpnet`,`MPNetForSequenceClassification`],[`albert`,`AlbertForSequenceClassification`],[`distilbert`,`DistilBertForSequenceClassification`],[`roberta`,`RobertaForSequenceClassification`],[`xlm`,`XLMForSequenceClassification`],[`xlm-roberta`,`XLMRobertaForSequenceClassification`],[`bart`,`BartForSequenceClassification`],[`mbart`,`MBartForSequenceClassification`],[`mobilebert`,`MobileBertForSequenceClassification`],[`squeezebert`,`SqueezeBertForSequenceClassification`]]),gP=new Map([[`bert`,`BertForTokenClassification`],[`eurobert`,`EuroBertForTokenClassification`],[`neobert`,`NeoBertForTokenClassification`],[`modernbert`,`ModernBertForTokenClassification`],[`roformer`,`RoFormerForTokenClassification`],[`electra`,`ElectraForTokenClassification`],[`esm`,`EsmForTokenClassification`],[`convbert`,`ConvBertForTokenClassification`],[`camembert`,`CamembertForTokenClassification`],[`deberta`,`DebertaForTokenClassification`],[`deberta-v2`,`DebertaV2ForTokenClassification`],[`mpnet`,`MPNetForTokenClassification`],[`distilbert`,`DistilBertForTokenClassification`],[`roberta`,`RobertaForTokenClassification`],[`xlm`,`XLMForTokenClassification`],[`xlm-roberta`,`XLMRobertaForTokenClassification`],[`openai_privacy_filter`,`OpenAIPrivacyFilterForTokenClassification`]]),_P=new Map([[`t5`,`T5ForConditionalGeneration`],[`longt5`,`LongT5ForConditionalGeneration`],[`mt5`,`MT5ForConditionalGeneration`],[`bart`,`BartForConditionalGeneration`],[`mbart`,`MBartForConditionalGeneration`],[`marian`,`MarianMTModel`],[`m2m_100`,`M2M100ForConditionalGeneration`],[`blenderbot`,`BlenderbotForConditionalGeneration`],[`blenderbot-small`,`BlenderbotSmallForConditionalGeneration`]]),vP=new Map([[`bloom`,`BloomForCausalLM`],[`gpt2`,`GPT2LMHeadModel`],[`gpt_oss`,`GptOssForCausalLM`],[`jais`,`JAISLMHeadModel`],[`gptj`,`GPTJForCausalLM`],[`gpt_bigcode`,`GPTBigCodeForCausalLM`],[`gpt_neo`,`GPTNeoForCausalLM`],[`gpt_neox`,`GPTNeoXForCausalLM`],[`codegen`,`CodeGenForCausalLM`],[`llama`,`LlamaForCausalLM`],[`nanochat`,`NanoChatForCausalLM`],[`apertus`,`ApertusForCausalLM`],[`llama4_text`,`Llama4ForCausalLM`],[`arcee`,`ArceeForCausalLM`],[`afmoe`,`AfmoeForCausalLM`],[`lfm2`,`Lfm2ForCausalLM`],[`lfm2_moe`,`Lfm2MoeForCausalLM`],[`smollm3`,`SmolLM3ForCausalLM`],[`exaone`,`ExaoneForCausalLM`],[`olmo`,`OlmoForCausalLM`],[`olmo2`,`Olmo2ForCausalLM`],[`olmo3`,`Olmo3ForCausalLM`],[`olmo_hybrid`,`OlmoHybridForCausalLM`],[`mobilellm`,`MobileLLMForCausalLM`],[`granite`,`GraniteForCausalLM`],[`granitemoehybrid`,`GraniteMoeHybridForCausalLM`],[`cohere`,`CohereForCausalLM`],[`cohere2`,`Cohere2ForCausalLM`],[`gemma`,`GemmaForCausalLM`],[`gemma2`,`Gemma2ForCausalLM`],[`vaultgemma`,`VaultGemmaForCausalLM`],[`gemma3_text`,`Gemma3ForCausalLM`],[`gemma3`,`Gemma3ForCausalLM`],[`helium`,`HeliumForCausalLM`],[`glm`,`GlmForCausalLM`],[`glm_moe_dsa`,`GlmMoeDsaForCausalLM`],[`openelm`,`OpenELMForCausalLM`],[`qwen2`,`Qwen2ForCausalLM`],[`qwen2_moe`,`Qwen2MoeForCausalLM`],[`qwen3`,`Qwen3ForCausalLM`],[`qwen3_moe`,`Qwen3MoeForCausalLM`],[`qwen3_next`,`Qwen3NextForCausalLM`],[`qwen2_vl`,`Qwen2VLForCausalLM`],[`qwen2_5_vl`,`Qwen2_5_VLForCausalLM`],[`qwen3_vl`,`Qwen3VLForCausalLM`],[`qwen3_vl_moe`,`Qwen3VLMoeForCausalLM`],[`qwen3_5`,`Qwen3_5ForCausalLM`],[`qwen3_5_text`,`Qwen3_5ForCausalLM`],[`qwen3_5_moe`,`Qwen3_5MoeForCausalLM`],[`gemma3n`,`Gemma3nForCausalLM`],[`gemma4`,`Gemma4ForCausalLM`],[`phi`,`PhiForCausalLM`],[`phi3`,`Phi3ForCausalLM`],[`mpt`,`MptForCausalLM`],[`opt`,`OPTForCausalLM`],[`mbart`,`MBartForCausalLM`],[`mistral`,`MistralForCausalLM`],[`mistral4`,`Mistral4ForCausalLM`],[`ministral`,`MinistralForCausalLM`],[`ministral3`,`Ministral3ForCausalLM`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2ForCausalLM`],[`deepseek_v3`,`DeepseekV3ForCausalLM`],[`falcon`,`FalconForCausalLM`],[`falcon_h1`,`FalconH1ForCausalLM`],[`nemotron_h`,`NemotronHForCausalLM`],[`trocr`,`TrOCRForCausalLM`],[`solar_open`,`SolarOpenForCausalLM`],[`stablelm`,`StableLmForCausalLM`],[`modernbert-decoder`,`ModernBertDecoderForCausalLM`],[`hunyuan_v1_dense`,`HunYuanDenseV1ForCausalLM`],[`youtu`,`YoutuForCausalLM`],[`phi3_v`,`Phi3VForCausalLM`]]),yP=new Map([[`multi_modality`,`MultiModalityCausalLM`]]),bP=new Map([[`bert`,`BertForMaskedLM`],[`eurobert`,`EuroBertForMaskedLM`],[`neobert`,`NeoBertForMaskedLM`],[`modernbert`,`ModernBertForMaskedLM`],[`roformer`,`RoFormerForMaskedLM`],[`electra`,`ElectraForMaskedLM`],[`esm`,`EsmForMaskedLM`],[`convbert`,`ConvBertForMaskedLM`],[`camembert`,`CamembertForMaskedLM`],[`deberta`,`DebertaForMaskedLM`],[`deberta-v2`,`DebertaV2ForMaskedLM`],[`mpnet`,`MPNetForMaskedLM`],[`albert`,`AlbertForMaskedLM`],[`distilbert`,`DistilBertForMaskedLM`],[`roberta`,`RobertaForMaskedLM`],[`xlm`,`XLMWithLMHeadModel`],[`xlm-roberta`,`XLMRobertaForMaskedLM`],[`mobilebert`,`MobileBertForMaskedLM`],[`squeezebert`,`SqueezeBertForMaskedLM`]]),xP=new Map([[`bert`,`BertForQuestionAnswering`],[`neobert`,`NeoBertForQuestionAnswering`],[`roformer`,`RoFormerForQuestionAnswering`],[`electra`,`ElectraForQuestionAnswering`],[`convbert`,`ConvBertForQuestionAnswering`],[`camembert`,`CamembertForQuestionAnswering`],[`deberta`,`DebertaForQuestionAnswering`],[`deberta-v2`,`DebertaV2ForQuestionAnswering`],[`mpnet`,`MPNetForQuestionAnswering`],[`albert`,`AlbertForQuestionAnswering`],[`distilbert`,`DistilBertForQuestionAnswering`],[`roberta`,`RobertaForQuestionAnswering`],[`xlm`,`XLMForQuestionAnswering`],[`xlm-roberta`,`XLMRobertaForQuestionAnswering`],[`mobilebert`,`MobileBertForQuestionAnswering`],[`squeezebert`,`SqueezeBertForQuestionAnswering`]]),SP=new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`]]),CP=new Map([[`llava`,`LlavaForConditionalGeneration`],[`llava_onevision`,`LlavaOnevisionForConditionalGeneration`],[`moondream1`,`Moondream1ForConditionalGeneration`],[`florence2`,`Florence2ForConditionalGeneration`],[`qwen2_vl`,`Qwen2VLForConditionalGeneration`],[`qwen2_5_vl`,`Qwen2_5_VLForConditionalGeneration`],[`qwen3_vl`,`Qwen3VLForConditionalGeneration`],[`qwen3_vl_moe`,`Qwen3VLMoeForConditionalGeneration`],[`qwen3_5`,`Qwen3_5ForConditionalGeneration`],[`qwen3_5_moe`,`Qwen3_5MoeForConditionalGeneration`],[`lfm2_vl`,`Lfm2VlForConditionalGeneration`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`],[`paligemma`,`PaliGemmaForConditionalGeneration`],[`llava_qwen2`,`LlavaQwen2ForCausalLM`],[`gemma3`,`Gemma3ForConditionalGeneration`],[`gemma3n`,`Gemma3nForConditionalGeneration`],[`gemma4`,`Gemma4ForConditionalGeneration`],[`mistral3`,`Mistral3ForConditionalGeneration`],[`lighton_ocr`,`LightOnOcrForConditionalGeneration`],[`glm_ocr`,`GlmOcrForConditionalGeneration`]]),wP=new Map([[`granite_speech`,`GraniteSpeechForConditionalGeneration`],[`ultravox`,`UltravoxModel`],[`voxtral`,`VoxtralForConditionalGeneration`],[`voxtral_realtime`,`VoxtralRealtimeForConditionalGeneration`]]),TP=new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`]]),EP=new Map([[`vit`,`ViTForImageClassification`],[`ijepa`,`IJepaForImageClassification`],[`pvt`,`PvtForImageClassification`],[`vit_msn`,`ViTMSNForImageClassification`],[`fastvit`,`FastViTForImageClassification`],[`mobilevit`,`MobileViTForImageClassification`],[`mobilevitv2`,`MobileViTV2ForImageClassification`],[`beit`,`BeitForImageClassification`],[`deit`,`DeiTForImageClassification`],[`hiera`,`HieraForImageClassification`],[`convnext`,`ConvNextForImageClassification`],[`convnextv2`,`ConvNextV2ForImageClassification`],[`dinov2`,`Dinov2ForImageClassification`],[`dinov2_with_registers`,`Dinov2WithRegistersForImageClassification`],[`resnet`,`ResNetForImageClassification`],[`swin`,`SwinForImageClassification`],[`segformer`,`SegformerForImageClassification`],[`efficientnet`,`EfficientNetForImageClassification`],[`mobilenet_v1`,`MobileNetV1ForImageClassification`],[`mobilenet_v2`,`MobileNetV2ForImageClassification`],[`mobilenet_v3`,`MobileNetV3ForImageClassification`],[`mobilenet_v4`,`MobileNetV4ForImageClassification`]]),DP=new Map([[`detr`,`DetrForObjectDetection`],[`rt_detr`,`RTDetrForObjectDetection`],[`rt_detr_v2`,`RTDetrV2ForObjectDetection`],[`rf_detr`,`RFDetrForObjectDetection`],[`d_fine`,`DFineForObjectDetection`],[`table-transformer`,`TableTransformerForObjectDetection`],[`yolos`,`YolosForObjectDetection`]]),OP=new Map([[`owlvit`,`OwlViTForObjectDetection`],[`owlv2`,`Owlv2ForObjectDetection`],[`grounding-dino`,`GroundingDinoForObjectDetection`]]),kP=new Map([[`detr`,`DetrForSegmentation`],[`clipseg`,`CLIPSegForImageSegmentation`]]),AP=new Map([[`segformer`,`SegformerForSemanticSegmentation`],[`sapiens`,`SapiensForSemanticSegmentation`],[`swin`,`SwinForSemanticSegmentation`],[`mobilenet_v1`,`MobileNetV1ForSemanticSegmentation`],[`mobilenet_v2`,`MobileNetV2ForSemanticSegmentation`],[`mobilenet_v3`,`MobileNetV3ForSemanticSegmentation`],[`mobilenet_v4`,`MobileNetV4ForSemanticSegmentation`]]),jP=new Map([[`detr`,`DetrForSegmentation`],[`maskformer`,`MaskFormerForInstanceSegmentation`]]),MP=new Map([[`sam`,`SamModel`],[`sam2`,`Sam2Model`],[`edgetam`,`EdgeTamModel`],[`sam3_tracker`,`Sam3TrackerModel`]]),NP=new Map([[`wav2vec2`,`Wav2Vec2ForCTC`],[`wav2vec2-bert`,`Wav2Vec2BertForCTC`],[`unispeech`,`UniSpeechForCTC`],[`unispeech-sat`,`UniSpeechSatForCTC`],[`wavlm`,`WavLMForCTC`],[`hubert`,`HubertForCTC`],[`parakeet_ctc`,`ParakeetForCTC`]]),PP=new Map([[`wav2vec2`,`Wav2Vec2ForSequenceClassification`],[`wav2vec2-bert`,`Wav2Vec2BertForSequenceClassification`],[`unispeech`,`UniSpeechForSequenceClassification`],[`unispeech-sat`,`UniSpeechSatForSequenceClassification`],[`wavlm`,`WavLMForSequenceClassification`],[`hubert`,`HubertForSequenceClassification`],[`audio-spectrogram-transformer`,`ASTForAudioClassification`]]),FP=new Map([[`wavlm`,`WavLMForXVector`]]),IP=new Map([[`unispeech-sat`,`UniSpeechSatForAudioFrameClassification`],[`wavlm`,`WavLMForAudioFrameClassification`],[`wav2vec2`,`Wav2Vec2ForAudioFrameClassification`],[`pyannote`,`PyAnnoteForAudioFrameClassification`]]),LP=new Map([[`vitmatte`,`VitMatteForImageMatting`]]),RP=new Map([[`patchtst`,`PatchTSTForPrediction`],[`patchtsmixer`,`PatchTSMixerForPrediction`]]),zP=new Map([[`swin2sr`,`Swin2SRForImageSuperResolution`]]),BP=new Map([[`chmv2`,`CHMv2ForDepthEstimation`],[`dpt`,`DPTForDepthEstimation`],[`depth_anything`,`DepthAnythingForDepthEstimation`],[`glpn`,`GLPNForDepthEstimation`],[`sapiens`,`SapiensForDepthEstimation`],[`depth_pro`,`DepthProForDepthEstimation`],[`metric3d`,`Metric3DForDepthEstimation`],[`metric3dv2`,`Metric3Dv2ForDepthEstimation`]]),VP=new Map([[`sapiens`,`SapiensForNormalEstimation`]]),HP=new Map([[`vitpose`,`VitPoseForPoseEstimation`]]),UP=new Map([[`clip`,`CLIPVisionModelWithProjection`],[`siglip`,`SiglipVisionModel`],[`jina_clip`,`JinaCLIPVisionModel`]]),WP=[[cP,R.EncoderOnly],[lP,R.EncoderDecoder],[dP,R.DecoderOnlyWithoutHead],[uP,R.AutoEncoder],[hP,R.EncoderOnly],[gP,R.EncoderOnly],[_P,R.Seq2Seq],[fP,R.Seq2Seq],[vP,R.DecoderOnly],[yP,R.MultiModality],[bP,R.EncoderOnly],[xP,R.EncoderOnly],[SP,R.Vision2Seq],[CP,R.ImageTextToText],[wP,R.AudioTextToText],[EP,R.EncoderOnly],[kP,R.EncoderOnly],[jP,R.EncoderOnly],[AP,R.EncoderOnly],[LP,R.EncoderOnly],[RP,R.EncoderOnly],[zP,R.EncoderOnly],[BP,R.EncoderOnly],[VP,R.EncoderOnly],[HP,R.EncoderOnly],[DP,R.EncoderOnly],[OP,R.EncoderOnly],[MP,R.MaskGeneration],[NP,R.EncoderOnly],[PP,R.EncoderOnly],[pP,R.Seq2Seq],[mP,R.EncoderOnly],[FP,R.EncoderOnly],[IP,R.EncoderOnly],[UP,R.EncoderOnly]];for(let[e,t]of WP)for(let n of e.values()){EO.set(n,t);let e=UO[n];OO.set(e,n),DO.set(n,e)}var GP=[[`MusicgenForConditionalGeneration`,xj,R.Musicgen],[`Phi3VForCausalLM`,Vj,R.Phi3V],[`CLIPTextModelWithProjection`,dk,R.EncoderOnly],[`SiglipTextModel`,mM,R.EncoderOnly],[`JinaCLIPTextModel`,RA,R.EncoderOnly],[`ClapTextModelWithProjection`,ck,R.EncoderOnly],[`ClapAudioModelWithProjection`,lk,R.EncoderOnly],[`DacEncoderModel`,Ek,R.EncoderOnly],[`DacDecoderModel`,Dk,R.EncoderOnly],[`MimiEncoderModel`,tj,R.EncoderOnly],[`MimiDecoderModel`,nj,R.EncoderOnly],[`SnacEncoderModel`,_M,R.EncoderOnly],[`SnacDecoderModel`,vM,R.EncoderOnly],[`Gemma3nForConditionalGeneration`,cA,R.ImageAudioTextToText],[`Gemma4ForConditionalGeneration`,lA,R.ImageAudioTextToText],[`SupertonicForConditionalGeneration`,EM,R.Supertonic],[`ChatterboxModel`,ik,R.Chatterbox],[`VoxtralRealtimeForConditionalGeneration`,wN,R.VoxtralRealtime]];for(let[e,t,n]of GP)EO.set(e,n),OO.set(t,e),DO.set(e,t);var KP=new Map([[`modnet`,kP],[`birefnet`,kP],[`isnet`,kP],[`ben`,kP]]);for(let[e,t]of KP.entries())t.set(e,`PreTrainedModel`),EO.set(e,R.EncoderOnly),DO.set(e,z);var qP=new Set(KP.keys());EO.set(`PreTrainedModel`,R.EncoderOnly),OO.set(z,`PreTrainedModel`);var JP={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:hP,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:gP,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:pP,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:mP,MODEL_FOR_MASKED_LM_MAPPING_NAMES:bP,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:xP,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:EP,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:kP,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:AP,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:jP,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:DP,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:OP,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:MP,MODEL_FOR_CTC_MAPPING_NAMES:NP,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:PP,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:FP,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:IP,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:TP,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:LP,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:zP,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:BP,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:VP,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:HP,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:UP,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:CP,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:wP,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:_P,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:fP,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:vP,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:SP};eme(JP);var YP=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d};if(f.config=await tO.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:p}=f.config;for(let t of this.MODEL_CLASS_MAPPINGS){let n=t.get(p);if(!n){for(let e of t.values())if(e[0]===p){n=e;break}if(!n)continue}return await UO[n].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return qP.has(p)||Wb.warn(`Unknown model class "${p}", attempting to construct from base class.`),await z.from_pretrained(e,f);throw Error(`Unsupported model type: ${p}`)}},XP=class extends YP{static MODEL_CLASS_MAPPINGS=WP.map(e=>e[0]);static BASE_IF_FAIL=!0},ZP=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},QP=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},$P=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},eF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},tF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},nF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},rF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},iF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},aF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},oF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},sF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},cF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},lF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},uF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},dF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},fF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var pF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_CTC_MAPPING_NAMES]},mF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]}),class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]};var hF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var gF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},_F=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]}),class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]};var vF=class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]}),class extends YP{static MODEL_CLASS_MAPPINGS=[JP.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function yF(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>$E.read(e)))}async function bF(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>typeof e==`string`||e instanceof URL?rE(e,t):e instanceof Float64Array?new Float32Array(e):e))}function xF(e,t){t&&(e=e.map(e=>e|0));let[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}var SF=class extends Nb{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}},CF=class extends SF{async _call(e,{top_k:t=1}={}){let n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),{problem_type:i,id2label:a}=this.model.config,o=i===`multi_label_classification`?e=>e.sigmoid():e=>new L(`float32`,hC(e.data),e.dims),s=[];for(let e of r.logits){let n=await pw(o(e),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));t===1?s.push(...i):s.push(i)}return Array.isArray(e)||t===1?s:s[0]}},wF=class extends SF{async _call(e,{ignore_labels:t=[`O`],aggregation_strategy:n=`none`}={}){if(n!==`none`&&n!==`simple`)throw Error(`Invalid aggregation_strategy: "${n}". Must be one of "none" or "simple".`);let r=Array.isArray(e),i=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(i)).logits,o=this.model.config.id2label,s=[];for(let e=0;e{let o=0,s=[];for(let n=i;ne==u),i=a[e].tolist(),f=o[e].tolist();for(let n=1;ne==t[n])!==-1)&&(i[n]=-1/0,f[n]=-1/0);let p=hC(i).map((e,t)=>[e,t]),m=hC(f).map((e,t)=>[e,t]);p[0][0]=0,m[0][0]=0;let h=Bb(p,m).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]),g=[];for(let e=0;ee==n);if(c===-1)throw Error(`Mask token (${r}) not found in text.`);let l=a[e][c],u=await pw(new L(`float32`,hC(l.data),l.dims),t),d=u[0].tolist(),f=u[1].tolist();o.push(f.map((e,t)=>{let n=i.slice();return n[c]=e,{score:d[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(n,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},kF=class extends SF{_default_generation_config={max_new_tokens:256};_key=`generated_text`;async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let r=this.tokenizer,i={padding:!0,truncation:!0},a;a=this.task===`translation`&&`_build_translation_inputs`in r?r._build_translation_inputs(e,i,t):r(e,i);let o=await this.model.generate({...a,...this._default_generation_config,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},AF=class extends kF{_key=`summary_text`},jF=class extends kF{_key=`translation_text`};function MF(e){return Array.isArray(e)&&e.every(e=>`role`in e&&`content`in e)}var NF=class extends SF{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let{add_special_tokens:n,return_full_text:r,tools:i,documents:a,chat_template:o,tokenizer_encode_kwargs:s,...c}=t,l=!1,u=!1,d=n??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,f=s,p;if(typeof e==`string`)p=e=[e];else if(Array.isArray(e)&&e.every(e=>typeof e==`string`))l=!0,p=e;else{if(MF(e))e=[e];else if(Array.isArray(e)&&e.every(MF))l=!0;else throw Error(`Input must be a string, an array of strings, a Chat, or an array of Chats`);u=!0;let t={tokenize:!1,add_generation_prompt:!0,...Hb({tools:i,documents:a,chat_template:o},[`tools`,`documents`,`chat_template`]),...f};p=e.map(e=>this.tokenizer.apply_chat_template(e,t)),d=!1,f=void 0}let m=u?!1:r??!0;this.tokenizer.padding_side=`left`;let h=this.tokenizer(p,{add_special_tokens:d,padding:!0,truncation:!0,...f}),g=await this.model.generate({...h,...this._default_generation_config,...c}),_=this.tokenizer.batch_decode(g,{skip_special_tokens:!0}),v;!m&&h.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(h.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let y=Array.from({length:e.length},e=>[]);for(let t=0;t<_.length;++t){let n=Math.floor(t/g.dims[0]*e.length);v&&(_[t]=_[t].slice(v[n])),y[n].push({generated_text:u?[...e[n],{role:`assistant`,content:_[t]}]:_[t]})}return!l&&y.length===1?y[0]:y}},PF=class extends SF{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([e,t])=>[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(Wb.warn(`Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.`),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(Wb.warn(`Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.`),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n=`This example is {}.`,multi_label:r=!1}={}){let i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(e=>n.replace(`{}`,e)),o=r||t.length===1,s=[];for(let n of e){let e=[];for(let t of a){let r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);o?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}let r=(o?e.map(e=>hC(e)[1]):hC(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);s.push({sequence:n,labels:r.map(e=>t[e[1]]),scores:r.map(e=>e[0])})}return i?s:s[0]}},FF=class extends SF{async _call(e,{top_k:t=5}={}){let n=this.processor.feature_extractor.config.sampling_rate,r=await bF(e,n),i=this.model.config.id2label,a=[];for(let e of r){let n=await this.processor(e),r=(await this.model(n)).logits[0],o=await pw(new L(`float32`,hC(r.data),r.dims),t),s=o[0].tolist(),c=o[1].tolist().map((e,t)=>({label:i?i[e]:`LABEL_${e}`,score:s[t]}));a.push(c)}return Array.isArray(e)?a:a[0]}},IF=class extends SF{async _call(e,t,{hypothesis_template:n=`This is a sound of {}.`}={}){let r=!Array.isArray(e);r&&(e=[e]);let i=t.map(e=>n.replace(`{}`,e)),a=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,s=await bF(e,o),c=[];for(let e of s){let n=await this.processor(e),r=hC((await this.model({...a,...n})).logits_per_audio.data);c.push([...r].map((e,n)=>({score:e,label:t[n]})))}return r?c[0]:c}},LF=class extends SF{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case`whisper`:case`lite-whisper`:return this._call_whisper(e,t);case`wav2vec2`:case`wav2vec2-bert`:case`unispeech`:case`unispeech-sat`:case`hubert`:case`parakeet_ctc`:return this._call_wav2vec2(e,t);case`moonshine`:return this._call_moonshine(e,t);case`cohere_asr`:return this._call_cohere_asr(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&Wb.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&Wb.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await bF(r,i),o=[];for(let e of a){let t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(let e of n)r.push(_C(e.data)[1]);let i=this.tokenizer.decode(r,{skip_special_tokens:!0}).trim();o.push({text:i})}return n?o[0]:o}async _call_whisper(e,t){let n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};n===`word`&&(o.return_token_timestamps=!0,o.return_timestamps=!0);let s=!Array.isArray(e),c=s?[e]:e,l=this.processor.feature_extractor.config,u=l.chunk_length/this.model.config.max_source_positions,d=l.hop_length,f=l.sampling_rate,p=await bF(c,f),m=[];for(let e of p){let t=[];if(r>0){if(a===null)a=r/6;else if(r<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let n=f*r,i=f*a,o=n-2*i,s=0;for(;;){let r=s+n,a=e.subarray(s,r),c=await this.processor(a),l=s===0,u=r>=e.length;if(t.push({stride:[a.length,l?0:i,u?0:i],input_features:c.input_features,is_last:u}),u)break;s+=o}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of t){o.num_frames=Math.floor(e.stride[0]/d);let t=await this.model.generate({inputs:e.input_features,...o});if(n===`word`){let n=t.sequences.tolist()[0],r=t.token_timestamps.tolist()[0],i=this.tokenizer.timestamp_begin,a=Math.max(n.findIndex(e=>Number(e)>=i),0);e.tokens=n.slice(a),e.token_timestamps=r.slice(a).map(e=>CC(e,2))}else e.tokens=t[0].tolist();e.stride=e.stride.map(e=>e/f)}let[s,c]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:s,...c})}return s?m[0]:m}async _call_moonshine(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await bF(r,i),o=[];for(let e of a){let n=await this.processor(e),r=Math.floor(e.length/i)*6,a=await this.model.generate({max_new_tokens:r,...t,...n}),s=this.processor.batch_decode(a,{skip_special_tokens:!0})[0];o.push({text:s})}return n?o[0]:o}async _call_cohere_asr(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor,a=i.config.sampling_rate,o=await bF(r,a),s=t.language??`en`,c=this.processor.get_decoder_prompt_ids(s),l=[];for(let e of o){let n=i.split_audio(e),r=[];for(let e of n){let n=await this.processor(e),i=await this.model.generate({...n,decoder_input_ids:c,...t}),a=this.tokenizer.decode(i[0].tolist(),{skip_special_tokens:!0}).trim();r.push(a)}let a=this.processor.constructor.join_chunks(r,s);l.push({text:a})}return n?l[0]:l}},RF=class extends SF{DEFAULT_VOCODER_ID=`Xenova/speecht5_hifigan`;constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e==`string`||e instanceof URL)&&(e=new Float32Array(await(await jb.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new L(`float32`,e,[e.length]);else if(!(e instanceof L))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,n,r=null){let i=t.data,[a,o]=t.dims,s=r?r.data:null,c=[];for(let e=0;e({generated_text:e.trim()}));a.push(r)}return n?a:a[0]}},BF=class extends SF{async _call(e,{top_k:t=5}={}){let n=await yF(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),{id2label:a}=this.model.config,o=[];for(let e of i.logits){let n=await pw(new L(`float32`,hC(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));o.push(i)}return Array.isArray(e)?o:o[0]}},VF={panoptic:`post_process_panoptic_segmentation`,instance:`post_process_instance_segmentation`,semantic:`post_process_semantic_segmentation`},HF=class extends SF{async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error(`Image segmentation pipeline currently only supports a batch size of 1.`);let s=await yF(e),c=s.map(e=>[e.height,e.width]),l=await this.processor(s),{inputNames:u,outputNames:d}=this.model.sessions.model;if(!u.includes(`pixel_values`)){if(u.length!==1)throw Error(`Expected a single input name, but got ${u.length} inputs: ${u}.`);let e=u[0];if(e in l)throw Error(`Input name ${e} already exists in the inputs.`);l[e]=l.pixel_values}let f=await this.model(l),p=null;if(o!==null)p=VF[o];else if(this.processor.image_processor){for(let[e,t]of Object.entries(VF))if(t in this.processor.image_processor){p=this.processor.image_processor[t].bind(this.processor.image_processor),o=e;break}}let m=this.model.config.id2label,h=[];if(!o){let e=f[d[0]];for(let t=0;te<-1e-5||e>1.00001)&&r.sigmoid_();let i=await $E.fromTensor(r.mul_(255).to(`uint8`)).resize(n[1],n[0]);h.push({label:null,score:null,mask:i})}}else if(o===`panoptic`||o===`instance`){let e=p(f,t,n,r,i,a??c)[0],o=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(o.data.length);for(let n=0;n{let n=e.clone();return n.putAlpha(r[t].mask),n});return Array.isArray(e)?i:i[0]}},model:[cF,lF,uF],default:{model:`Xenova/modnet`},type:`image`},"zero-shot-image-classification":{pipeline:class extends SF{async _call(e,t,{hypothesis_template:n=`This is a photo of {}`}={}){let r=Array.isArray(e),i=await yF(e),a=t.map(e=>n.replace(`{}`,e)),o=this.tokenizer(a,{padding:this.model.config.model_type!==`siglip`||`max_length`,truncation:!0}),{pixel_values:s}=await this.processor(i),c=await this.model({...o,pixel_values:s}),l=this.model.config.model_type===`siglip`?e=>e.sigmoid().data:e=>hC(e.data),u=[];for(let e of c.logits_per_image){let n=[...l(e)].map((e,n)=>({score:e,label:t[n]}));n.sort((e,t)=>t.score-e.score),u.push(n)}return r?u:u[0]}},model:XP,default:{model:`Xenova/clip-vit-base-patch32`},type:`multimodal`},"object-detection":{pipeline:class extends SF{async _call(e,{threshold:t=.9,percentage:n=!1}={}){let r=Array.isArray(e);if(r&&e.length!==1)throw Error(`Object detection pipeline currently only supports a batch size of 1.`);let i=await yF(e),a=n?null:i.map(e=>[e.height,e.width]),{pixel_values:o,pixel_mask:s}=await this.processor(i),c=await this.model({pixel_values:o,pixel_mask:s}),l=this.processor.image_processor.post_process_object_detection(c,t,a),{id2label:u}=this.model.config,d=l.map(e=>e.boxes.map((t,r)=>({score:e.scores[r],label:u[e.classes[r]],box:xF(t,!n)})));return r?d:d[0]}},model:dF,default:{model:`Xenova/detr-resnet-50`},type:`multimodal`},"zero-shot-object-detection":{pipeline:class extends SF{async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){let a=Array.isArray(e),o=await yF(e),s=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(o),l=[];for(let e=0;e({score:e.scores[n],label:e.labels[n],box:xF(t,!i)}))}else{let e=this.processor.image_processor.post_process_object_detection(f,n,u,!0)[0];p=e.boxes.map((n,r)=>({score:e.scores[r],label:t[e.classes[r]],box:xF(n,!i)}))}p.sort((e,t)=>t.score-e.score),r!==null&&(p=p.slice(0,r)),l.push(p)}return a?l:l[0]}},model:fF,default:{model:`Xenova/owlvit-base-patch32`},type:`multimodal`},"document-question-answering":{pipeline:class extends SF{_default_generation_config={max_new_tokens:256};async _call(e,t,n={}){if(Array.isArray(e)){if(e.length!==1)throw Error(`Document Question Answering pipeline currently only supports a batch size of 1.`);e=e[0]}let r=(await yF(e))[0],{pixel_values:i}=await this.processor(r),a=`${t}`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,s=await this.model.generate({inputs:i,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...this._default_generation_config,...n}),c=this.tokenizer.batch_decode(s)[0].match(/(.*?)<\/s_answer>/),l=null;return c&&c.length>=2&&(l=c[1].trim()),[{answer:l}]}},model:hF,default:{model:`Xenova/donut-base-finetuned-docvqa`},type:`multimodal`},"image-to-image":{pipeline:class extends SF{async _call(e){let t=await yF(e),n=await this.processor(t),r=await this.model(n),i=[];for(let e of r.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to(`uint8`);i.push($E.fromTensor(t))}return Array.isArray(e)?i:i[0]}},model:gF,default:{model:`Xenova/swin2SR-classical-sr-x2-64`},type:`image`},"depth-estimation":{pipeline:class extends SF{async _call(e){let t=await yF(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;ee>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,WF=class{put(e){throw Error(`Not implemented`)}end(){throw Error(`Not implemented`)}},GF=wb.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),KF=class extends WF{constructor(e,{skip_prompt:t=!1,callback_function:n=null,token_callback_function:r=null,skip_special_tokens:i=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=n??GF,this.token_callback_function=r,this.decode_kwargs={skip_special_tokens:i,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error(`TextStreamer only supports batch size of 1`);let t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let n=e[0];if(this.token_callback_function?.(n),n.length===1&&this.special_ids.has(n[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(e,!1),this.token_cache=[],this.print_len=0}let e=this.tokenizer.decode(n,this.decode_kwargs);this.on_finalized_text(e,!1);return}this.token_cache=zb(this.token_cache,n);let r=this.tokenizer.decode(this.token_cache,this.decode_kwargs),i;t||r.endsWith(` +`)?(i=r.slice(this.print_len),this.token_cache=[],this.print_len=0):r.length>0&&UF(r.charCodeAt(r.length-1))?(i=r.slice(this.print_len),this.print_len+=i.length):(i=r.slice(this.print_len,r.lastIndexOf(` `)+1),this.print_len+=i.length),this.on_finalized_text(i,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e=``,this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===GF&&wb.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}};Object.keys(aw); +/*! +* hash-wasm (https://www.npmjs.com/package/hash-wasm) +* (c) Dani Biro +* @license MIT +*/ +function qF(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}var JF=class{constructor(){this.mutex=Promise.resolve()}lock(){let e=()=>{};return this.mutex=this.mutex.then(()=>new Promise(e)),new Promise(t=>{e=t})}dispatch(e){return qF(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}};function YF(){return typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:global}const XF=YF(),ZF=XF.Buffer??null,QF=XF.TextEncoder?new XF.TextEncoder:null;function $F(e,t){return(e&15)+(e>>6|e>>3&8)<<4|(t&15)+(t>>6|t>>3&8)}function eI(e,t){let n=t.length>>1;for(let r=0;r>>4;e[r++]=n>9?n+87:n+48,n=t[i]&15,e[r++]=n>9?n+87:n+48}return String.fromCharCode.apply(null,e)}const rI=ZF===null?e=>{if(typeof e==`string`)return QF.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`Invalid data type!`)}:e=>{if(typeof e==`string`){let t=ZF.from(e,`utf8`);return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(ZF.isBuffer(e))return new Uint8Array(e.buffer,e.byteOffset,e.length);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`Invalid data type!`)},iI=new Uint8Array(256);for(let e=0;e<64;e++)iI[`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.charCodeAt(e)]=e;function aI(e){let t=Math.floor(e.length*.75),n=e.length;return e[n-1]===`=`&&(--t,e[n-2]===`=`&&--t),t}function oI(e){let t=aI(e),n=e.length,r=new Uint8Array(t),i=0;for(let t=0;t>4,i+=1,r[i]=(a&15)<<4|o>>2,i+=1,r[i]=(o&3)<<6|s&63,i+=1}return r}const sI=16384,cI=new JF,lI=new Map;function uI(e,t){return qF(this,void 0,void 0,function*(){let n=null,r=null,i=!1;if(typeof WebAssembly>`u`)throw Error(`WebAssembly is not supported in this environment!`);let a=(e,t=0)=>{r.set(e,t)},o=()=>r,s=()=>n.exports,c=e=>{n.exports.Hash_SetMemorySize(e);let t=n.exports.Hash_GetBuffer(),i=n.exports.memory.buffer;r=new Uint8Array(i,t,e)},l=()=>new DataView(n.exports.memory.buffer).getUint32(n.exports.STATE_SIZE,!0),u=cI.dispatch(()=>qF(this,void 0,void 0,function*(){if(!lI.has(e.name)){let t=oI(e.data),n=WebAssembly.compile(t);lI.set(e.name,n)}let t=yield lI.get(e.name);n=yield WebAssembly.instantiate(t,{})})),d=()=>qF(this,void 0,void 0,function*(){n||(yield u);let e=n.exports.Hash_GetBuffer(),t=n.exports.memory.buffer;r=new Uint8Array(t,e,sI)}),f=(e=null)=>{i=!0,n.exports.Hash_Init(e)},p=e=>{let t=0;for(;t{if(!i)throw Error(`update() called before init()`);let t=rI(e);p(t)},h=new Uint8Array(t*2),g=(e,a=null)=>{if(!i)throw Error(`digest() called before init()`);return i=!1,n.exports.Hash_Final(a),e===`binary`?r.slice(0,t):nI(h,r,t)},_=()=>{if(!i)throw Error(`save() can only be called after init() and before digest()`);let t=n.exports.Hash_GetState(),r=l(),a=n.exports.memory.buffer,o=new Uint8Array(a,t,r),s=new Uint8Array(4+r);return eI(s,e.hash),s.set(o,4),s},v=t=>{if(!(t instanceof Uint8Array))throw Error(`load() expects an Uint8Array generated by save()`);let r=n.exports.Hash_GetState(),a=l(),o=4+a,s=n.exports.memory.buffer;if(t.length!==o)throw Error(`Bad state length (expected ${o} bytes, got ${t.length})`);if(!tI(e.hash,t.subarray(0,4)))throw Error(`This state was written by an incompatible hash implementation`);let c=t.subarray(4);new Uint8Array(s,r,a).set(c),i=!0},y=e=>typeof e==`string`?e.length!0;break;case`blake2b`:case`blake2s`:b=(e,t)=>t<=512&&y(e);break;case`blake3`:b=(e,t)=>t===0&&y(e);break;case`xxhash64`:case`xxhash3`:case`xxhash128`:case`crc64`:b=()=>!1}return yield d(),{getMemory:o,writeMemory:a,getExports:s,setMemorySize:c,init:f,update:m,digest:g,save:_,load:v,calculate:(e,i=null,a=null)=>{if(!b(e,i))return f(i),m(e),g(`hex`,a);let o=rI(e);return r.set(o),n.exports.Hash_Calculate(o.length,i,a),nI(h,r,t)},hashLength:t}})}new JF,new JF,new JF,new JF,new JF,new JF,new JF,new JF,new JF,new JF,new JF;var dI={name:`sha256`,data:`AGFzbQEAAAABEQRgAAF/YAF/AGAAAGACf38AAwgHAAEBAQIAAwUEAQECAgYOAn8BQfCJBQt/AEGACAsHcAgGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQAAQtIYXNoX1VwZGF0ZQACCkhhc2hfRmluYWwABA1IYXNoX0dldFN0YXRlAAUOSGFzaF9DYWxjdWxhdGUABgpTVEFURV9TSVpFAwEKnEoHBQBBgAkLnQEAQQBCADcDwIkBQQBBHEEgIABB4AFGIgAbNgLoiQFBAEKnn+anxvST/b5/Qquzj/yRo7Pw2wAgABs3A+CJAUEAQrGWgP6fooWs6ABC/6S5iMWR2oKbfyAAGzcD2IkBQQBCl7rDg5Onlod3QvLmu+Ojp/2npX8gABs3A9CJAUEAQti9loj8oLW+NkLnzKfQ1tDrs7t/IAAbNwPIiQEL7wICAX4Gf0EAQQApA8CJASIBIACtfDcDwIkBAkACQAJAIAGnQT9xIgINAEGACSEDDAELAkBBwAAgAmsiBCAAIAQgAEkbIgNFDQAgA0EDcSEFIAJBgIkBaiEGQQAhAgJAIANBBEkNACADQfwAcSEHQQAhAgNAIAYgAmoiAyACQYAJai0AADoAACADQQFqIAJBgQlqLQAAOgAAIANBAmogAkGCCWotAAA6AAAgA0EDaiACQYMJai0AADoAACAHIAJBBGoiAkcNAAsLIAVFDQADQCAGIAJqIAJBgAlqLQAAOgAAIAJBAWohAiAFQX9qIgUNAAsLIAAgBEkNAUGAiQEQAyAAIARrIQAgBEGACWohAwsCQCAAQcAASQ0AA0AgAxADIANBwABqIQMgAEFAaiIAQT9LDQALCyAARQ0AQQAhAkEAIQUDQCACQYCJAWogAyACai0AADoAACACQQFqIQIgACAFQQFqIgVB/wFxSw0ACwsLoz4BRX9BACAAKAI8IgFBGHQgAUGA/gNxQQh0ciABQQh2QYD+A3EgAUEYdnJyIgFBGXcgAUEOd3MgAUEDdnMgACgCOCICQRh0IAJBgP4DcUEIdHIgAkEIdkGA/gNxIAJBGHZyciICaiAAKAIgIgNBGHQgA0GA/gNxQQh0ciADQQh2QYD+A3EgA0EYdnJyIgRBGXcgBEEOd3MgBEEDdnMgACgCHCIDQRh0IANBgP4DcUEIdHIgA0EIdkGA/gNxIANBGHZyciIFaiAAKAIEIgNBGHQgA0GA/gNxQQh0ciADQQh2QYD+A3EgA0EYdnJyIgZBGXcgBkEOd3MgBkEDdnMgACgCACIDQRh0IANBgP4DcUEIdHIgA0EIdkGA/gNxIANBGHZyciIHaiAAKAIkIgNBGHQgA0GA/gNxQQh0ciADQQh2QYD+A3EgA0EYdnJyIghqIAJBD3cgAkENd3MgAkEKdnNqIgNqIAAoAhgiCUEYdCAJQYD+A3FBCHRyIAlBCHZBgP4DcSAJQRh2cnIiCkEZdyAKQQ53cyAKQQN2cyAAKAIUIglBGHQgCUGA/gNxQQh0ciAJQQh2QYD+A3EgCUEYdnJyIgtqIAJqIAAoAhAiCUEYdCAJQYD+A3FBCHRyIAlBCHZBgP4DcSAJQRh2cnIiDEEZdyAMQQ53cyAMQQN2cyAAKAIMIglBGHQgCUGA/gNxQQh0ciAJQQh2QYD+A3EgCUEYdnJyIg1qIAAoAjAiCUEYdCAJQYD+A3FBCHRyIAlBCHZBgP4DcSAJQRh2cnIiDmogACgCCCIJQRh0IAlBgP4DcUEIdHIgCUEIdkGA/gNxIAlBGHZyciIPQRl3IA9BDndzIA9BA3ZzIAZqIAAoAigiCUEYdCAJQYD+A3FBCHRyIAlBCHZBgP4DcSAJQRh2cnIiEGogAUEPdyABQQ13cyABQQp2c2oiCUEPdyAJQQ13cyAJQQp2c2oiEUEPdyARQQ13cyARQQp2c2oiEkEPdyASQQ13cyASQQp2c2oiE2ogACgCNCIUQRh0IBRBgP4DcUEIdHIgFEEIdkGA/gNxIBRBGHZyciIVQRl3IBVBDndzIBVBA3ZzIA5qIBJqIAAoAiwiAEEYdCAAQYD+A3FBCHRyIABBCHZBgP4DcSAAQRh2cnIiFkEZdyAWQQ53cyAWQQN2cyAQaiARaiAIQRl3IAhBDndzIAhBA3ZzIARqIAlqIAVBGXcgBUEOd3MgBUEDdnMgCmogAWogC0EZdyALQQ53cyALQQN2cyAMaiAVaiANQRl3IA1BDndzIA1BA3ZzIA9qIBZqIANBD3cgA0ENd3MgA0EKdnNqIhRBD3cgFEENd3MgFEEKdnNqIhdBD3cgF0ENd3MgF0EKdnNqIhhBD3cgGEENd3MgGEEKdnNqIhlBD3cgGUENd3MgGUEKdnNqIhpBD3cgGkENd3MgGkEKdnNqIhtBD3cgG0ENd3MgG0EKdnNqIhxBGXcgHEEOd3MgHEEDdnMgAkEZdyACQQ53cyACQQN2cyAVaiAYaiAOQRl3IA5BDndzIA5BA3ZzIBZqIBdqIBBBGXcgEEEOd3MgEEEDdnMgCGogFGogE0EPdyATQQ13cyATQQp2c2oiHUEPdyAdQQ13cyAdQQp2c2oiHkEPdyAeQQ13cyAeQQp2c2oiH2ogE0EZdyATQQ53cyATQQN2cyAYaiADQRl3IANBDndzIANBA3ZzIAFqIBlqIB9BD3cgH0ENd3MgH0EKdnNqIiBqIBJBGXcgEkEOd3MgEkEDdnMgF2ogH2ogEUEZdyARQQ53cyARQQN2cyAUaiAeaiAJQRl3IAlBDndzIAlBA3ZzIANqIB1qIBxBD3cgHEENd3MgHEEKdnNqIiFBD3cgIUENd3MgIUEKdnNqIiJBD3cgIkENd3MgIkEKdnNqIiNBD3cgI0ENd3MgI0EKdnNqIiRqIBtBGXcgG0EOd3MgG0EDdnMgHmogI2ogGkEZdyAaQQ53cyAaQQN2cyAdaiAiaiAZQRl3IBlBDndzIBlBA3ZzIBNqICFqIBhBGXcgGEEOd3MgGEEDdnMgEmogHGogF0EZdyAXQQ53cyAXQQN2cyARaiAbaiAUQRl3IBRBDndzIBRBA3ZzIAlqIBpqICBBD3cgIEENd3MgIEEKdnNqIiVBD3cgJUENd3MgJUEKdnNqIiZBD3cgJkENd3MgJkEKdnNqIidBD3cgJ0ENd3MgJ0EKdnNqIihBD3cgKEENd3MgKEEKdnNqIilBD3cgKUENd3MgKUEKdnNqIipBD3cgKkENd3MgKkEKdnNqIitBGXcgK0EOd3MgK0EDdnMgH0EZdyAfQQ53cyAfQQN2cyAbaiAnaiAeQRl3IB5BDndzIB5BA3ZzIBpqICZqIB1BGXcgHUEOd3MgHUEDdnMgGWogJWogJEEPdyAkQQ13cyAkQQp2c2oiLEEPdyAsQQ13cyAsQQp2c2oiLUEPdyAtQQ13cyAtQQp2c2oiLmogJEEZdyAkQQ53cyAkQQN2cyAnaiAgQRl3ICBBDndzICBBA3ZzIBxqIChqIC5BD3cgLkENd3MgLkEKdnNqIi9qICNBGXcgI0EOd3MgI0EDdnMgJmogLmogIkEZdyAiQQ53cyAiQQN2cyAlaiAtaiAhQRl3ICFBDndzICFBA3ZzICBqICxqICtBD3cgK0ENd3MgK0EKdnNqIjBBD3cgMEENd3MgMEEKdnNqIjFBD3cgMUENd3MgMUEKdnNqIjJBD3cgMkENd3MgMkEKdnNqIjNqICpBGXcgKkEOd3MgKkEDdnMgLWogMmogKUEZdyApQQ53cyApQQN2cyAsaiAxaiAoQRl3IChBDndzIChBA3ZzICRqIDBqICdBGXcgJ0EOd3MgJ0EDdnMgI2ogK2ogJkEZdyAmQQ53cyAmQQN2cyAiaiAqaiAlQRl3ICVBDndzICVBA3ZzICFqIClqIC9BD3cgL0ENd3MgL0EKdnNqIjRBD3cgNEENd3MgNEEKdnNqIjVBD3cgNUENd3MgNUEKdnNqIjZBD3cgNkENd3MgNkEKdnNqIjdBD3cgN0ENd3MgN0EKdnNqIjhBD3cgOEENd3MgOEEKdnNqIjlBD3cgOUENd3MgOUEKdnNqIjogOCA0IC4gLCAhIBsgGSADIA4gBEEAKALYiQEiO0EadyA7QRV3cyA7QQd3c0EAKALkiQEiPGpBACgC4IkBIj1BACgC3IkBIj5zIDtxID1zaiAHakGY36iUBGoiB0EAKALUiQEiP2oiACAMaiA7IA1qID4gD2ogPSAGaiAAID4gO3NxID5zaiAAQRp3IABBFXdzIABBB3dzakGRid2JB2oiQEEAKALQiQEiQWoiDCAAIDtzcSA7c2ogDEEadyAMQRV3cyAMQQd3c2pBz/eDrntqIkJBACgCzIkBIkNqIg0gDCAAc3EgAHNqIA1BGncgDUEVd3MgDUEHd3NqQaW3181+aiJEQQAoAsiJASIAaiIPIA0gDHNxIAxzaiAPQRp3IA9BFXdzIA9BB3dzakHbhNvKA2oiRSBBIEMgAHNxIEMgAHFzIABBHncgAEETd3MgAEEKd3NqIAdqIgZqIgdqIAUgD2ogCiANaiALIAxqIAcgDyANc3EgDXNqIAdBGncgB0EVd3MgB0EHd3NqQfGjxM8FaiIKIAYgAHMgQ3EgBiAAcXMgBkEedyAGQRN3cyAGQQp3c2ogQGoiDGoiBCAHIA9zcSAPc2ogBEEadyAEQRV3cyAEQQd3c2pBpIX+kXlqIgsgDCAGcyAAcSAMIAZxcyAMQR53IAxBE3dzIAxBCndzaiBCaiINaiIPIAQgB3NxIAdzaiAPQRp3IA9BFXdzIA9BB3dzakHVvfHYemoiQCANIAxzIAZxIA0gDHFzIA1BHncgDUETd3MgDUEKd3NqIERqIgZqIgcgDyAEc3EgBHNqIAdBGncgB0EVd3MgB0EHd3NqQZjVnsB9aiJCIAYgDXMgDHEgBiANcXMgBkEedyAGQRN3cyAGQQp3c2ogRWoiDGoiBWogFiAHaiAQIA9qIAggBGogBSAHIA9zcSAPc2ogBUEadyAFQRV3cyAFQQd3c2pBgbaNlAFqIgggDCAGcyANcSAMIAZxcyAMQR53IAxBE3dzIAxBCndzaiAKaiINaiIPIAUgB3NxIAdzaiAPQRp3IA9BFXdzIA9BB3dzakG+i8ahAmoiDiANIAxzIAZxIA0gDHFzIA1BHncgDUETd3MgDUEKd3NqIAtqIgZqIgcgDyAFc3EgBXNqIAdBGncgB0EVd3MgB0EHd3NqQcP7sagFaiIQIAYgDXMgDHEgBiANcXMgBkEedyAGQRN3cyAGQQp3c2ogQGoiDGoiBCAHIA9zcSAPc2ogBEEadyAEQRV3cyAEQQd3c2pB9Lr5lQdqIhYgDCAGcyANcSAMIAZxcyAMQR53IAxBE3dzIAxBCndzaiBCaiINaiIFaiABIARqIAIgB2ogFSAPaiAFIAQgB3NxIAdzaiAFQRp3IAVBFXdzIAVBB3dzakH+4/qGeGoiByANIAxzIAZxIA0gDHFzIA1BHncgDUETd3MgDUEKd3NqIAhqIgFqIgYgBSAEc3EgBHNqIAZBGncgBkEVd3MgBkEHd3NqQaeN8N55aiIEIAEgDXMgDHEgASANcXMgAUEedyABQRN3cyABQQp3c2ogDmoiAmoiDCAGIAVzcSAFc2ogDEEadyAMQRV3cyAMQQd3c2pB9OLvjHxqIgUgAiABcyANcSACIAFxcyACQR53IAJBE3dzIAJBCndzaiAQaiIDaiINIAwgBnNxIAZzaiANQRp3IA1BFXdzIA1BB3dzakHB0+2kfmoiCCADIAJzIAFxIAMgAnFzIANBHncgA0ETd3MgA0EKd3NqIBZqIgFqIg8gF2ogESANaiAUIAxqIAkgBmogDyANIAxzcSAMc2ogD0EadyAPQRV3cyAPQQd3c2pBho/5/X5qIgYgASADcyACcSABIANxcyABQR53IAFBE3dzIAFBCndzaiAHaiICaiIJIA8gDXNxIA1zaiAJQRp3IAlBFXdzIAlBB3dzakHGu4b+AGoiDCACIAFzIANxIAIgAXFzIAJBHncgAkETd3MgAkEKd3NqIARqIgNqIhEgCSAPc3EgD3NqIBFBGncgEUEVd3MgEUEHd3NqQczDsqACaiINIAMgAnMgAXEgAyACcXMgA0EedyADQRN3cyADQQp3c2ogBWoiAWoiFCARIAlzcSAJc2ogFEEadyAUQRV3cyAUQQd3c2pB79ik7wJqIg8gASADcyACcSABIANxcyABQR53IAFBE3dzIAFBCndzaiAIaiICaiIXaiATIBRqIBggEWogEiAJaiAXIBQgEXNxIBFzaiAXQRp3IBdBFXdzIBdBB3dzakGqidLTBGoiGCACIAFzIANxIAIgAXFzIAJBHncgAkETd3MgAkEKd3NqIAZqIgNqIgkgFyAUc3EgFHNqIAlBGncgCUEVd3MgCUEHd3NqQdzTwuUFaiIUIAMgAnMgAXEgAyACcXMgA0EedyADQRN3cyADQQp3c2ogDGoiAWoiESAJIBdzcSAXc2ogEUEadyARQRV3cyARQQd3c2pB2pHmtwdqIhcgASADcyACcSABIANxcyABQR53IAFBE3dzIAFBCndzaiANaiICaiISIBEgCXNxIAlzaiASQRp3IBJBFXdzIBJBB3dzakHSovnBeWoiGSACIAFzIANxIAIgAXFzIAJBHncgAkETd3MgAkEKd3NqIA9qIgNqIhNqIB4gEmogGiARaiAdIAlqIBMgEiARc3EgEXNqIBNBGncgE0EVd3MgE0EHd3NqQe2Mx8F6aiIaIAMgAnMgAXEgAyACcXMgA0EedyADQRN3cyADQQp3c2ogGGoiAWoiCSATIBJzcSASc2ogCUEadyAJQRV3cyAJQQd3c2pByM+MgHtqIhggASADcyACcSABIANxcyABQR53IAFBE3dzIAFBCndzaiAUaiICaiIRIAkgE3NxIBNzaiARQRp3IBFBFXdzIBFBB3dzakHH/+X6e2oiFCACIAFzIANxIAIgAXFzIAJBHncgAkETd3MgAkEKd3NqIBdqIgNqIhIgESAJc3EgCXNqIBJBGncgEkEVd3MgEkEHd3NqQfOXgLd8aiIXIAMgAnMgAXEgAyACcXMgA0EedyADQRN3cyADQQp3c2ogGWoiAWoiE2ogICASaiAcIBFqIB8gCWogEyASIBFzcSARc2ogE0EadyATQRV3cyATQQd3c2pBx6KerX1qIhkgASADcyACcSABIANxcyABQR53IAFBE3dzIAFBCndzaiAaaiICaiIJIBMgEnNxIBJzaiAJQRp3IAlBFXdzIAlBB3dzakHRxqk2aiIaIAIgAXMgA3EgAiABcXMgAkEedyACQRN3cyACQQp3c2ogGGoiA2oiESAJIBNzcSATc2ogEUEadyARQRV3cyARQQd3c2pB59KkoQFqIhggAyACcyABcSADIAJxcyADQR53IANBE3dzIANBCndzaiAUaiIBaiISIBEgCXNxIAlzaiASQRp3IBJBFXdzIBJBB3dzakGFldy9AmoiFCABIANzIAJxIAEgA3FzIAFBHncgAUETd3MgAUEKd3NqIBdqIgJqIhMgI2ogJiASaiAiIBFqICUgCWogEyASIBFzcSARc2ogE0EadyATQRV3cyATQQd3c2pBuMLs8AJqIhcgAiABcyADcSACIAFxcyACQR53IAJBE3dzIAJBCndzaiAZaiIDaiIJIBMgEnNxIBJzaiAJQRp3IAlBFXdzIAlBB3dzakH827HpBGoiGSADIAJzIAFxIAMgAnFzIANBHncgA0ETd3MgA0EKd3NqIBpqIgFqIhEgCSATc3EgE3NqIBFBGncgEUEVd3MgEUEHd3NqQZOa4JkFaiIaIAEgA3MgAnEgASADcXMgAUEedyABQRN3cyABQQp3c2ogGGoiAmoiEiARIAlzcSAJc2ogEkEadyASQRV3cyASQQd3c2pB1OapqAZqIhggAiABcyADcSACIAFxcyACQR53IAJBE3dzIAJBCndzaiAUaiIDaiITaiAoIBJqICQgEWogJyAJaiATIBIgEXNxIBFzaiATQRp3IBNBFXdzIBNBB3dzakG7laizB2oiFCADIAJzIAFxIAMgAnFzIANBHncgA0ETd3MgA0EKd3NqIBdqIgFqIgkgEyASc3EgEnNqIAlBGncgCUEVd3MgCUEHd3NqQa6Si454aiIXIAEgA3MgAnEgASADcXMgAUEedyABQRN3cyABQQp3c2ogGWoiAmoiESAJIBNzcSATc2ogEUEadyARQRV3cyARQQd3c2pBhdnIk3lqIhkgAiABcyADcSACIAFxcyACQR53IAJBE3dzIAJBCndzaiAaaiIDaiISIBEgCXNxIAlzaiASQRp3IBJBFXdzIBJBB3dzakGh0f+VemoiGiADIAJzIAFxIAMgAnFzIANBHncgA0ETd3MgA0EKd3NqIBhqIgFqIhNqICogEmogLSARaiApIAlqIBMgEiARc3EgEXNqIBNBGncgE0EVd3MgE0EHd3NqQcvM6cB6aiIYIAEgA3MgAnEgASADcXMgAUEedyABQRN3cyABQQp3c2ogFGoiAmoiCSATIBJzcSASc2ogCUEadyAJQRV3cyAJQQd3c2pB8JauknxqIhQgAiABcyADcSACIAFxcyACQR53IAJBE3dzIAJBCndzaiAXaiIDaiIRIAkgE3NxIBNzaiARQRp3IBFBFXdzIBFBB3dzakGjo7G7fGoiFyADIAJzIAFxIAMgAnFzIANBHncgA0ETd3MgA0EKd3NqIBlqIgFqIhIgESAJc3EgCXNqIBJBGncgEkEVd3MgEkEHd3NqQZnQy4x9aiIZIAEgA3MgAnEgASADcXMgAUEedyABQRN3cyABQQp3c2ogGmoiAmoiE2ogMCASaiAvIBFqICsgCWogEyASIBFzcSARc2ogE0EadyATQRV3cyATQQd3c2pBpIzktH1qIhogAiABcyADcSACIAFxcyACQR53IAJBE3dzIAJBCndzaiAYaiIDaiIJIBMgEnNxIBJzaiAJQRp3IAlBFXdzIAlBB3dzakGF67igf2oiGCADIAJzIAFxIAMgAnFzIANBHncgA0ETd3MgA0EKd3NqIBRqIgFqIhEgCSATc3EgE3NqIBFBGncgEUEVd3MgEUEHd3NqQfDAqoMBaiIUIAEgA3MgAnEgASADcXMgAUEedyABQRN3cyABQQp3c2ogF2oiAmoiEiARIAlzcSAJc2ogEkEadyASQRV3cyASQQd3c2pBloKTzQFqIhcgAiABcyADcSACIAFxcyACQR53IAJBE3dzIAJBCndzaiAZaiIDaiITIDZqIDIgEmogNSARaiAxIAlqIBMgEiARc3EgEXNqIBNBGncgE0EVd3MgE0EHd3NqQYjY3fEBaiIZIAMgAnMgAXEgAyACcXMgA0EedyADQRN3cyADQQp3c2ogGmoiAWoiCSATIBJzcSASc2ogCUEadyAJQRV3cyAJQQd3c2pBzO6hugJqIhogASADcyACcSABIANxcyABQR53IAFBE3dzIAFBCndzaiAYaiICaiIRIAkgE3NxIBNzaiARQRp3IBFBFXdzIBFBB3dzakG1+cKlA2oiGCACIAFzIANxIAIgAXFzIAJBHncgAkETd3MgAkEKd3NqIBRqIgNqIhIgESAJc3EgCXNqIBJBGncgEkEVd3MgEkEHd3NqQbOZ8MgDaiIUIAMgAnMgAXEgAyACcXMgA0EedyADQRN3cyADQQp3c2ogF2oiAWoiE2ogLEEZdyAsQQ53cyAsQQN2cyAoaiA0aiAzQQ93IDNBDXdzIDNBCnZzaiIXIBJqIDcgEWogMyAJaiATIBIgEXNxIBFzaiATQRp3IBNBFXdzIBNBB3dzakHK1OL2BGoiGyABIANzIAJxIAEgA3FzIAFBHncgAUETd3MgAUEKd3NqIBlqIgJqIgkgEyASc3EgEnNqIAlBGncgCUEVd3MgCUEHd3NqQc+U89wFaiIZIAIgAXMgA3EgAiABcXMgAkEedyACQRN3cyACQQp3c2ogGmoiA2oiESAJIBNzcSATc2ogEUEadyARQRV3cyARQQd3c2pB89+5wQZqIhogAyACcyABcSADIAJxcyADQR53IANBE3dzIANBCndzaiAYaiIBaiISIBEgCXNxIAlzaiASQRp3IBJBFXdzIBJBB3dzakHuhb6kB2oiHCABIANzIAJxIAEgA3FzIAFBHncgAUETd3MgAUEKd3NqIBRqIgJqIhNqIC5BGXcgLkEOd3MgLkEDdnMgKmogNmogLUEZdyAtQQ53cyAtQQN2cyApaiA1aiAXQQ93IBdBDXdzIBdBCnZzaiIUQQ93IBRBDXdzIBRBCnZzaiIYIBJqIDkgEWogFCAJaiATIBIgEXNxIBFzaiATQRp3IBNBFXdzIBNBB3dzakHvxpXFB2oiCSACIAFzIANxIAIgAXFzIAJBHncgAkETd3MgAkEKd3NqIBtqIgNqIhEgEyASc3EgEnNqIBFBGncgEUEVd3MgEUEHd3NqQZTwoaZ4aiIbIAMgAnMgAXEgAyACcXMgA0EedyADQRN3cyADQQp3c2ogGWoiAWoiEiARIBNzcSATc2ogEkEadyASQRV3cyASQQd3c2pBiISc5nhqIhkgASADcyACcSABIANxcyABQR53IAFBE3dzIAFBCndzaiAaaiICaiITIBIgEXNxIBFzaiATQRp3IBNBFXdzIBNBB3dzakH6//uFeWoiGiACIAFzIANxIAIgAXFzIAJBHncgAkETd3MgAkEKd3NqIBxqIgNqIhQgPGo2AuSJAUEAID8gAyACcyABcSADIAJxcyADQR53IANBE3dzIANBCndzaiAJaiIBIANzIAJxIAEgA3FzIAFBHncgAUETd3MgAUEKd3NqIBtqIgIgAXMgA3EgAiABcXMgAkEedyACQRN3cyACQQp3c2ogGWoiAyACcyABcSADIAJxcyADQR53IANBE3dzIANBCndzaiAaaiIJajYC1IkBQQAgPSAvQRl3IC9BDndzIC9BA3ZzICtqIDdqIBhBD3cgGEENd3MgGEEKdnNqIhggEWogFCATIBJzcSASc2ogFEEadyAUQRV3cyAUQQd3c2pB69nBonpqIhkgAWoiEWo2AuCJAUEAIEEgCSADcyACcSAJIANxcyAJQR53IAlBE3dzIAlBCndzaiAZaiIBajYC0IkBQQAgPiAwQRl3IDBBDndzIDBBA3ZzIC9qIBdqIDpBD3cgOkENd3MgOkEKdnNqIBJqIBEgFCATc3EgE3NqIBFBGncgEUEVd3MgEUEHd3NqQffH5vd7aiIXIAJqIhJqNgLciQFBACBDIAEgCXMgA3EgASAJcXMgAUEedyABQRN3cyABQQp3c2ogF2oiAmo2AsyJAUEAIDsgNEEZdyA0QQ53cyA0QQN2cyAwaiA4aiAYQQ93IBhBDXdzIBhBCnZzaiATaiASIBEgFHNxIBRzaiASQRp3IBJBFXdzIBJBB3dzakHy8cWzfGoiESADamo2AtiJAUEAIAAgAiABcyAJcSACIAFxcyACQR53IAJBE3dzIAJBCndzaiARamo2AsiJAQuyBgIEfwF+QQAoAsCJASIAQQJ2QQ9xIgFBAnRBgIkBaiICIAIoAgBBfyAAQQN0IgB0QX9zcUGAASAAdHM2AgACQAJAAkAgAUEOSQ0AAkAgAUEORw0AQQBBADYCvIkBC0GAiQEQA0EAIQIMAQsgAUENRg0BIAFBAWohAgsgAiEDAkBBBiACa0EHcSIARQ0AIAIgAGohAyACQQJ0QYCJAWohAQNAIAFBADYCACABQQRqIQEgAEF/aiIADQALCyACQXlqQQdJDQAgA0ECdCEBA0AgAUGYiQFqQgA3AgAgAUGQiQFqQgA3AgAgAUGIiQFqQgA3AgAgAUGAiQFqQgA3AgAgAUEgaiIBQThHDQALC0EAIQFBAEEAKQPAiQEiBKciAEEbdCAAQQt0QYCA/AdxciAAQQV2QYD+A3EgAEEDdEEYdnJyNgK8iQFBACAEQh2IpyIAQRh0IABBgP4DcUEIdHIgAEEIdkGA/gNxIABBGHZycjYCuIkBQYCJARADQQBBACgC5IkBIgBBGHQgAEGA/gNxQQh0ciAAQQh2QYD+A3EgAEEYdnJyNgLkiQFBAEEAKALgiQEiAEEYdCAAQYD+A3FBCHRyIABBCHZBgP4DcSAAQRh2cnI2AuCJAUEAQQAoAtyJASIAQRh0IABBgP4DcUEIdHIgAEEIdkGA/gNxIABBGHZycjYC3IkBQQBBACgC2IkBIgBBGHQgAEGA/gNxQQh0ciAAQQh2QYD+A3EgAEEYdnJyNgLYiQFBAEEAKALUiQEiAEEYdCAAQYD+A3FBCHRyIABBCHZBgP4DcSAAQRh2cnI2AtSJAUEAQQAoAtCJASIAQRh0IABBgP4DcUEIdHIgAEEIdkGA/gNxIABBGHZycjYC0IkBQQBBACgCzIkBIgBBGHQgAEGA/gNxQQh0ciAAQQh2QYD+A3EgAEEYdnJyNgLMiQFBAEEAKALIiQEiAEEYdCAAQYD+A3FBCHRyIABBCHZBgP4DcSAAQRh2cnI2AsiJAQJAQQAoAuiJASICRQ0AQQAhAANAIAFBgAlqIAFByIkBai0AADoAACABQQFqIQEgAiAAQQFqIgBB/wFxSw0ACwsLBgBBgIkBC6MBAEEAQgA3A8CJAUEAQRxBICABQeABRiIBGzYC6IkBQQBCp5/mp8b0k/2+f0Krs4/8kaOz8NsAIAEbNwPgiQFBAEKxloD+n6KFrOgAQv+kuYjFkdqCm38gARs3A9iJAUEAQpe6w4OTp5aHd0Ly5rvjo6f9p6V/IAEbNwPQiQFBAELYvZaI/KC1vjZC58yn0NbQ67O7fyABGzcDyIkBIAAQAhAECwsLAQBBgAgLBHAAAAA=`,hash:`8c18dd94`};new JF,new JF;function fI(){return uI(dI,32).then(e=>{e.init(256);let t={init:()=>(e.init(256),t),update:n=>(e.update(n),t),digest:t=>e.digest(t),save:()=>e.save(),load:n=>(e.load(n),t),blockSize:64,digestSize:32};return t})}new JF,new JF,new JF,new JF,new JF,new JF,new JF,new JF,new JF;var pI={source:{repo:`openbmb/MiniCPM5-2B`,revision:`abe115e887989b14f05e64a3b260648329324c3f`,files:{"config.json":{bytes:704,sha256:`59613157e5357d62bcb121e04cb90f2170b43d789b142380c12c3d4277d95180`},"generation_config.json":{bytes:213,sha256:`9ac4f32e5f32358697a9f438a3ea89ef80e6ba786c72c49e932f9f21c122fdb1`},"tokenizer.json":{bytes:9894271,sha256:`3e065a558a034185fe299917b398685c1facd0169a9eea1e629eb30c171fed81`},"tokenizer_config.json":{bytes:94391,sha256:`e9b1064649e771d7a8e15637c68b2d2749724877ba3648bd74a4ece31c26303b`},"special_tokens_map.json":{bytes:551,sha256:`82d96d7a9e6ced037f12394b7ea6a5b02e6ca87e0d11edaa8d60d9be857ce7db`},"chat_template.jinja":{bytes:9060,sha256:`cc945752db555d60949b16989df4ccfeb52a313d6b4b5c5229dd786e2e9fcf1c`},"model.safetensors.index.json":{bytes:31378,sha256:`6d839cd76e8395de548a0e6cc310386f66d1ecbb2c75d198a8dfd3d70892b756`},"model-00000-of-00001.safetensors":{bytes:5033557096,sha256:`14fb8e7f0a18d53d1f239773758bf581cee7e456a4523a54622c3a245b64402c`}}},changes:[`last-position LM head at export`,`four lossless embedding column shards`,`concrete cache head dimensions`,`template serialization and compatibility`],graph_nodes:480,external_chunks:7,files:{"chat_template.jinja":{bytes:8154,sha256:`48636abac6ea1ae7442893ee234e55cce5d45c770ddcc87476555fbf4efde8fe`},"config.json":{bytes:822,sha256:`9103173d5af7567b80f15914f95205652f6475f459e843fdc47a4bbb5bdadade`},"generation_config.json":{bytes:213,sha256:`9ac4f32e5f32358697a9f438a3ea89ef80e6ba786c72c49e932f9f21c122fdb1`},"onnx/model_q4f16.onnx":{bytes:318519,sha256:`d83a86b8ae2566b5bdde23fae366f94a35383f3aefdf3300f138e6dde4ad9d57`},"onnx/model_q4f16.onnx_data":{bytes:265703424,sha256:`57ad7c0aef4bdb7ea57ae34f5f2327b88de701c65b52a45b5dc94ff9af1bb985`},"onnx/model_q4f16.onnx_data_1":{bytes:265420800,sha256:`19e766345e32a1f1162ab1d418583d94643c01c5ea89b4160c1e68afeca5cfe4`},"onnx/model_q4f16.onnx_data_2":{bytes:265420800,sha256:`a83508febe793e70a5c2ce13d7fe029ee5116f33d69863c75a17343caf72ca56`},"onnx/model_q4f16.onnx_data_3":{bytes:265420800,sha256:`5d5e46728e6101139e5e8527a0d192a5552393d74f6075f7ffee28fd5881ef0b`},"onnx/model_q4f16.onnx_data_4":{bytes:237109248,sha256:`62fe730b14bc33fce8fafa4797b43579abc9b366ec30fb966ba9daad8243be5a`},"onnx/model_q4f16.onnx_data_5":{bytes:267386880,sha256:`87c6ba0cd37a3bbbbcba46f33a4adf44214ad9d06854e6cd49e67a03769c1df1`},"onnx/model_q4f16.onnx_data_6":{bytes:267386880,sha256:`1b054f4046373d1a4f8c4a70421472e4f6b8fc419151e6911ffe33f8614bb77c`},"special_tokens_map.json":{bytes:551,sha256:`82d96d7a9e6ced037f12394b7ea6a5b02e6ca87e0d11edaa8d60d9be857ce7db`},"tokenizer.json":{bytes:9894271,sha256:`3e065a558a034185fe299917b398685c1facd0169a9eea1e629eb30c171fed81`},"tokenizer_config.json":{bytes:102804,sha256:`36b50abe63f32fc16e21a2ab30af359601915c6d2e58d7466629458adc2492a1`}}};const mI=`04a6c49fcba3a65a0351c92644c3a7e9d4343059`,hI=`Mike0021/MiniCPM5-2B-ONNX`,gI=Object.values(pI.files).reduce((e,t)=>e+t.bytes,0),_I=32*1024**2,vI=(e,t)=>new Promise((n,r)=>{t?.throwIfAborted();let i=()=>{clearTimeout(a),r(t.reason)},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})});async function yI(e,t,n,r,i){for(let a=0;;a++)try{let a=r>_I,o=await fetch(e,{headers:a?{Range:`bytes=${t}-${n}`}:{},signal:AbortSignal.any([i,AbortSignal.timeout(9e4)]),cache:`no-store`});if(!o.ok)throw Error(`Download returned HTTP ${o.status}`);if(a&&o.status!==206)throw await o.body?.cancel(),Error(`The model host did not honor byte ranges.`);let s=o.headers.get(`Content-Range`);if(s&&s!==`bytes ${t}-${n}/${r}`)throw await o.body?.cancel(),Error(`Incorrect download range.`);let c=new Uint8Array(await o.arrayBuffer());if(c.length!==n-t+1)throw Error(`Incomplete download chunk.`);return c}catch(e){if(i.throwIfAborted(),a===2)throw e;await vI(500*2**a,i)}}async function bI(e,t){return navigator.locks?navigator.locks.request(`pi-minicpm5-download-`+mI,{signal:t.signal},()=>wI(e,t)):wI(e,t)}async function xI(e=!1){if(!navigator.storage?.getDirectory)throw Error(`This app needs browser file storage (OPFS) to cache the 1.84 GB model. Open it in a regular browser tab.`);let t=await(await navigator.storage.getDirectory()).getDirectoryHandle(`pi-minicpm5-`+mI,{create:e}),n=await t.getFileHandle(`verified.json`,{create:e}),r;try{r=JSON.parse(await(await n.getFile()).text())}catch{r={}}(!r||typeof r!=`object`||Array.isArray(r))&&(r={});let i=0,a=[],o=e=>encodeURIComponent(e);for(let[e,n]of Object.entries(pI.files)){try{let a=await(await t.getFileHandle(o(e))).getFile(),s=r[e];if(a.size===n.bytes&&s?.sha256===n.sha256&&s.modified===a.lastModified){i+=n.bytes;continue}}catch(e){if(e.name!==`NotFoundError`)throw e}a.push([e,n])}return{root:t,receiptsFile:n,receipts:r,pending:a,cached:i}}async function SI(){try{return(await xI()).pending.length===0}catch{return!1}}function CI(){return Object.assign(Error(`The saved model is incomplete. Confirm the download to restore it.`),{code:`MODEL_CACHE_MISS`})}async function wI(e,{signal:t,cachedOnly:n=!1,onProgress:r=()=>{}}){let i;try{i=await xI(!n)}catch(e){throw n&&e.name===`NotFoundError`?CI():e}let{root:a,receiptsFile:o,receipts:s,pending:c,cached:l}=i;if(n&&c.length)throw CI();let u=l,d=e=>encodeURIComponent(e);if(r({phase:`download`,loaded:u,total:gI,cached:l}),c.length){let e=await navigator.storage.estimate();if(e.quota&&e.quota-e.usage{let e=JSON.stringify(s),t=m.then(async()=>{let t=await o.createWritable();await t.write(e),await t.close()});return m=t.catch(()=>{}),t};async function g(){for(;c.length;){p.throwIfAborted();let[t,n]=c.shift(),i=await a.getFileHandle(d(t),{create:!0}),o=await i.createWritable();try{let a=await fI();a.init();for(let i=0;i{}),f.abort(e),e}}}let _=(await Promise.allSettled(Array.from({length:6},g))).find(e=>e.status===`rejected`);if(_)throw _.reason;return await m,{cachedBytes:l,async match(t){let n=typeof t==`string`?t:t.url;if(!n.startsWith(e))return;let r=n.slice(e.length);if(!Object.hasOwn(pI.files,r))return;let i=await(await a.getFileHandle(d(r))).getFile();return new Response(i,{headers:{"Content-Length":String(i.size)}})},async put(){}}}var TI=t((e=>{function t(e,t,n){if(n===void 0&&(n=Array.prototype),e&&typeof n.find==`function`)return n.find.call(e,t);for(var i=0;i-1}var _=n({HTML:`http://www.w3.org/1999/xhtml`,SVG:`http://www.w3.org/2000/svg`,XML:`http://www.w3.org/XML/1998/namespace`,XMLNS:`http://www.w3.org/2000/xmlns/`});e.assign=i,e.find=t,e.freeze=n,e.HTML_BOOLEAN_ATTRIBUTES=a,e.HTML_RAW_TEXT_ELEMENTS=l,e.HTML_VOID_ELEMENTS=s,e.hasDefaultHTMLNamespace=p,e.hasOwn=r,e.isHTMLBooleanAttribute=o,e.isHTMLRawTextElement=u,e.isHTMLEscapableRawTextElement=d,e.isHTMLMimeType=f,e.isHTMLVoidElement=c,e.isValidMimeType=g,e.MIME_TYPE=m,e.NAMESPACE=_})),EI=t((e=>{var t=TI();function n(e,t){e.prototype=Object.create(Error.prototype,{constructor:{value:e},name:{value:e.name,enumerable:!0,writable:t}})}var r=t.freeze({Error:`Error`,IndexSizeError:`IndexSizeError`,DomstringSizeError:`DomstringSizeError`,HierarchyRequestError:`HierarchyRequestError`,WrongDocumentError:`WrongDocumentError`,InvalidCharacterError:`InvalidCharacterError`,NoDataAllowedError:`NoDataAllowedError`,NoModificationAllowedError:`NoModificationAllowedError`,NotFoundError:`NotFoundError`,NotSupportedError:`NotSupportedError`,InUseAttributeError:`InUseAttributeError`,InvalidStateError:`InvalidStateError`,SyntaxError:`SyntaxError`,InvalidModificationError:`InvalidModificationError`,NamespaceError:`NamespaceError`,InvalidAccessError:`InvalidAccessError`,ValidationError:`ValidationError`,TypeMismatchError:`TypeMismatchError`,SecurityError:`SecurityError`,NetworkError:`NetworkError`,AbortError:`AbortError`,URLMismatchError:`URLMismatchError`,QuotaExceededError:`QuotaExceededError`,TimeoutError:`TimeoutError`,InvalidNodeTypeError:`InvalidNodeTypeError`,DataCloneError:`DataCloneError`,EncodingError:`EncodingError`,NotReadableError:`NotReadableError`,UnknownError:`UnknownError`,ConstraintError:`ConstraintError`,DataError:`DataError`,TransactionInactiveError:`TransactionInactiveError`,ReadOnlyError:`ReadOnlyError`,VersionError:`VersionError`,OperationError:`OperationError`,NotAllowedError:`NotAllowedError`,OptOutError:`OptOutError`}),i=Object.keys(r);function a(e){return typeof e==`number`&&e>=1&&e<=25}function o(e){return typeof e==`string`&&e.substring(e.length-r.Error.length)===r.Error}function s(e,t){a(e)?(this.name=i[e],this.message=t||``):(this.message=e,this.name=o(t)?t:r.Error),Error.captureStackTrace&&Error.captureStackTrace(this,s)}n(s,!0),Object.defineProperties(s.prototype,{code:{enumerable:!0,get:function(){var e=i.indexOf(this.name);return a(e)?e:0}}});for(var c={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25},l=Object.entries(c),u=0;u{function t(e){try{typeof e!=`function`&&(e=RegExp);var t=new e(`𝌆`,`u`).exec(`𝌆`);return!!t&&t[0].length===2}catch{}return!1}var n=t();function r(e){if(e.source[0]!==`[`)throw Error(e+` can not be used with chars`);return e.source.slice(1,e.source.lastIndexOf(`]`))}function i(e,t){if(e.source[0]!==`[`)throw Error(`/`+e.source+`/ can not be used with chars_without`);if(!t||typeof t!=`string`)throw Error(JSON.stringify(t)+` is not a valid search`);if(e.source.indexOf(t)===-1)throw Error(`"`+t+`" is not is /`+e.source+`/`);if(t===`-`&&e.source.indexOf(t)!==1)throw Error(`"`+t+`" is not at the first postion of /`+e.source+`/`);return new RegExp(e.source.replace(t,``),n?`u`:``)}function a(e){var t=this;return new RegExp(Array.prototype.slice.call(arguments).map(function(e){var n=typeof e==`string`;if(n&&t===void 0&&e===`|`)throw Error("use regg instead of reg to wrap expressions with `|`!");return n?e:e.source}).join(``),n?`u`:``)}function o(e){if(arguments.length===0)throw Error(`no parameters provided`);return a.apply(o,[`(?:`].concat(Array.prototype.slice.call(arguments),[`)`]))}var s=`�`,c=/[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/;n&&(c=a(`[`,r(c),`\\u{10000}-\\u{10FFFF}`,`]`));var l=RegExp(`[^`+r(c)+`]`,n?`u`:``),u=/[\x20\x09\x0D\x0A]/,d=r(u),f=a(u,`+`),p=a(u,`*`),m=/[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;n&&(m=a(`[`,r(m),`\\u{10000}-\\u{10FFFF}`,`]`));var h=a(`[`,r(m),r(/[-.0-9\xB7]/),r(/[\u0300-\u036F\u203F-\u2040]/),`]`),g=a(m,h,`*`),_=a(`^`,g,`$`),v=a(h,`+`),y=o(a(`&`,g,`;`),`|`,o(/&#[0-9]+;|&#x[0-9a-fA-F]+;/)),b=a(`%`,g,`;`),x=o(a(`"`,o(/[^%&"]/,`|`,b,`|`,y),`*`,`"`),`|`,a(`'`,o(/[^%&']/,`|`,b,`|`,y),`*`,`'`)),S=o(`"`,o(/[^<&"]/,`|`,y),`*`,`"`,`|`,`'`,o(/[^<&']/,`|`,y),`*`,`'`),C=a(i(m,`:`),i(h,`:`),`*`),w=a(`^`,C,`$`),T=a(C,o(`:`,C),`?`),E=a(`^`,T,`$`),D=a(`(`,T,`)`),O=o(/"[^"]*"|'[^']*'/),k=a(/^<\?/,`(`,g,`)`,o(f,`(?!`,u,`)(`,c,`*?)`),`?`,/\?>/),A=/[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/,j=o(`"`,A,`*"`,`|`,`'`,i(A,`'`),`*'`),M=``,te=a(M,o(i(c,`-`),`|`,a(`-`,i(c,`-`))),`*`,ee),N=`#PCDATA`,ne=o(`EMPTY`,`|`,`ANY`,`|`,o(a(/\(/,p,N,o(p,/\|/,p,T),`*`,p,/\)\*/),`|`,a(/\(/,p,N,p,/\)/)),`|`,a(/\([^>]+\)/,/[?*+]?/)),re=a(``),ie=a(``),ae=`about:legacy-compat`,oe=o(`"`+ae+`"`,`|`,`'`+ae+`'`),se=`SYSTEM`,ce=`PUBLIC`,le=o(o(se,f,O),`|`,o(ce,f,j,f,O)),ue=a(`^`,o(o(se,f,`(?`,O,`)`),`|`,o(ce,f,`(?`,j,`)`,f,`(?`,O,`)`))),de=a(`^`,j,`$`),fe=a(`^`,O,`$`),pe=o(x,`|`,o(le,o(f,`NDATA`,f,g),`?`)),me=``),`|`,a(me,f,`%`,f,g,f,o(x,`|`,le),p,`>`)),P=a(``),ge=a(p,`=`,p),_e=/1[.]\d+/,F=a(f,`version`,ge,o(`'`,_e,`'`,`|`,`"`,_e,`"`)),ve=/[A-Za-z][-A-Za-z0-9._]*/,ye=a(/^<\?xml/,F,o(f,`encoding`,ge,o(`"`,ve,`"`,`|`,`'`,ve,`'`)),`?`,o(f,`standalone`,ge,o(`'`,o(`yes`,`|`,`no`),`'`,`|`,`"`,o(`yes`,`|`,`no`),`"`)),`?`,p,/\?>/),be=``,Ce=a(//));e.chars=r,e.chars_without=i,e.detectUnicodeSupport=t,e.reg=a,e.regg=o,e.ABOUT_LEGACY_COMPAT=ae,e.ABOUT_LEGACY_COMPAT_SystemLiteral=oe,e.AttlistDecl=ie,e.CDATA_START=xe,e.CDATA_END=Se,e.CDSect=Ce,e.Char=c,e.Comment=te,e.COMMENT_START=M,e.COMMENT_END=ee,e.DOCTYPE_DECL_START=be,e.elementdecl=re,e.EntityDecl=he,e.EntityValue=x,e.ExternalID=le,e.ExternalID_match=ue,e.Name=g,e.Name_exact=_,e.NCName_exact=w,e.NotationDecl=P,e.Reference=y,e.PEReference=b,e.PI=k,e.PUBLIC=ce,e.PubidLiteral=j,e.PubidLiteral_match=de,e.QName=T,e.QName_exact=E,e.QName_group=D,e.S=f,e.SChar_s=d,e.S_OPT=p,e.SYSTEM=se,e.SystemLiteral=O,e.SystemLiteral_match=fe,e.InvalidChar=l,e.UNICODE_REPLACEMENT_CHARACTER=s,e.UNICODE_SUPPORT=n,e.XMLDecl=ye})),OI=t((e=>{var t=TI(),n=t.find,r=t.hasDefaultHTMLNamespace,i=t.hasOwn,a=t.isHTMLMimeType,o=t.isHTMLRawTextElement,s=t.isHTMLVoidElement,c=t.MIME_TYPE,l=t.NAMESPACE,u=Symbol(),d=EI(),f=d.DOMException,p=d.DOMExceptionName,m=DI();function h(e){if(e!==u)throw TypeError(`Illegal constructor`)}function g(e){return e!==``}function _(e){return e?e.split(/[\t\n\f\r ]+/).filter(g):[]}function v(e,t){return i(e,t)||(e[t]=!0),e}function y(e){if(!e)return[];var t=_(e);return Object.keys(t.reduce(v,{}))}function b(e){return function(t){return e&&e.indexOf(t)!==-1}}function x(e){if(!m.QName_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`invalid character in qualified name "`+e+`"`)}function S(e,n){x(n),e||=null;var r=null,i=n;if(n.indexOf(`:`)>=0){var a=n.split(`:`);r=a[0],i=a[1]}if(r!==null&&e===null)throw new f(f.NAMESPACE_ERR,`prefix is non-null and namespace is null`);if(r===`xml`&&e!==t.NAMESPACE.XML)throw new f(f.NAMESPACE_ERR,`prefix is "xml" and namespace is not the XML namespace`);if((r===`xmlns`||n===`xmlns`)&&e!==t.NAMESPACE.XMLNS)throw new f(f.NAMESPACE_ERR,`either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace`);if(e===t.NAMESPACE.XMLNS&&r!==`xmlns`&&n!==`xmlns`)throw new f(f.NAMESPACE_ERR,`namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"`);return[e,r,i]}function C(e,t){for(var n in e)i(e,n)&&(t[n]=e[n])}function w(e,t){var n=e.prototype;if(!(n instanceof t)){function r(){}r.prototype=t.prototype,r=new r,C(n,r),e.prototype=n=r}n.constructor!=e&&(typeof e!=`function`&&console.error(`unknown Class:`+e),n.constructor=e)}var T={},E=T.ELEMENT_NODE=1,D=T.ATTRIBUTE_NODE=2,O=T.TEXT_NODE=3,k=T.CDATA_SECTION_NODE=4,A=T.ENTITY_REFERENCE_NODE=5,j=T.ENTITY_NODE=6,M=T.PROCESSING_INSTRUCTION_NODE=7,ee=T.COMMENT_NODE=8,te=T.DOCUMENT_NODE=9,N=T.DOCUMENT_TYPE_NODE=10,ne=T.DOCUMENT_FRAGMENT_NODE=11,re=T.NOTATION_NODE=12,ie=t.freeze({DOCUMENT_POSITION_DISCONNECTED:1,DOCUMENT_POSITION_PRECEDING:2,DOCUMENT_POSITION_FOLLOWING:4,DOCUMENT_POSITION_CONTAINS:8,DOCUMENT_POSITION_CONTAINED_BY:16,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC:32});function ae(e,t){if(t.length=0&&e=0){for(var i=t.length-1;r<=i;)t[r]=t[++r];if(t.length=i,he(t,n),e){var a=e.ownerDocument;a&&Ce(a,e,n),n.ownerElement=null}}}ue.prototype={length:0,item:se.prototype.item,getNamedItem:function(e){this._ownerElement&&this._ownerElement._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase());for(var t=0;t0;){var n=t.pop(),r=n.node,i=n.other;if(r.nodeType!==i.nodeType)return!1;switch(r.nodeType){case r.DOCUMENT_TYPE_NODE:if(r.name!==i.name||r.publicId!==i.publicId||r.systemId!==i.systemId)return!1;break;case r.ELEMENT_NODE:if(r.namespaceURI!==i.namespaceURI||r.prefix!==i.prefix||r.localName!==i.localName||r.attributes.length!==i.attributes.length)return!1;for(var a=0;a=0;a--)t.push({node:r.childNodes[a],other:i.childNodes[a]})}return!0},isSameNode:function(e){return this===e},insertBefore:function(e,t){return Ie(this,e,t)},replaceChild:function(e,t){Ie(this,e,t,Fe),t&&this.removeChild(t)},removeChild:function(e){return Te(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return tt(this.ownerDocument||this,this,e)},normalize:function(){be(this,null,{enter:function(e){for(var t=e.firstChild;t;){var n=t.nextSibling;if(n!==null&&n.nodeType===O&&t.nodeType===O){for(var r=[],i=n;i!==null&&i.nodeType===O;)r.push(i.data),i=i.nextSibling;for(var a=t.nextSibling;a!==i;){var o=a.nextSibling;a.parentNode=null,a.previousSibling=null,a.nextSibling=null,a=o}t.nextSibling=i,i===null?e.lastChild=t:i.previousSibling=t,t.appendData(r.join(``)),we(e.ownerDocument,e),t=i}else t=n}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},lookupPrefix:function(e){for(var t=this;t;){var n=t._nsMap;if(n){for(var r in n)if(i(n,r)&&n[r]===e)return r}t=t.nodeType==D?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var n=t._nsMap;if(n&&i(n,e))return n[e];t=t.nodeType==D?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){return this.lookupPrefix(e)==null},compareDocumentPosition:function(e){if(this===e)return 0;var t=e,n=this,r=null,i=null;if(t instanceof Re&&(r=t,t=r.ownerElement),n instanceof Re&&(i=n,n=i.ownerElement,r&&t&&n===t))for(var a=0,o;o=n.attributes[a];a++){if(o===r)return ie.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+ie.DOCUMENT_POSITION_PRECEDING;if(o===i)return ie.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+ie.DOCUMENT_POSITION_FOLLOWING}if(!t||!n||n.ownerDocument!==t.ownerDocument)return ie.DOCUMENT_POSITION_DISCONNECTED+ie.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+(oe(n.ownerDocument)>oe(t.ownerDocument)?ie.DOCUMENT_POSITION_FOLLOWING:ie.DOCUMENT_POSITION_PRECEDING);if(i&&t===n)return ie.DOCUMENT_POSITION_CONTAINS+ie.DOCUMENT_POSITION_PRECEDING;if(r&&t===n)return ie.DOCUMENT_POSITION_CONTAINED_BY+ie.DOCUMENT_POSITION_FOLLOWING;for(var s=[],c=t.parentNode;c;){if(!i&&c===n)return ie.DOCUMENT_POSITION_CONTAINED_BY+ie.DOCUMENT_POSITION_FOLLOWING;s.push(c),c=c.parentNode}s.reverse();for(var l=[],u=n.parentNode;u;){if(!r&&u===t)return ie.DOCUMENT_POSITION_CONTAINS+ie.DOCUMENT_POSITION_PRECEDING;l.push(u),u=u.parentNode}l.reverse();var d=ae(s,l);for(var f in d.childNodes){var p=d.childNodes[f];if(p===n)return ie.DOCUMENT_POSITION_FOLLOWING;if(p===t)return ie.DOCUMENT_POSITION_PRECEDING;if(l.indexOf(p)>=0)return ie.DOCUMENT_POSITION_FOLLOWING;if(s.indexOf(p)>=0)return ie.DOCUMENT_POSITION_PRECEDING}return 0}};function ve(e){return e==`<`&&`<`||e==`>`&&`>`||e==`&`&&`&`||e==`"`&&`"`||`&#`+e.charCodeAt()+`;`}C(T,F),C(T,F.prototype),C(ie,F),C(ie,F.prototype);function ye(e,t){be(e,null,{enter:function(e){return!t(e)||be.STOP}})}function be(e,t,n){for(var r=[{node:e,context:t,phase:be.ENTER}];r.length>0;){var i=r.pop();if(i.phase===be.ENTER){var a=n.enter(i.node,i.context);if(a===be.STOP)return be.STOP;if(r.push({node:i.node,context:a,phase:be.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)r.push({node:o,context:a,phase:be.ENTER}),o=o.previousSibling}else n.exit&&n.exit(i.node,i.context)}}be.STOP=Symbol(`walkDOM.STOP`),be.ENTER=0,be.EXIT=1;function xe(e,t){h(e);var n=t||{};this.ownerDocument=this,this.contentType=n.contentType||c.XML_APPLICATION,this.type=a(this.contentType)?`html`:`xml`}function Se(e,t,n){e&&e._inc++,n.namespaceURI===l.XMLNS&&(t._nsMap[n.prefix?n.localName:``]=n.value)}function Ce(e,t,n,r){e&&e._inc++,n.namespaceURI===l.XMLNS&&delete t._nsMap[n.prefix?n.localName:``]}function we(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n&&!n.nextSibling)r[r.length++]=n;else{for(var i=t.firstChild,a=0;i;)r[a++]=i,i=i.nextSibling;r.length=a,delete r[r.length]}}}function Te(e,t){if(e!==t.parentNode)throw new f(f.NOT_FOUND_ERR,`child's parent is not parent`);var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,we(e.ownerDocument,e),t.parentNode=null,t.previousSibling=null,t.nextSibling=null,t}function Ee(e){return e&&(e.nodeType===F.DOCUMENT_NODE||e.nodeType===F.DOCUMENT_FRAGMENT_NODE||e.nodeType===F.ELEMENT_NODE)}function De(e){return e&&(e.nodeType===F.CDATA_SECTION_NODE||e.nodeType===F.COMMENT_NODE||e.nodeType===F.DOCUMENT_FRAGMENT_NODE||e.nodeType===F.DOCUMENT_TYPE_NODE||e.nodeType===F.ELEMENT_NODE||e.nodeType===F.PROCESSING_INSTRUCTION_NODE||e.nodeType===F.TEXT_NODE)}function Oe(e){return e&&e.nodeType===F.DOCUMENT_TYPE_NODE}function ke(e){return e&&e.nodeType===F.ELEMENT_NODE}function Ae(e){return e&&e.nodeType===F.TEXT_NODE}function je(e,t){var r=e.childNodes||[];if(n(r,ke)||Oe(t))return!1;var i=n(r,Oe);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function Me(e,t){var r=e.childNodes||[];function i(e){return ke(e)&&e!==t}if(n(r,i))return!1;var a=n(r,Oe);return!(t&&a&&r.indexOf(a)>r.indexOf(t))}function Ne(e,t,n){if(!Ee(e))throw new f(f.HIERARCHY_REQUEST_ERR,`Unexpected parent node type `+e.nodeType);if(n&&n.parentNode!==e)throw new f(f.NOT_FOUND_ERR,`child not in parent`);if(!De(t)||Oe(t)&&e.nodeType!==F.DOCUMENT_NODE)throw new f(f.HIERARCHY_REQUEST_ERR,`Unexpected node type `+t.nodeType+` for parent node type `+e.nodeType)}function Pe(e,t,r){var i=e.childNodes||[],a=t.childNodes||[];if(t.nodeType===F.DOCUMENT_FRAGMENT_NODE){var o=a.filter(ke);if(o.length>1||n(a,Ae))throw new f(f.HIERARCHY_REQUEST_ERR,`More than one element or text in fragment`);if(o.length===1&&!je(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Element in fragment can not be inserted before doctype`)}if(ke(t)&&!je(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one element can be added and only after doctype`);if(Oe(t)){if(n(i,Oe))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one doctype is allowed`);var s=n(i,ke);if(r&&i.indexOf(s)1||n(a,Ae))throw new f(f.HIERARCHY_REQUEST_ERR,`More than one element or text in fragment`);if(o.length===1&&!Me(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Element in fragment can not be inserted before doctype`)}if(ke(t)&&!Me(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one element can be added and only after doctype`);if(Oe(t)){function e(e){return Oe(e)&&e!==r}if(n(i,e))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one doctype is allowed`);var s=n(i,ke);if(r&&i.indexOf(s)`)!==-1)throw new f(f.INVALID_CHARACTER_ERR,`data contains "]]>"`);var t=new He(u);return t.ownerDocument=this,t.childNodes=new se,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new Je(u);return n.ownerDocument=this,n.childNodes=new se,n.nodeName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){if(!m.QName_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`invalid character in name "`+e+`"`);return this.type===`html`&&(e=e.toLowerCase()),this._createAttribute(e)},_createAttribute:function(e){var t=new Re(u);return t.ownerDocument=this,t.childNodes=new se,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!m.Name_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`not a valid xml name "`+e+`"`);if(this.type===`html`)throw new f(`document is an html document`,p.NotSupportedError);var t=new Ke(u);return t.ownerDocument=this,t.childNodes=new se,t.nodeName=e,t},createElementNS:function(e,t){var n=S(e,t),r=new Le(u),i=r.attributes=new ue;return r.childNodes=new se,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=n[0],r.prefix=n[1],r.localName=n[2],i._ownerElement=r,r},createAttributeNS:function(e,t){var n=S(e,t),r=new Re(u);return r.ownerDocument=this,r.childNodes=new se,r.nodeName=t,r.name=t,r.specified=!0,r.namespaceURI=n[0],r.prefix=n[1],r.localName=n[2],r}},w(xe,F);function Le(e){h(e),this._nsMap=Object.create(null)}Le.prototype={nodeType:E,attributes:null,getQualifiedName:function(){return this.prefix?this.prefix+`:`+this.localName:this.localName},_isInHTMLDocumentAndNamespace:function(){return this.ownerDocument.type===`html`&&this.namespaceURI===l.HTML},hasAttributes:function(){return!!(this.attributes&&this.attributes.length)},hasAttribute:function(e){return!!this.getAttributeNode(e)},getAttribute:function(e){var t=this.getAttributeNode(e);return t?t.value:null},getAttributeNode:function(e){return this._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase()),this.attributes.getNamedItem(e)},setAttribute:function(e,t){this._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase());var n=this.getAttributeNode(e);n?n.value=n.nodeValue=``+t:(n=this.ownerDocument._createAttribute(e),n.value=n.nodeValue=``+t,this.setAttributeNode(n))},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n?n.value:null},setAttributeNS:function(e,t,n){var r=S(e,t)[2],i=this.getAttributeNodeNS(e,r);i?i.value=i.nodeValue=``+n:(i=this.ownerDocument.createAttributeNS(e,t),i.value=i.nodeValue=``+n,this.setAttributeNode(i))},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByClassName:function(e){var t=y(e);return new ce(this,function(n){var r=[];return t.length>0&&ye(n,function(i){if(i!==n&&i.nodeType===E){var a=i.getAttribute(`class`);if(a){var o=e===a;if(!o){var s=y(a);o=t.every(b(s))}o&&r.push(i)}}}),r})},getElementsByTagName:function(e){var t=(this.nodeType===te?this:this.ownerDocument).type===`html`,n=e.toLowerCase();return new ce(this,function(r){var i=[];return ye(r,function(a){a!==r&&a.nodeType===E&&(e===`*`||a.getQualifiedName()===(t&&a.namespaceURI===l.HTML?n:e))&&i.push(a)}),i})},getElementsByTagNameNS:function(e,t){return new ce(this,function(n){var r=[];return ye(n,function(i){i!==n&&i.nodeType===E&&(e===`*`||i.namespaceURI===e)&&(t===`*`||i.localName==t)&&r.push(i)}),r})}},xe.prototype.getElementsByClassName=Le.prototype.getElementsByClassName,xe.prototype.getElementsByTagName=Le.prototype.getElementsByTagName,xe.prototype.getElementsByTagNameNS=Le.prototype.getElementsByTagNameNS,w(Le,F);function Re(e){h(e),this.namespaceURI=null,this.prefix=null,this.ownerElement=null}Re.prototype.nodeType=D,w(Re,F);function ze(e){h(e)}ze.prototype={data:``,substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},deleteData:function(e,t){this.replaceData(e,t,``)},replaceData:function(e,t,n){var r=this.data.substring(0,e),i=this.data.substring(e+t);n=r+n+i,this.nodeValue=this.data=n,this.length=n.length}},w(ze,F);function Be(e){h(e)}Be.prototype={nodeName:`#text`,nodeType:O,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}},w(Be,ze);function Ve(e){h(e)}Ve.prototype={nodeName:`#comment`,nodeType:ee},w(Ve,ze);function He(e){h(e)}He.prototype={nodeName:`#cdata-section`,nodeType:k},w(He,Be);function Ue(e){h(e)}Ue.prototype.nodeType=N,w(Ue,F);function We(e){h(e)}We.prototype.nodeType=re,w(We,F);function Ge(e){h(e)}Ge.prototype.nodeType=j,w(Ge,F);function Ke(e){h(e)}Ke.prototype.nodeType=A,w(Ke,F);function qe(e){h(e)}qe.prototype.nodeName=`#document-fragment`,qe.prototype.nodeType=ne,w(qe,F);function Je(e){h(e)}Je.prototype.nodeType=M,w(Je,ze);function Ye(){}Ye.prototype.serializeToString=function(e,t){return Xe.call(e,t)},F.prototype.toString=Xe;function Xe(e){var t=typeof e==`function`?{requireWellFormed:!1,splitCDATASections:!0,nodeFilter:e}:e==null?{requireWellFormed:!1,splitCDATASections:!0,nodeFilter:null}:{requireWellFormed:!!e.requireWellFormed,splitCDATASections:e.splitCDATASections!==!1,nodeFilter:e.nodeFilter||null},n=[],r=this.nodeType===te&&this.documentElement||this,i=r.prefix,a=r.namespaceURI;if(a&&i==null){var i=r.lookupPrefix(a);if(i==null)var o=[{namespace:a,prefix:null}]}return $e(this,n,o,t),n.join(``)}function Ze(e,t,n){var r=e.prefix||``,i=e.namespaceURI;if(!i||r===`xml`&&i===l.XML||i===l.XMLNS)return!1;for(var a=n.length;a--;){var o=n[a];if(o.prefix===r)return o.namespace!==i}return!0}function Qe(e,t,n,r){if(r&&!m.QName_exact.test(t))throw new f(`The attribute name "`+t+`" is not a valid XML QName`,p.InvalidStateError);e.push(` `,t,`="`,n.replace(/[<>&"\t\n\r]/g,ve),`"`)}function $e(e,t,n,r){n||=[];var i=r.nodeFilter,a=r.requireWellFormed,c=r.splitCDATASections,u=(e.nodeType===te?e:e.ownerDocument).type===`html`;be(e,{ns:n},{enter:function(e,n){var d=n.ns;if(i){if(e=i(e),e){if(typeof e==`string`)return t.push(e),null}else return null}switch(e.nodeType){case E:var h=e.attributes,g=h.length,_=e.tagName,v=_;if(!u&&!e.prefix&&e.namespaceURI){for(var y,b=0;b=0;x--){var S=d[x];if(S.prefix===``&&S.namespace===e.namespaceURI){y=S.namespace;break}}if(y!==e.namespaceURI)for(var x=d.length-1;x>=0;x--){var S=d[x];if(S.namespace===e.namespaceURI){S.prefix&&(v=S.prefix+`:`+_);break}}}if(a&&!m.QName_exact.test(v))throw new f(`The element name "`+v+`" is not a valid XML QName`,p.InvalidStateError);t.push(`<`,v);for(var C=d.slice(),w=0;w`),null;if(t.push(`>`),u&&o(_)){for(var se=e.firstChild;se;)se.data?t.push(se.data):$e(se,t,C.slice(),r),se=se.nextSibling;return t.push(``),null}return{ns:C,tag:v};case te:case ne:if(a&&e.nodeType===te&&e.documentElement==null)throw new f(`The Document has no documentElement`,p.InvalidStateError);return{ns:d};case D:return Qe(t,e.name,e.value,a),null;case O:if(a&&m.InvalidChar.test(e.data))throw new f(`The Text node data contains characters outside the XML Char production`,p.InvalidStateError);return t.push(e.data.replace(/[<&>]/g,ve)),null;case k:if(a&&e.data.indexOf(`]]>`)!==-1)throw new f(`The CDATASection data contains "]]>"`,p.InvalidStateError);return c?t.push(m.CDATA_START,e.data.replace(/]]>/g,`]]]]>`),m.CDATA_END):t.push(m.CDATA_START,e.data,m.CDATA_END),null;case ee:if(a){if(m.InvalidChar.test(e.data))throw new f(`The comment node data contains characters outside the XML Char production`,p.InvalidStateError);if(e.data.indexOf(`--`)!==-1||e.data[e.data.length-1]===`-`)throw new f(`The comment node data contains "--" or ends with "-"`,p.InvalidStateError)}return t.push(m.COMMENT_START,e.data,m.COMMENT_END),null;case N:var ce=e.publicId,le=e.systemId;if(a){if(!m.Name_exact.test(e.name))throw new f(`The doctype name "`+e.name+`" is not a valid XML Name`,p.InvalidStateError);if(ce&&!m.PubidLiteral_match.test(ce))throw new f(`DocumentType publicId is not a valid PubidLiteral`,p.InvalidStateError);if(le&&le!==`.`&&!m.SystemLiteral_match.test(le))throw new f(`DocumentType systemId is not a valid SystemLiteral`,p.InvalidStateError);if(e.internalSubset&&e.internalSubset.indexOf(`]>`)!==-1)throw new f(`DocumentType internalSubset contains "]>"`,p.InvalidStateError)}return t.push(m.DOCTYPE_DECL_START,` `,e.name),ce?(t.push(` `,m.PUBLIC,` `,ce),le&&le!==`.`&&t.push(` `,le)):le&&le!==`.`&&t.push(` `,m.SYSTEM,` `,le),e.internalSubset&&t.push(` [`,e.internalSubset,`]`),t.push(`>`),null;case M:if(a){if(!m.NCName_exact.test(e.target)||e.target.toLowerCase()===`xml`)throw new f(`The processing instruction target "`+e.target+`" is not a valid XML NCName or is reserved`,p.InvalidStateError);if(m.InvalidChar.test(e.data))throw new f(`The ProcessingInstruction data contains characters outside the XML Char production`,p.InvalidStateError);if(e.data.indexOf(`?>`)!==-1)throw new f(`The ProcessingInstruction data contains "?>"`,p.InvalidStateError)}return t.push(``),null;case A:if(a&&!m.Name_exact.test(e.nodeName))throw new f(`The entity reference name "`+e.nodeName+`" is not a valid XML Name`,p.InvalidStateError);return t.push(`&`,e.nodeName,`;`),null;default:return t.push(`??`,e.nodeName),null}},exit:function(e,n){n&&n.tag&&t.push(``)}})}function et(e,t,n){var r;return be(t,null,{enter:function(t,i){var a=t.cloneNode(!1);return a.ownerDocument=e,a.parentNode=null,i===null?r=a:i.appendChild(a),t.nodeType===D||n?a:null}}),r}function tt(e,t,n){var r;return be(t,null,{enter:function(t,a){var o=new t.constructor(u);for(var s in t)if(i(t,s)){var c=t[s];typeof c!=`object`&&c!=o[s]&&(o[s]=c)}t.childNodes&&(o.childNodes=new se),o.ownerDocument=e;var l=n;switch(o.nodeType){case E:var d=t.attributes,f=o.attributes=new ue,p=d.length;f._ownerElement=o;for(var m=0;m{var t=TI().freeze;e.XML_ENTITIES=t({amp:`&`,apos:`'`,gt:`>`,lt:`<`,quot:`"`}),e.HTML_ENTITIES=t({Aacute:`Á`,aacute:`á`,Abreve:`Ă`,abreve:`ă`,ac:`∾`,acd:`∿`,acE:`∾̳`,Acirc:`Â`,acirc:`â`,acute:`´`,Acy:`А`,acy:`а`,AElig:`Æ`,aelig:`æ`,af:`⁡`,Afr:`𝔄`,afr:`𝔞`,Agrave:`À`,agrave:`à`,alefsym:`ℵ`,aleph:`ℵ`,Alpha:`Α`,alpha:`α`,Amacr:`Ā`,amacr:`ā`,amalg:`⨿`,AMP:`&`,amp:`&`,And:`⩓`,and:`∧`,andand:`⩕`,andd:`⩜`,andslope:`⩘`,andv:`⩚`,ang:`∠`,ange:`⦤`,angle:`∠`,angmsd:`∡`,angmsdaa:`⦨`,angmsdab:`⦩`,angmsdac:`⦪`,angmsdad:`⦫`,angmsdae:`⦬`,angmsdaf:`⦭`,angmsdag:`⦮`,angmsdah:`⦯`,angrt:`∟`,angrtvb:`⊾`,angrtvbd:`⦝`,angsph:`∢`,angst:`Å`,angzarr:`⍼`,Aogon:`Ą`,aogon:`ą`,Aopf:`𝔸`,aopf:`𝕒`,ap:`≈`,apacir:`⩯`,apE:`⩰`,ape:`≊`,apid:`≋`,apos:`'`,ApplyFunction:`⁡`,approx:`≈`,approxeq:`≊`,Aring:`Å`,aring:`å`,Ascr:`𝒜`,ascr:`𝒶`,Assign:`≔`,ast:`*`,asymp:`≈`,asympeq:`≍`,Atilde:`Ã`,atilde:`ã`,Auml:`Ä`,auml:`ä`,awconint:`∳`,awint:`⨑`,backcong:`≌`,backepsilon:`϶`,backprime:`‵`,backsim:`∽`,backsimeq:`⋍`,Backslash:`∖`,Barv:`⫧`,barvee:`⊽`,Barwed:`⌆`,barwed:`⌅`,barwedge:`⌅`,bbrk:`⎵`,bbrktbrk:`⎶`,bcong:`≌`,Bcy:`Б`,bcy:`б`,bdquo:`„`,becaus:`∵`,Because:`∵`,because:`∵`,bemptyv:`⦰`,bepsi:`϶`,bernou:`ℬ`,Bernoullis:`ℬ`,Beta:`Β`,beta:`β`,beth:`ℶ`,between:`≬`,Bfr:`𝔅`,bfr:`𝔟`,bigcap:`⋂`,bigcirc:`◯`,bigcup:`⋃`,bigodot:`⨀`,bigoplus:`⨁`,bigotimes:`⨂`,bigsqcup:`⨆`,bigstar:`★`,bigtriangledown:`▽`,bigtriangleup:`△`,biguplus:`⨄`,bigvee:`⋁`,bigwedge:`⋀`,bkarow:`⤍`,blacklozenge:`⧫`,blacksquare:`▪`,blacktriangle:`▴`,blacktriangledown:`▾`,blacktriangleleft:`◂`,blacktriangleright:`▸`,blank:`␣`,blk12:`▒`,blk14:`░`,blk34:`▓`,block:`█`,bne:`=⃥`,bnequiv:`≡⃥`,bNot:`⫭`,bnot:`⌐`,Bopf:`𝔹`,bopf:`𝕓`,bot:`⊥`,bottom:`⊥`,bowtie:`⋈`,boxbox:`⧉`,boxDL:`╗`,boxDl:`╖`,boxdL:`╕`,boxdl:`┐`,boxDR:`╔`,boxDr:`╓`,boxdR:`╒`,boxdr:`┌`,boxH:`═`,boxh:`─`,boxHD:`╦`,boxHd:`╤`,boxhD:`╥`,boxhd:`┬`,boxHU:`╩`,boxHu:`╧`,boxhU:`╨`,boxhu:`┴`,boxminus:`⊟`,boxplus:`⊞`,boxtimes:`⊠`,boxUL:`╝`,boxUl:`╜`,boxuL:`╛`,boxul:`┘`,boxUR:`╚`,boxUr:`╙`,boxuR:`╘`,boxur:`└`,boxV:`║`,boxv:`│`,boxVH:`╬`,boxVh:`╫`,boxvH:`╪`,boxvh:`┼`,boxVL:`╣`,boxVl:`╢`,boxvL:`╡`,boxvl:`┤`,boxVR:`╠`,boxVr:`╟`,boxvR:`╞`,boxvr:`├`,bprime:`‵`,Breve:`˘`,breve:`˘`,brvbar:`¦`,Bscr:`ℬ`,bscr:`𝒷`,bsemi:`⁏`,bsim:`∽`,bsime:`⋍`,bsol:`\\`,bsolb:`⧅`,bsolhsub:`⟈`,bull:`•`,bullet:`•`,bump:`≎`,bumpE:`⪮`,bumpe:`≏`,Bumpeq:`≎`,bumpeq:`≏`,Cacute:`Ć`,cacute:`ć`,Cap:`⋒`,cap:`∩`,capand:`⩄`,capbrcup:`⩉`,capcap:`⩋`,capcup:`⩇`,capdot:`⩀`,CapitalDifferentialD:`ⅅ`,caps:`∩︀`,caret:`⁁`,caron:`ˇ`,Cayleys:`ℭ`,ccaps:`⩍`,Ccaron:`Č`,ccaron:`č`,Ccedil:`Ç`,ccedil:`ç`,Ccirc:`Ĉ`,ccirc:`ĉ`,Cconint:`∰`,ccups:`⩌`,ccupssm:`⩐`,Cdot:`Ċ`,cdot:`ċ`,cedil:`¸`,Cedilla:`¸`,cemptyv:`⦲`,cent:`¢`,CenterDot:`·`,centerdot:`·`,Cfr:`ℭ`,cfr:`𝔠`,CHcy:`Ч`,chcy:`ч`,check:`✓`,checkmark:`✓`,Chi:`Χ`,chi:`χ`,cir:`○`,circ:`ˆ`,circeq:`≗`,circlearrowleft:`↺`,circlearrowright:`↻`,circledast:`⊛`,circledcirc:`⊚`,circleddash:`⊝`,CircleDot:`⊙`,circledR:`®`,circledS:`Ⓢ`,CircleMinus:`⊖`,CirclePlus:`⊕`,CircleTimes:`⊗`,cirE:`⧃`,cire:`≗`,cirfnint:`⨐`,cirmid:`⫯`,cirscir:`⧂`,ClockwiseContourIntegral:`∲`,CloseCurlyDoubleQuote:`”`,CloseCurlyQuote:`’`,clubs:`♣`,clubsuit:`♣`,Colon:`∷`,colon:`:`,Colone:`⩴`,colone:`≔`,coloneq:`≔`,comma:`,`,commat:`@`,comp:`∁`,compfn:`∘`,complement:`∁`,complexes:`ℂ`,cong:`≅`,congdot:`⩭`,Congruent:`≡`,Conint:`∯`,conint:`∮`,ContourIntegral:`∮`,Copf:`ℂ`,copf:`𝕔`,coprod:`∐`,Coproduct:`∐`,COPY:`©`,copy:`©`,copysr:`℗`,CounterClockwiseContourIntegral:`∳`,crarr:`↵`,Cross:`⨯`,cross:`✗`,Cscr:`𝒞`,cscr:`𝒸`,csub:`⫏`,csube:`⫑`,csup:`⫐`,csupe:`⫒`,ctdot:`⋯`,cudarrl:`⤸`,cudarrr:`⤵`,cuepr:`⋞`,cuesc:`⋟`,cularr:`↶`,cularrp:`⤽`,Cup:`⋓`,cup:`∪`,cupbrcap:`⩈`,CupCap:`≍`,cupcap:`⩆`,cupcup:`⩊`,cupdot:`⊍`,cupor:`⩅`,cups:`∪︀`,curarr:`↷`,curarrm:`⤼`,curlyeqprec:`⋞`,curlyeqsucc:`⋟`,curlyvee:`⋎`,curlywedge:`⋏`,curren:`¤`,curvearrowleft:`↶`,curvearrowright:`↷`,cuvee:`⋎`,cuwed:`⋏`,cwconint:`∲`,cwint:`∱`,cylcty:`⌭`,Dagger:`‡`,dagger:`†`,daleth:`ℸ`,Darr:`↡`,dArr:`⇓`,darr:`↓`,dash:`‐`,Dashv:`⫤`,dashv:`⊣`,dbkarow:`⤏`,dblac:`˝`,Dcaron:`Ď`,dcaron:`ď`,Dcy:`Д`,dcy:`д`,DD:`ⅅ`,dd:`ⅆ`,ddagger:`‡`,ddarr:`⇊`,DDotrahd:`⤑`,ddotseq:`⩷`,deg:`°`,Del:`∇`,Delta:`Δ`,delta:`δ`,demptyv:`⦱`,dfisht:`⥿`,Dfr:`𝔇`,dfr:`𝔡`,dHar:`⥥`,dharl:`⇃`,dharr:`⇂`,DiacriticalAcute:`´`,DiacriticalDot:`˙`,DiacriticalDoubleAcute:`˝`,DiacriticalGrave:"`",DiacriticalTilde:`˜`,diam:`⋄`,Diamond:`⋄`,diamond:`⋄`,diamondsuit:`♦`,diams:`♦`,die:`¨`,DifferentialD:`ⅆ`,digamma:`ϝ`,disin:`⋲`,div:`÷`,divide:`÷`,divideontimes:`⋇`,divonx:`⋇`,DJcy:`Ђ`,djcy:`ђ`,dlcorn:`⌞`,dlcrop:`⌍`,dollar:`$`,Dopf:`𝔻`,dopf:`𝕕`,Dot:`¨`,dot:`˙`,DotDot:`⃜`,doteq:`≐`,doteqdot:`≑`,DotEqual:`≐`,dotminus:`∸`,dotplus:`∔`,dotsquare:`⊡`,doublebarwedge:`⌆`,DoubleContourIntegral:`∯`,DoubleDot:`¨`,DoubleDownArrow:`⇓`,DoubleLeftArrow:`⇐`,DoubleLeftRightArrow:`⇔`,DoubleLeftTee:`⫤`,DoubleLongLeftArrow:`⟸`,DoubleLongLeftRightArrow:`⟺`,DoubleLongRightArrow:`⟹`,DoubleRightArrow:`⇒`,DoubleRightTee:`⊨`,DoubleUpArrow:`⇑`,DoubleUpDownArrow:`⇕`,DoubleVerticalBar:`∥`,DownArrow:`↓`,Downarrow:`⇓`,downarrow:`↓`,DownArrowBar:`⤓`,DownArrowUpArrow:`⇵`,DownBreve:`̑`,downdownarrows:`⇊`,downharpoonleft:`⇃`,downharpoonright:`⇂`,DownLeftRightVector:`⥐`,DownLeftTeeVector:`⥞`,DownLeftVector:`↽`,DownLeftVectorBar:`⥖`,DownRightTeeVector:`⥟`,DownRightVector:`⇁`,DownRightVectorBar:`⥗`,DownTee:`⊤`,DownTeeArrow:`↧`,drbkarow:`⤐`,drcorn:`⌟`,drcrop:`⌌`,Dscr:`𝒟`,dscr:`𝒹`,DScy:`Ѕ`,dscy:`ѕ`,dsol:`⧶`,Dstrok:`Đ`,dstrok:`đ`,dtdot:`⋱`,dtri:`▿`,dtrif:`▾`,duarr:`⇵`,duhar:`⥯`,dwangle:`⦦`,DZcy:`Џ`,dzcy:`џ`,dzigrarr:`⟿`,Eacute:`É`,eacute:`é`,easter:`⩮`,Ecaron:`Ě`,ecaron:`ě`,ecir:`≖`,Ecirc:`Ê`,ecirc:`ê`,ecolon:`≕`,Ecy:`Э`,ecy:`э`,eDDot:`⩷`,Edot:`Ė`,eDot:`≑`,edot:`ė`,ee:`ⅇ`,efDot:`≒`,Efr:`𝔈`,efr:`𝔢`,eg:`⪚`,Egrave:`È`,egrave:`è`,egs:`⪖`,egsdot:`⪘`,el:`⪙`,Element:`∈`,elinters:`⏧`,ell:`ℓ`,els:`⪕`,elsdot:`⪗`,Emacr:`Ē`,emacr:`ē`,empty:`∅`,emptyset:`∅`,EmptySmallSquare:`◻`,emptyv:`∅`,EmptyVerySmallSquare:`▫`,emsp:` `,emsp13:` `,emsp14:` `,ENG:`Ŋ`,eng:`ŋ`,ensp:` `,Eogon:`Ę`,eogon:`ę`,Eopf:`𝔼`,eopf:`𝕖`,epar:`⋕`,eparsl:`⧣`,eplus:`⩱`,epsi:`ε`,Epsilon:`Ε`,epsilon:`ε`,epsiv:`ϵ`,eqcirc:`≖`,eqcolon:`≕`,eqsim:`≂`,eqslantgtr:`⪖`,eqslantless:`⪕`,Equal:`⩵`,equals:`=`,EqualTilde:`≂`,equest:`≟`,Equilibrium:`⇌`,equiv:`≡`,equivDD:`⩸`,eqvparsl:`⧥`,erarr:`⥱`,erDot:`≓`,Escr:`ℰ`,escr:`ℯ`,esdot:`≐`,Esim:`⩳`,esim:`≂`,Eta:`Η`,eta:`η`,ETH:`Ð`,eth:`ð`,Euml:`Ë`,euml:`ë`,euro:`€`,excl:`!`,exist:`∃`,Exists:`∃`,expectation:`ℰ`,ExponentialE:`ⅇ`,exponentiale:`ⅇ`,fallingdotseq:`≒`,Fcy:`Ф`,fcy:`ф`,female:`♀`,ffilig:`ffi`,fflig:`ff`,ffllig:`ffl`,Ffr:`𝔉`,ffr:`𝔣`,filig:`fi`,FilledSmallSquare:`◼`,FilledVerySmallSquare:`▪`,fjlig:`fj`,flat:`♭`,fllig:`fl`,fltns:`▱`,fnof:`ƒ`,Fopf:`𝔽`,fopf:`𝕗`,ForAll:`∀`,forall:`∀`,fork:`⋔`,forkv:`⫙`,Fouriertrf:`ℱ`,fpartint:`⨍`,frac12:`½`,frac13:`⅓`,frac14:`¼`,frac15:`⅕`,frac16:`⅙`,frac18:`⅛`,frac23:`⅔`,frac25:`⅖`,frac34:`¾`,frac35:`⅗`,frac38:`⅜`,frac45:`⅘`,frac56:`⅚`,frac58:`⅝`,frac78:`⅞`,frasl:`⁄`,frown:`⌢`,Fscr:`ℱ`,fscr:`𝒻`,gacute:`ǵ`,Gamma:`Γ`,gamma:`γ`,Gammad:`Ϝ`,gammad:`ϝ`,gap:`⪆`,Gbreve:`Ğ`,gbreve:`ğ`,Gcedil:`Ģ`,Gcirc:`Ĝ`,gcirc:`ĝ`,Gcy:`Г`,gcy:`г`,Gdot:`Ġ`,gdot:`ġ`,gE:`≧`,ge:`≥`,gEl:`⪌`,gel:`⋛`,geq:`≥`,geqq:`≧`,geqslant:`⩾`,ges:`⩾`,gescc:`⪩`,gesdot:`⪀`,gesdoto:`⪂`,gesdotol:`⪄`,gesl:`⋛︀`,gesles:`⪔`,Gfr:`𝔊`,gfr:`𝔤`,Gg:`⋙`,gg:`≫`,ggg:`⋙`,gimel:`ℷ`,GJcy:`Ѓ`,gjcy:`ѓ`,gl:`≷`,gla:`⪥`,glE:`⪒`,glj:`⪤`,gnap:`⪊`,gnapprox:`⪊`,gnE:`≩`,gne:`⪈`,gneq:`⪈`,gneqq:`≩`,gnsim:`⋧`,Gopf:`𝔾`,gopf:`𝕘`,grave:"`",GreaterEqual:`≥`,GreaterEqualLess:`⋛`,GreaterFullEqual:`≧`,GreaterGreater:`⪢`,GreaterLess:`≷`,GreaterSlantEqual:`⩾`,GreaterTilde:`≳`,Gscr:`𝒢`,gscr:`ℊ`,gsim:`≳`,gsime:`⪎`,gsiml:`⪐`,Gt:`≫`,GT:`>`,gt:`>`,gtcc:`⪧`,gtcir:`⩺`,gtdot:`⋗`,gtlPar:`⦕`,gtquest:`⩼`,gtrapprox:`⪆`,gtrarr:`⥸`,gtrdot:`⋗`,gtreqless:`⋛`,gtreqqless:`⪌`,gtrless:`≷`,gtrsim:`≳`,gvertneqq:`≩︀`,gvnE:`≩︀`,Hacek:`ˇ`,hairsp:` `,half:`½`,hamilt:`ℋ`,HARDcy:`Ъ`,hardcy:`ъ`,hArr:`⇔`,harr:`↔`,harrcir:`⥈`,harrw:`↭`,Hat:`^`,hbar:`ℏ`,Hcirc:`Ĥ`,hcirc:`ĥ`,hearts:`♥`,heartsuit:`♥`,hellip:`…`,hercon:`⊹`,Hfr:`ℌ`,hfr:`𝔥`,HilbertSpace:`ℋ`,hksearow:`⤥`,hkswarow:`⤦`,hoarr:`⇿`,homtht:`∻`,hookleftarrow:`↩`,hookrightarrow:`↪`,Hopf:`ℍ`,hopf:`𝕙`,horbar:`―`,HorizontalLine:`─`,Hscr:`ℋ`,hscr:`𝒽`,hslash:`ℏ`,Hstrok:`Ħ`,hstrok:`ħ`,HumpDownHump:`≎`,HumpEqual:`≏`,hybull:`⁃`,hyphen:`‐`,Iacute:`Í`,iacute:`í`,ic:`⁣`,Icirc:`Î`,icirc:`î`,Icy:`И`,icy:`и`,Idot:`İ`,IEcy:`Е`,iecy:`е`,iexcl:`¡`,iff:`⇔`,Ifr:`ℑ`,ifr:`𝔦`,Igrave:`Ì`,igrave:`ì`,ii:`ⅈ`,iiiint:`⨌`,iiint:`∭`,iinfin:`⧜`,iiota:`℩`,IJlig:`IJ`,ijlig:`ij`,Im:`ℑ`,Imacr:`Ī`,imacr:`ī`,image:`ℑ`,ImaginaryI:`ⅈ`,imagline:`ℐ`,imagpart:`ℑ`,imath:`ı`,imof:`⊷`,imped:`Ƶ`,Implies:`⇒`,in:`∈`,incare:`℅`,infin:`∞`,infintie:`⧝`,inodot:`ı`,Int:`∬`,int:`∫`,intcal:`⊺`,integers:`ℤ`,Integral:`∫`,intercal:`⊺`,Intersection:`⋂`,intlarhk:`⨗`,intprod:`⨼`,InvisibleComma:`⁣`,InvisibleTimes:`⁢`,IOcy:`Ё`,iocy:`ё`,Iogon:`Į`,iogon:`į`,Iopf:`𝕀`,iopf:`𝕚`,Iota:`Ι`,iota:`ι`,iprod:`⨼`,iquest:`¿`,Iscr:`ℐ`,iscr:`𝒾`,isin:`∈`,isindot:`⋵`,isinE:`⋹`,isins:`⋴`,isinsv:`⋳`,isinv:`∈`,it:`⁢`,Itilde:`Ĩ`,itilde:`ĩ`,Iukcy:`І`,iukcy:`і`,Iuml:`Ï`,iuml:`ï`,Jcirc:`Ĵ`,jcirc:`ĵ`,Jcy:`Й`,jcy:`й`,Jfr:`𝔍`,jfr:`𝔧`,jmath:`ȷ`,Jopf:`𝕁`,jopf:`𝕛`,Jscr:`𝒥`,jscr:`𝒿`,Jsercy:`Ј`,jsercy:`ј`,Jukcy:`Є`,jukcy:`є`,Kappa:`Κ`,kappa:`κ`,kappav:`ϰ`,Kcedil:`Ķ`,kcedil:`ķ`,Kcy:`К`,kcy:`к`,Kfr:`𝔎`,kfr:`𝔨`,kgreen:`ĸ`,KHcy:`Х`,khcy:`х`,KJcy:`Ќ`,kjcy:`ќ`,Kopf:`𝕂`,kopf:`𝕜`,Kscr:`𝒦`,kscr:`𝓀`,lAarr:`⇚`,Lacute:`Ĺ`,lacute:`ĺ`,laemptyv:`⦴`,lagran:`ℒ`,Lambda:`Λ`,lambda:`λ`,Lang:`⟪`,lang:`⟨`,langd:`⦑`,langle:`⟨`,lap:`⪅`,Laplacetrf:`ℒ`,laquo:`«`,Larr:`↞`,lArr:`⇐`,larr:`←`,larrb:`⇤`,larrbfs:`⤟`,larrfs:`⤝`,larrhk:`↩`,larrlp:`↫`,larrpl:`⤹`,larrsim:`⥳`,larrtl:`↢`,lat:`⪫`,lAtail:`⤛`,latail:`⤙`,late:`⪭`,lates:`⪭︀`,lBarr:`⤎`,lbarr:`⤌`,lbbrk:`❲`,lbrace:`{`,lbrack:`[`,lbrke:`⦋`,lbrksld:`⦏`,lbrkslu:`⦍`,Lcaron:`Ľ`,lcaron:`ľ`,Lcedil:`Ļ`,lcedil:`ļ`,lceil:`⌈`,lcub:`{`,Lcy:`Л`,lcy:`л`,ldca:`⤶`,ldquo:`“`,ldquor:`„`,ldrdhar:`⥧`,ldrushar:`⥋`,ldsh:`↲`,lE:`≦`,le:`≤`,LeftAngleBracket:`⟨`,LeftArrow:`←`,Leftarrow:`⇐`,leftarrow:`←`,LeftArrowBar:`⇤`,LeftArrowRightArrow:`⇆`,leftarrowtail:`↢`,LeftCeiling:`⌈`,LeftDoubleBracket:`⟦`,LeftDownTeeVector:`⥡`,LeftDownVector:`⇃`,LeftDownVectorBar:`⥙`,LeftFloor:`⌊`,leftharpoondown:`↽`,leftharpoonup:`↼`,leftleftarrows:`⇇`,LeftRightArrow:`↔`,Leftrightarrow:`⇔`,leftrightarrow:`↔`,leftrightarrows:`⇆`,leftrightharpoons:`⇋`,leftrightsquigarrow:`↭`,LeftRightVector:`⥎`,LeftTee:`⊣`,LeftTeeArrow:`↤`,LeftTeeVector:`⥚`,leftthreetimes:`⋋`,LeftTriangle:`⊲`,LeftTriangleBar:`⧏`,LeftTriangleEqual:`⊴`,LeftUpDownVector:`⥑`,LeftUpTeeVector:`⥠`,LeftUpVector:`↿`,LeftUpVectorBar:`⥘`,LeftVector:`↼`,LeftVectorBar:`⥒`,lEg:`⪋`,leg:`⋚`,leq:`≤`,leqq:`≦`,leqslant:`⩽`,les:`⩽`,lescc:`⪨`,lesdot:`⩿`,lesdoto:`⪁`,lesdotor:`⪃`,lesg:`⋚︀`,lesges:`⪓`,lessapprox:`⪅`,lessdot:`⋖`,lesseqgtr:`⋚`,lesseqqgtr:`⪋`,LessEqualGreater:`⋚`,LessFullEqual:`≦`,LessGreater:`≶`,lessgtr:`≶`,LessLess:`⪡`,lesssim:`≲`,LessSlantEqual:`⩽`,LessTilde:`≲`,lfisht:`⥼`,lfloor:`⌊`,Lfr:`𝔏`,lfr:`𝔩`,lg:`≶`,lgE:`⪑`,lHar:`⥢`,lhard:`↽`,lharu:`↼`,lharul:`⥪`,lhblk:`▄`,LJcy:`Љ`,ljcy:`љ`,Ll:`⋘`,ll:`≪`,llarr:`⇇`,llcorner:`⌞`,Lleftarrow:`⇚`,llhard:`⥫`,lltri:`◺`,Lmidot:`Ŀ`,lmidot:`ŀ`,lmoust:`⎰`,lmoustache:`⎰`,lnap:`⪉`,lnapprox:`⪉`,lnE:`≨`,lne:`⪇`,lneq:`⪇`,lneqq:`≨`,lnsim:`⋦`,loang:`⟬`,loarr:`⇽`,lobrk:`⟦`,LongLeftArrow:`⟵`,Longleftarrow:`⟸`,longleftarrow:`⟵`,LongLeftRightArrow:`⟷`,Longleftrightarrow:`⟺`,longleftrightarrow:`⟷`,longmapsto:`⟼`,LongRightArrow:`⟶`,Longrightarrow:`⟹`,longrightarrow:`⟶`,looparrowleft:`↫`,looparrowright:`↬`,lopar:`⦅`,Lopf:`𝕃`,lopf:`𝕝`,loplus:`⨭`,lotimes:`⨴`,lowast:`∗`,lowbar:`_`,LowerLeftArrow:`↙`,LowerRightArrow:`↘`,loz:`◊`,lozenge:`◊`,lozf:`⧫`,lpar:`(`,lparlt:`⦓`,lrarr:`⇆`,lrcorner:`⌟`,lrhar:`⇋`,lrhard:`⥭`,lrm:`‎`,lrtri:`⊿`,lsaquo:`‹`,Lscr:`ℒ`,lscr:`𝓁`,Lsh:`↰`,lsh:`↰`,lsim:`≲`,lsime:`⪍`,lsimg:`⪏`,lsqb:`[`,lsquo:`‘`,lsquor:`‚`,Lstrok:`Ł`,lstrok:`ł`,Lt:`≪`,LT:`<`,lt:`<`,ltcc:`⪦`,ltcir:`⩹`,ltdot:`⋖`,lthree:`⋋`,ltimes:`⋉`,ltlarr:`⥶`,ltquest:`⩻`,ltri:`◃`,ltrie:`⊴`,ltrif:`◂`,ltrPar:`⦖`,lurdshar:`⥊`,luruhar:`⥦`,lvertneqq:`≨︀`,lvnE:`≨︀`,macr:`¯`,male:`♂`,malt:`✠`,maltese:`✠`,Map:`⤅`,map:`↦`,mapsto:`↦`,mapstodown:`↧`,mapstoleft:`↤`,mapstoup:`↥`,marker:`▮`,mcomma:`⨩`,Mcy:`М`,mcy:`м`,mdash:`—`,mDDot:`∺`,measuredangle:`∡`,MediumSpace:` `,Mellintrf:`ℳ`,Mfr:`𝔐`,mfr:`𝔪`,mho:`℧`,micro:`µ`,mid:`∣`,midast:`*`,midcir:`⫰`,middot:`·`,minus:`−`,minusb:`⊟`,minusd:`∸`,minusdu:`⨪`,MinusPlus:`∓`,mlcp:`⫛`,mldr:`…`,mnplus:`∓`,models:`⊧`,Mopf:`𝕄`,mopf:`𝕞`,mp:`∓`,Mscr:`ℳ`,mscr:`𝓂`,mstpos:`∾`,Mu:`Μ`,mu:`μ`,multimap:`⊸`,mumap:`⊸`,nabla:`∇`,Nacute:`Ń`,nacute:`ń`,nang:`∠⃒`,nap:`≉`,napE:`⩰̸`,napid:`≋̸`,napos:`ʼn`,napprox:`≉`,natur:`♮`,natural:`♮`,naturals:`ℕ`,nbsp:`\xA0`,nbump:`≎̸`,nbumpe:`≏̸`,ncap:`⩃`,Ncaron:`Ň`,ncaron:`ň`,Ncedil:`Ņ`,ncedil:`ņ`,ncong:`≇`,ncongdot:`⩭̸`,ncup:`⩂`,Ncy:`Н`,ncy:`н`,ndash:`–`,ne:`≠`,nearhk:`⤤`,neArr:`⇗`,nearr:`↗`,nearrow:`↗`,nedot:`≐̸`,NegativeMediumSpace:`​`,NegativeThickSpace:`​`,NegativeThinSpace:`​`,NegativeVeryThinSpace:`​`,nequiv:`≢`,nesear:`⤨`,nesim:`≂̸`,NestedGreaterGreater:`≫`,NestedLessLess:`≪`,NewLine:` +`,nexist:`∄`,nexists:`∄`,Nfr:`𝔑`,nfr:`𝔫`,ngE:`≧̸`,nge:`≱`,ngeq:`≱`,ngeqq:`≧̸`,ngeqslant:`⩾̸`,nges:`⩾̸`,nGg:`⋙̸`,ngsim:`≵`,nGt:`≫⃒`,ngt:`≯`,ngtr:`≯`,nGtv:`≫̸`,nhArr:`⇎`,nharr:`↮`,nhpar:`⫲`,ni:`∋`,nis:`⋼`,nisd:`⋺`,niv:`∋`,NJcy:`Њ`,njcy:`њ`,nlArr:`⇍`,nlarr:`↚`,nldr:`‥`,nlE:`≦̸`,nle:`≰`,nLeftarrow:`⇍`,nleftarrow:`↚`,nLeftrightarrow:`⇎`,nleftrightarrow:`↮`,nleq:`≰`,nleqq:`≦̸`,nleqslant:`⩽̸`,nles:`⩽̸`,nless:`≮`,nLl:`⋘̸`,nlsim:`≴`,nLt:`≪⃒`,nlt:`≮`,nltri:`⋪`,nltrie:`⋬`,nLtv:`≪̸`,nmid:`∤`,NoBreak:`⁠`,NonBreakingSpace:`\xA0`,Nopf:`ℕ`,nopf:`𝕟`,Not:`⫬`,not:`¬`,NotCongruent:`≢`,NotCupCap:`≭`,NotDoubleVerticalBar:`∦`,NotElement:`∉`,NotEqual:`≠`,NotEqualTilde:`≂̸`,NotExists:`∄`,NotGreater:`≯`,NotGreaterEqual:`≱`,NotGreaterFullEqual:`≧̸`,NotGreaterGreater:`≫̸`,NotGreaterLess:`≹`,NotGreaterSlantEqual:`⩾̸`,NotGreaterTilde:`≵`,NotHumpDownHump:`≎̸`,NotHumpEqual:`≏̸`,notin:`∉`,notindot:`⋵̸`,notinE:`⋹̸`,notinva:`∉`,notinvb:`⋷`,notinvc:`⋶`,NotLeftTriangle:`⋪`,NotLeftTriangleBar:`⧏̸`,NotLeftTriangleEqual:`⋬`,NotLess:`≮`,NotLessEqual:`≰`,NotLessGreater:`≸`,NotLessLess:`≪̸`,NotLessSlantEqual:`⩽̸`,NotLessTilde:`≴`,NotNestedGreaterGreater:`⪢̸`,NotNestedLessLess:`⪡̸`,notni:`∌`,notniva:`∌`,notnivb:`⋾`,notnivc:`⋽`,NotPrecedes:`⊀`,NotPrecedesEqual:`⪯̸`,NotPrecedesSlantEqual:`⋠`,NotReverseElement:`∌`,NotRightTriangle:`⋫`,NotRightTriangleBar:`⧐̸`,NotRightTriangleEqual:`⋭`,NotSquareSubset:`⊏̸`,NotSquareSubsetEqual:`⋢`,NotSquareSuperset:`⊐̸`,NotSquareSupersetEqual:`⋣`,NotSubset:`⊂⃒`,NotSubsetEqual:`⊈`,NotSucceeds:`⊁`,NotSucceedsEqual:`⪰̸`,NotSucceedsSlantEqual:`⋡`,NotSucceedsTilde:`≿̸`,NotSuperset:`⊃⃒`,NotSupersetEqual:`⊉`,NotTilde:`≁`,NotTildeEqual:`≄`,NotTildeFullEqual:`≇`,NotTildeTilde:`≉`,NotVerticalBar:`∤`,npar:`∦`,nparallel:`∦`,nparsl:`⫽⃥`,npart:`∂̸`,npolint:`⨔`,npr:`⊀`,nprcue:`⋠`,npre:`⪯̸`,nprec:`⊀`,npreceq:`⪯̸`,nrArr:`⇏`,nrarr:`↛`,nrarrc:`⤳̸`,nrarrw:`↝̸`,nRightarrow:`⇏`,nrightarrow:`↛`,nrtri:`⋫`,nrtrie:`⋭`,nsc:`⊁`,nsccue:`⋡`,nsce:`⪰̸`,Nscr:`𝒩`,nscr:`𝓃`,nshortmid:`∤`,nshortparallel:`∦`,nsim:`≁`,nsime:`≄`,nsimeq:`≄`,nsmid:`∤`,nspar:`∦`,nsqsube:`⋢`,nsqsupe:`⋣`,nsub:`⊄`,nsubE:`⫅̸`,nsube:`⊈`,nsubset:`⊂⃒`,nsubseteq:`⊈`,nsubseteqq:`⫅̸`,nsucc:`⊁`,nsucceq:`⪰̸`,nsup:`⊅`,nsupE:`⫆̸`,nsupe:`⊉`,nsupset:`⊃⃒`,nsupseteq:`⊉`,nsupseteqq:`⫆̸`,ntgl:`≹`,Ntilde:`Ñ`,ntilde:`ñ`,ntlg:`≸`,ntriangleleft:`⋪`,ntrianglelefteq:`⋬`,ntriangleright:`⋫`,ntrianglerighteq:`⋭`,Nu:`Ν`,nu:`ν`,num:`#`,numero:`№`,numsp:` `,nvap:`≍⃒`,nVDash:`⊯`,nVdash:`⊮`,nvDash:`⊭`,nvdash:`⊬`,nvge:`≥⃒`,nvgt:`>⃒`,nvHarr:`⤄`,nvinfin:`⧞`,nvlArr:`⤂`,nvle:`≤⃒`,nvlt:`<⃒`,nvltrie:`⊴⃒`,nvrArr:`⤃`,nvrtrie:`⊵⃒`,nvsim:`∼⃒`,nwarhk:`⤣`,nwArr:`⇖`,nwarr:`↖`,nwarrow:`↖`,nwnear:`⤧`,Oacute:`Ó`,oacute:`ó`,oast:`⊛`,ocir:`⊚`,Ocirc:`Ô`,ocirc:`ô`,Ocy:`О`,ocy:`о`,odash:`⊝`,Odblac:`Ő`,odblac:`ő`,odiv:`⨸`,odot:`⊙`,odsold:`⦼`,OElig:`Œ`,oelig:`œ`,ofcir:`⦿`,Ofr:`𝔒`,ofr:`𝔬`,ogon:`˛`,Ograve:`Ò`,ograve:`ò`,ogt:`⧁`,ohbar:`⦵`,ohm:`Ω`,oint:`∮`,olarr:`↺`,olcir:`⦾`,olcross:`⦻`,oline:`‾`,olt:`⧀`,Omacr:`Ō`,omacr:`ō`,Omega:`Ω`,omega:`ω`,Omicron:`Ο`,omicron:`ο`,omid:`⦶`,ominus:`⊖`,Oopf:`𝕆`,oopf:`𝕠`,opar:`⦷`,OpenCurlyDoubleQuote:`“`,OpenCurlyQuote:`‘`,operp:`⦹`,oplus:`⊕`,Or:`⩔`,or:`∨`,orarr:`↻`,ord:`⩝`,order:`ℴ`,orderof:`ℴ`,ordf:`ª`,ordm:`º`,origof:`⊶`,oror:`⩖`,orslope:`⩗`,orv:`⩛`,oS:`Ⓢ`,Oscr:`𝒪`,oscr:`ℴ`,Oslash:`Ø`,oslash:`ø`,osol:`⊘`,Otilde:`Õ`,otilde:`õ`,Otimes:`⨷`,otimes:`⊗`,otimesas:`⨶`,Ouml:`Ö`,ouml:`ö`,ovbar:`⌽`,OverBar:`‾`,OverBrace:`⏞`,OverBracket:`⎴`,OverParenthesis:`⏜`,par:`∥`,para:`¶`,parallel:`∥`,parsim:`⫳`,parsl:`⫽`,part:`∂`,PartialD:`∂`,Pcy:`П`,pcy:`п`,percnt:`%`,period:`.`,permil:`‰`,perp:`⊥`,pertenk:`‱`,Pfr:`𝔓`,pfr:`𝔭`,Phi:`Φ`,phi:`φ`,phiv:`ϕ`,phmmat:`ℳ`,phone:`☎`,Pi:`Π`,pi:`π`,pitchfork:`⋔`,piv:`ϖ`,planck:`ℏ`,planckh:`ℎ`,plankv:`ℏ`,plus:`+`,plusacir:`⨣`,plusb:`⊞`,pluscir:`⨢`,plusdo:`∔`,plusdu:`⨥`,pluse:`⩲`,PlusMinus:`±`,plusmn:`±`,plussim:`⨦`,plustwo:`⨧`,pm:`±`,Poincareplane:`ℌ`,pointint:`⨕`,Popf:`ℙ`,popf:`𝕡`,pound:`£`,Pr:`⪻`,pr:`≺`,prap:`⪷`,prcue:`≼`,prE:`⪳`,pre:`⪯`,prec:`≺`,precapprox:`⪷`,preccurlyeq:`≼`,Precedes:`≺`,PrecedesEqual:`⪯`,PrecedesSlantEqual:`≼`,PrecedesTilde:`≾`,preceq:`⪯`,precnapprox:`⪹`,precneqq:`⪵`,precnsim:`⋨`,precsim:`≾`,Prime:`″`,prime:`′`,primes:`ℙ`,prnap:`⪹`,prnE:`⪵`,prnsim:`⋨`,prod:`∏`,Product:`∏`,profalar:`⌮`,profline:`⌒`,profsurf:`⌓`,prop:`∝`,Proportion:`∷`,Proportional:`∝`,propto:`∝`,prsim:`≾`,prurel:`⊰`,Pscr:`𝒫`,pscr:`𝓅`,Psi:`Ψ`,psi:`ψ`,puncsp:` `,Qfr:`𝔔`,qfr:`𝔮`,qint:`⨌`,Qopf:`ℚ`,qopf:`𝕢`,qprime:`⁗`,Qscr:`𝒬`,qscr:`𝓆`,quaternions:`ℍ`,quatint:`⨖`,quest:`?`,questeq:`≟`,QUOT:`"`,quot:`"`,rAarr:`⇛`,race:`∽̱`,Racute:`Ŕ`,racute:`ŕ`,radic:`√`,raemptyv:`⦳`,Rang:`⟫`,rang:`⟩`,rangd:`⦒`,range:`⦥`,rangle:`⟩`,raquo:`»`,Rarr:`↠`,rArr:`⇒`,rarr:`→`,rarrap:`⥵`,rarrb:`⇥`,rarrbfs:`⤠`,rarrc:`⤳`,rarrfs:`⤞`,rarrhk:`↪`,rarrlp:`↬`,rarrpl:`⥅`,rarrsim:`⥴`,Rarrtl:`⤖`,rarrtl:`↣`,rarrw:`↝`,rAtail:`⤜`,ratail:`⤚`,ratio:`∶`,rationals:`ℚ`,RBarr:`⤐`,rBarr:`⤏`,rbarr:`⤍`,rbbrk:`❳`,rbrace:`}`,rbrack:`]`,rbrke:`⦌`,rbrksld:`⦎`,rbrkslu:`⦐`,Rcaron:`Ř`,rcaron:`ř`,Rcedil:`Ŗ`,rcedil:`ŗ`,rceil:`⌉`,rcub:`}`,Rcy:`Р`,rcy:`р`,rdca:`⤷`,rdldhar:`⥩`,rdquo:`”`,rdquor:`”`,rdsh:`↳`,Re:`ℜ`,real:`ℜ`,realine:`ℛ`,realpart:`ℜ`,reals:`ℝ`,rect:`▭`,REG:`®`,reg:`®`,ReverseElement:`∋`,ReverseEquilibrium:`⇋`,ReverseUpEquilibrium:`⥯`,rfisht:`⥽`,rfloor:`⌋`,Rfr:`ℜ`,rfr:`𝔯`,rHar:`⥤`,rhard:`⇁`,rharu:`⇀`,rharul:`⥬`,Rho:`Ρ`,rho:`ρ`,rhov:`ϱ`,RightAngleBracket:`⟩`,RightArrow:`→`,Rightarrow:`⇒`,rightarrow:`→`,RightArrowBar:`⇥`,RightArrowLeftArrow:`⇄`,rightarrowtail:`↣`,RightCeiling:`⌉`,RightDoubleBracket:`⟧`,RightDownTeeVector:`⥝`,RightDownVector:`⇂`,RightDownVectorBar:`⥕`,RightFloor:`⌋`,rightharpoondown:`⇁`,rightharpoonup:`⇀`,rightleftarrows:`⇄`,rightleftharpoons:`⇌`,rightrightarrows:`⇉`,rightsquigarrow:`↝`,RightTee:`⊢`,RightTeeArrow:`↦`,RightTeeVector:`⥛`,rightthreetimes:`⋌`,RightTriangle:`⊳`,RightTriangleBar:`⧐`,RightTriangleEqual:`⊵`,RightUpDownVector:`⥏`,RightUpTeeVector:`⥜`,RightUpVector:`↾`,RightUpVectorBar:`⥔`,RightVector:`⇀`,RightVectorBar:`⥓`,ring:`˚`,risingdotseq:`≓`,rlarr:`⇄`,rlhar:`⇌`,rlm:`‏`,rmoust:`⎱`,rmoustache:`⎱`,rnmid:`⫮`,roang:`⟭`,roarr:`⇾`,robrk:`⟧`,ropar:`⦆`,Ropf:`ℝ`,ropf:`𝕣`,roplus:`⨮`,rotimes:`⨵`,RoundImplies:`⥰`,rpar:`)`,rpargt:`⦔`,rppolint:`⨒`,rrarr:`⇉`,Rrightarrow:`⇛`,rsaquo:`›`,Rscr:`ℛ`,rscr:`𝓇`,Rsh:`↱`,rsh:`↱`,rsqb:`]`,rsquo:`’`,rsquor:`’`,rthree:`⋌`,rtimes:`⋊`,rtri:`▹`,rtrie:`⊵`,rtrif:`▸`,rtriltri:`⧎`,RuleDelayed:`⧴`,ruluhar:`⥨`,rx:`℞`,Sacute:`Ś`,sacute:`ś`,sbquo:`‚`,Sc:`⪼`,sc:`≻`,scap:`⪸`,Scaron:`Š`,scaron:`š`,sccue:`≽`,scE:`⪴`,sce:`⪰`,Scedil:`Ş`,scedil:`ş`,Scirc:`Ŝ`,scirc:`ŝ`,scnap:`⪺`,scnE:`⪶`,scnsim:`⋩`,scpolint:`⨓`,scsim:`≿`,Scy:`С`,scy:`с`,sdot:`⋅`,sdotb:`⊡`,sdote:`⩦`,searhk:`⤥`,seArr:`⇘`,searr:`↘`,searrow:`↘`,sect:`§`,semi:`;`,seswar:`⤩`,setminus:`∖`,setmn:`∖`,sext:`✶`,Sfr:`𝔖`,sfr:`𝔰`,sfrown:`⌢`,sharp:`♯`,SHCHcy:`Щ`,shchcy:`щ`,SHcy:`Ш`,shcy:`ш`,ShortDownArrow:`↓`,ShortLeftArrow:`←`,shortmid:`∣`,shortparallel:`∥`,ShortRightArrow:`→`,ShortUpArrow:`↑`,shy:`­`,Sigma:`Σ`,sigma:`σ`,sigmaf:`ς`,sigmav:`ς`,sim:`∼`,simdot:`⩪`,sime:`≃`,simeq:`≃`,simg:`⪞`,simgE:`⪠`,siml:`⪝`,simlE:`⪟`,simne:`≆`,simplus:`⨤`,simrarr:`⥲`,slarr:`←`,SmallCircle:`∘`,smallsetminus:`∖`,smashp:`⨳`,smeparsl:`⧤`,smid:`∣`,smile:`⌣`,smt:`⪪`,smte:`⪬`,smtes:`⪬︀`,SOFTcy:`Ь`,softcy:`ь`,sol:`/`,solb:`⧄`,solbar:`⌿`,Sopf:`𝕊`,sopf:`𝕤`,spades:`♠`,spadesuit:`♠`,spar:`∥`,sqcap:`⊓`,sqcaps:`⊓︀`,sqcup:`⊔`,sqcups:`⊔︀`,Sqrt:`√`,sqsub:`⊏`,sqsube:`⊑`,sqsubset:`⊏`,sqsubseteq:`⊑`,sqsup:`⊐`,sqsupe:`⊒`,sqsupset:`⊐`,sqsupseteq:`⊒`,squ:`□`,Square:`□`,square:`□`,SquareIntersection:`⊓`,SquareSubset:`⊏`,SquareSubsetEqual:`⊑`,SquareSuperset:`⊐`,SquareSupersetEqual:`⊒`,SquareUnion:`⊔`,squarf:`▪`,squf:`▪`,srarr:`→`,Sscr:`𝒮`,sscr:`𝓈`,ssetmn:`∖`,ssmile:`⌣`,sstarf:`⋆`,Star:`⋆`,star:`☆`,starf:`★`,straightepsilon:`ϵ`,straightphi:`ϕ`,strns:`¯`,Sub:`⋐`,sub:`⊂`,subdot:`⪽`,subE:`⫅`,sube:`⊆`,subedot:`⫃`,submult:`⫁`,subnE:`⫋`,subne:`⊊`,subplus:`⪿`,subrarr:`⥹`,Subset:`⋐`,subset:`⊂`,subseteq:`⊆`,subseteqq:`⫅`,SubsetEqual:`⊆`,subsetneq:`⊊`,subsetneqq:`⫋`,subsim:`⫇`,subsub:`⫕`,subsup:`⫓`,succ:`≻`,succapprox:`⪸`,succcurlyeq:`≽`,Succeeds:`≻`,SucceedsEqual:`⪰`,SucceedsSlantEqual:`≽`,SucceedsTilde:`≿`,succeq:`⪰`,succnapprox:`⪺`,succneqq:`⪶`,succnsim:`⋩`,succsim:`≿`,SuchThat:`∋`,Sum:`∑`,sum:`∑`,sung:`♪`,Sup:`⋑`,sup:`⊃`,sup1:`¹`,sup2:`²`,sup3:`³`,supdot:`⪾`,supdsub:`⫘`,supE:`⫆`,supe:`⊇`,supedot:`⫄`,Superset:`⊃`,SupersetEqual:`⊇`,suphsol:`⟉`,suphsub:`⫗`,suplarr:`⥻`,supmult:`⫂`,supnE:`⫌`,supne:`⊋`,supplus:`⫀`,Supset:`⋑`,supset:`⊃`,supseteq:`⊇`,supseteqq:`⫆`,supsetneq:`⊋`,supsetneqq:`⫌`,supsim:`⫈`,supsub:`⫔`,supsup:`⫖`,swarhk:`⤦`,swArr:`⇙`,swarr:`↙`,swarrow:`↙`,swnwar:`⤪`,szlig:`ß`,Tab:` `,target:`⌖`,Tau:`Τ`,tau:`τ`,tbrk:`⎴`,Tcaron:`Ť`,tcaron:`ť`,Tcedil:`Ţ`,tcedil:`ţ`,Tcy:`Т`,tcy:`т`,tdot:`⃛`,telrec:`⌕`,Tfr:`𝔗`,tfr:`𝔱`,there4:`∴`,Therefore:`∴`,therefore:`∴`,Theta:`Θ`,theta:`θ`,thetasym:`ϑ`,thetav:`ϑ`,thickapprox:`≈`,thicksim:`∼`,ThickSpace:`  `,thinsp:` `,ThinSpace:` `,thkap:`≈`,thksim:`∼`,THORN:`Þ`,thorn:`þ`,Tilde:`∼`,tilde:`˜`,TildeEqual:`≃`,TildeFullEqual:`≅`,TildeTilde:`≈`,times:`×`,timesb:`⊠`,timesbar:`⨱`,timesd:`⨰`,tint:`∭`,toea:`⤨`,top:`⊤`,topbot:`⌶`,topcir:`⫱`,Topf:`𝕋`,topf:`𝕥`,topfork:`⫚`,tosa:`⤩`,tprime:`‴`,TRADE:`™`,trade:`™`,triangle:`▵`,triangledown:`▿`,triangleleft:`◃`,trianglelefteq:`⊴`,triangleq:`≜`,triangleright:`▹`,trianglerighteq:`⊵`,tridot:`◬`,trie:`≜`,triminus:`⨺`,TripleDot:`⃛`,triplus:`⨹`,trisb:`⧍`,tritime:`⨻`,trpezium:`⏢`,Tscr:`𝒯`,tscr:`𝓉`,TScy:`Ц`,tscy:`ц`,TSHcy:`Ћ`,tshcy:`ћ`,Tstrok:`Ŧ`,tstrok:`ŧ`,twixt:`≬`,twoheadleftarrow:`↞`,twoheadrightarrow:`↠`,Uacute:`Ú`,uacute:`ú`,Uarr:`↟`,uArr:`⇑`,uarr:`↑`,Uarrocir:`⥉`,Ubrcy:`Ў`,ubrcy:`ў`,Ubreve:`Ŭ`,ubreve:`ŭ`,Ucirc:`Û`,ucirc:`û`,Ucy:`У`,ucy:`у`,udarr:`⇅`,Udblac:`Ű`,udblac:`ű`,udhar:`⥮`,ufisht:`⥾`,Ufr:`𝔘`,ufr:`𝔲`,Ugrave:`Ù`,ugrave:`ù`,uHar:`⥣`,uharl:`↿`,uharr:`↾`,uhblk:`▀`,ulcorn:`⌜`,ulcorner:`⌜`,ulcrop:`⌏`,ultri:`◸`,Umacr:`Ū`,umacr:`ū`,uml:`¨`,UnderBar:`_`,UnderBrace:`⏟`,UnderBracket:`⎵`,UnderParenthesis:`⏝`,Union:`⋃`,UnionPlus:`⊎`,Uogon:`Ų`,uogon:`ų`,Uopf:`𝕌`,uopf:`𝕦`,UpArrow:`↑`,Uparrow:`⇑`,uparrow:`↑`,UpArrowBar:`⤒`,UpArrowDownArrow:`⇅`,UpDownArrow:`↕`,Updownarrow:`⇕`,updownarrow:`↕`,UpEquilibrium:`⥮`,upharpoonleft:`↿`,upharpoonright:`↾`,uplus:`⊎`,UpperLeftArrow:`↖`,UpperRightArrow:`↗`,Upsi:`ϒ`,upsi:`υ`,upsih:`ϒ`,Upsilon:`Υ`,upsilon:`υ`,UpTee:`⊥`,UpTeeArrow:`↥`,upuparrows:`⇈`,urcorn:`⌝`,urcorner:`⌝`,urcrop:`⌎`,Uring:`Ů`,uring:`ů`,urtri:`◹`,Uscr:`𝒰`,uscr:`𝓊`,utdot:`⋰`,Utilde:`Ũ`,utilde:`ũ`,utri:`▵`,utrif:`▴`,uuarr:`⇈`,Uuml:`Ü`,uuml:`ü`,uwangle:`⦧`,vangrt:`⦜`,varepsilon:`ϵ`,varkappa:`ϰ`,varnothing:`∅`,varphi:`ϕ`,varpi:`ϖ`,varpropto:`∝`,vArr:`⇕`,varr:`↕`,varrho:`ϱ`,varsigma:`ς`,varsubsetneq:`⊊︀`,varsubsetneqq:`⫋︀`,varsupsetneq:`⊋︀`,varsupsetneqq:`⫌︀`,vartheta:`ϑ`,vartriangleleft:`⊲`,vartriangleright:`⊳`,Vbar:`⫫`,vBar:`⫨`,vBarv:`⫩`,Vcy:`В`,vcy:`в`,VDash:`⊫`,Vdash:`⊩`,vDash:`⊨`,vdash:`⊢`,Vdashl:`⫦`,Vee:`⋁`,vee:`∨`,veebar:`⊻`,veeeq:`≚`,vellip:`⋮`,Verbar:`‖`,verbar:`|`,Vert:`‖`,vert:`|`,VerticalBar:`∣`,VerticalLine:`|`,VerticalSeparator:`❘`,VerticalTilde:`≀`,VeryThinSpace:` `,Vfr:`𝔙`,vfr:`𝔳`,vltri:`⊲`,vnsub:`⊂⃒`,vnsup:`⊃⃒`,Vopf:`𝕍`,vopf:`𝕧`,vprop:`∝`,vrtri:`⊳`,Vscr:`𝒱`,vscr:`𝓋`,vsubnE:`⫋︀`,vsubne:`⊊︀`,vsupnE:`⫌︀`,vsupne:`⊋︀`,Vvdash:`⊪`,vzigzag:`⦚`,Wcirc:`Ŵ`,wcirc:`ŵ`,wedbar:`⩟`,Wedge:`⋀`,wedge:`∧`,wedgeq:`≙`,weierp:`℘`,Wfr:`𝔚`,wfr:`𝔴`,Wopf:`𝕎`,wopf:`𝕨`,wp:`℘`,wr:`≀`,wreath:`≀`,Wscr:`𝒲`,wscr:`𝓌`,xcap:`⋂`,xcirc:`◯`,xcup:`⋃`,xdtri:`▽`,Xfr:`𝔛`,xfr:`𝔵`,xhArr:`⟺`,xharr:`⟷`,Xi:`Ξ`,xi:`ξ`,xlArr:`⟸`,xlarr:`⟵`,xmap:`⟼`,xnis:`⋻`,xodot:`⨀`,Xopf:`𝕏`,xopf:`𝕩`,xoplus:`⨁`,xotime:`⨂`,xrArr:`⟹`,xrarr:`⟶`,Xscr:`𝒳`,xscr:`𝓍`,xsqcup:`⨆`,xuplus:`⨄`,xutri:`△`,xvee:`⋁`,xwedge:`⋀`,Yacute:`Ý`,yacute:`ý`,YAcy:`Я`,yacy:`я`,Ycirc:`Ŷ`,ycirc:`ŷ`,Ycy:`Ы`,ycy:`ы`,yen:`¥`,Yfr:`𝔜`,yfr:`𝔶`,YIcy:`Ї`,yicy:`ї`,Yopf:`𝕐`,yopf:`𝕪`,Yscr:`𝒴`,yscr:`𝓎`,YUcy:`Ю`,yucy:`ю`,Yuml:`Ÿ`,yuml:`ÿ`,Zacute:`Ź`,zacute:`ź`,Zcaron:`Ž`,zcaron:`ž`,Zcy:`З`,zcy:`з`,Zdot:`Ż`,zdot:`ż`,zeetrf:`ℨ`,ZeroWidthSpace:`​`,Zeta:`Ζ`,zeta:`ζ`,Zfr:`ℨ`,zfr:`𝔷`,ZHcy:`Ж`,zhcy:`ж`,zigrarr:`⇝`,Zopf:`ℤ`,zopf:`𝕫`,Zscr:`𝒵`,zscr:`𝓏`,zwj:`‍`,zwnj:`‌`}),e.entityMap=e.HTML_ENTITIES})),AI=t((e=>{var t=TI(),n=DI(),r=EI(),i=t.isHTMLEscapableRawTextElement,a=t.isHTMLMimeType,o=t.isHTMLRawTextElement,s=t.hasOwn,c=t.NAMESPACE,l=r.ParseError,u=r.DOMException,d=0,f=1,p=2,m=3,h=4,g=5,_=6,v=7;function y(){}y.prototype={parse:function(e,t,n){var r=this.domBuilder;r.startDocument(),E(t,t=Object.create(null)),x(e,t,n,r,this.errorHandler),r.endDocument()}};var b=/&#?\w+;?/g;function x(e,r,i,o,c){var d=a(o.mimeType);e.indexOf(n.UNICODE_REPLACEMENT_CHARACTER)>=0&&c.warning(`Unicode replacement character detected, source encoding issues?`);function f(e){if(e>65535){e-=65536;var t=55296+(e>>10),n=56320+(e&1023);return String.fromCharCode(t,n)}return String.fromCharCode(e)}function p(e){var t=e[e.length-1]===`;`?e:e+`;`;if(!d&&t!==e)return c.error(`EntityRef: expecting ;`),e;var r=n.Reference.exec(t);if(!r||r[0].length!==t.length)return c.error(`entity not matching Reference production: `+e),e;var a=t.slice(1,-1);return s(i,a)?i[a]:a.charAt(0)===`#`?f(parseInt(a.substring(1).replace(`x`,`0x`))):(c.error(`entity not found:`+e),e)}function m(t){if(t>D){var n=e.substring(D,t).replace(b,p);v&&y(D),o.characters(n,0,t-D),D=t}}var h=0,g=0,_=/\r\n?|\n|$/g,v=o.locator;function y(t,n){for(;t>=g&&(n=_.exec(e));)h=g,g=n.index+n[0].length,v.lineNumber++;v.columnNumber=t-h+1}for(var x=[{currentNSMap:r}],E=[],D=0;;){try{var O=e.indexOf(`<`,D);if(O<0){if(!d&&E.length>0)return c.fatalError(`unclosed xml tag(s): `+E.join(`, `));if(!e.substring(D).match(/^\s*$/)){var M=o.doc,ee=M.createTextNode(e.substring(D));if(M.documentElement)return c.error(`Extra content at the end of the document`);M.appendChild(ee),o.currentElement=ee}return}if(O>D){var te=e.substring(D,O);!d&&E.length===0&&(te=te.replace(new RegExp(n.S_OPT.source,`g`),``),te&&c.error(`Unexpected content outside root element: '`+te+`'`)),m(O)}switch(e.charAt(O+1)){case`/`:var N=e.indexOf(`>`,O+2),ne=e.substring(O+2,N>0?N:void 0);if(!ne)return c.fatalError(`end tag name missing`);var re=n.reg(`^`,n.QName_group,n.S_OPT,`$`),ie=N>0&&re.exec(ne);if(!ie){var ae=N>0&&n.reg(`^`,n.QName_group).exec(ne);if(d&&ae)c.warning(`end tag name contains invalid trailing characters: "`+ne+`"`),ie=ae;else if(ae&&new RegExp(re.source,re.flags+`m`).test(ne))c.error(`end tag name is followed by a line break and trailing content: "`+ne+`"`),ie=ae;else return c.fatalError(`end tag name contains invalid characters: "`+ne+`"`)}if(!o.currentElement&&!o.doc.documentElement)return;var oe=E[E.length-1]||o.currentElement.tagName||o.doc.documentElement.tagName||``;if(oe!==ie[1]){var se=ie[1].toLowerCase();if(!d||oe.toLowerCase()!==se)return c.fatalError(`Opening and ending tag mismatch: "`+oe+`" != "`+ne+`"`)}var ce=x.pop();E.pop();var le=ce.localNSMap;if(o.endElement(ce.uri,ce.localName,oe),le)for(var ue in le)s(le,ue)&&o.endPrefixMapping(ue);N++;break;case`?`:v&&y(O),N=A(e,O,o,c);break;case`!`:v&&y(O),N=k(e,O,o,c,d);break;default:v&&y(O);var de=new j,fe=x[x.length-1].currentNSMap,N=C(e,O,de,fe,p,c,d),pe=de.length;if(de.closed||(d&&t.isHTMLVoidElement(de.tagName)?de.closed=!0:E.push(de.tagName)),v&&pe){for(var me=S(v,{}),he=0;heD?D=N:m(Math.max(O,D)+1)}}function S(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function C(e,t,n,r,i,a,o){function c(e,t,r){if(s(n.attributeNames,e))return a.fatalError(`Attribute `+e+` redefined`);if(!o&&t.indexOf(`<`)>=0)return a.fatalError(`Unescaped '<' not allowed in attributes values`);n.addValue(e,t.replace(/[\t\n\r]/g,` `).replace(b,i),r)}for(var l,u,y=++t,x=d;;){var S=e.charAt(y);if(x===d&&S===`<`)throw Error(`unexpected < in tag name: `+e.slice(t,y));switch(S){case`=`:if(x===f)l=e.slice(t,y),x=m;else if(x===p)x=m;else throw Error(`attribute equal must after attrName`);break;case`'`:case`"`:if(x===m||x===f){if(x===f&&(a.warning(`attribute value must after "="`),l=e.slice(t,y)),t=y+1,y=e.indexOf(S,t),y>0)u=e.slice(t,y),c(l,u,t-1),x=g;else throw Error(`attribute value no end '`+S+`' match`)}else if(x==h)u=e.slice(t,y),c(l,u,t),a.warning(`attribute "`+l+`" missed start quot(`+S+`)!!`),t=y+1,x=g;else throw Error(`attribute value must after "="`);break;case`/`:switch(x){case d:n.setTagName(e.slice(t,y));case g:case _:case v:x=v,n.closed=!0;case h:case f:break;case p:n.closed=!0;break;default:throw Error(`attribute invalid close char('/')`)}break;case``:return a.error(`unexpected end of input`),x==d&&n.setTagName(e.slice(t,y)),y;case`>`:switch(x){case d:n.setTagName(e.slice(t,y));case g:case _:case v:break;case h:case f:u=e.slice(t,y),u.slice(-1)===`/`&&(n.closed=!0,u=u.slice(0,-1));case p:x===p&&(u=l),x==h?(a.warning(`attribute "`+u+`" missed quot(")!`),c(l,u,t)):(o||a.warning(`attribute "`+u+`" missed value!! "`+u+`" instead!!`),c(u,u,t));break;case m:if(!o)return a.fatalError(`AttValue: ' or " expected`)}return y;case`€`:S=` `;default:if(S<=` `)switch(x){case d:n.setTagName(e.slice(t,y)),x=_;break;case f:l=e.slice(t,y),x=p;break;case h:var u=e.slice(t,y);a.warning(`attribute "`+u+`" missed quot(")!!`),c(l,u,t);case g:x=_}else switch(x){case p:o||a.warning(`attribute "`+l+`" missed value!! "`+l+`" instead2!!`),c(l,l,t),t=y,x=f;break;case g:a.warning(`attribute space is required"`+l+`"!!`);case _:x=f,t=y;break;case m:x=h,t=y;break;case v:throw Error(`elements closed character '/' and '>' must be connected to`)}}y++}}function w(e,t,n){for(var r=e.tagName,i=null,a=e.length;a--;){var o=e[a],l=o.qName,u=o.value,d=l.indexOf(`:`);if(d>0)var f=o.prefix=l.slice(0,d),p=l.slice(d+1),m=f===`xmlns`&&p;else p=l,f=null,m=l===`xmlns`&&``;o.localName=p,m!==!1&&(i??(i=Object.create(null),n=Object.create(n)),n[m]=i[m]=u,o.uri=c.XMLNS,t.startPrefixMapping(m,u))}for(var a=e.length;a--;)o=e[a],o.prefix&&(o.prefix===`xml`&&(o.uri=c.XML),o.prefix!==`xmlns`&&(o.uri=n[o.prefix]));var d=r.indexOf(`:`);d>0?(f=e.prefix=r.slice(0,d),p=e.localName=r.slice(d+1)):(f=null,p=e.localName=r);var h=e.uri=n[f||``];if(t.startElement(h,p,r,e),e.closed){if(t.endElement(h,p,r),i)for(f in i)s(i,f)&&t.endPrefixMapping(f)}else return e.currentNSMap=n,e.localNSMap=i,!0}function T(e,t,n,r,a){var s=i(n);if(s||o(n)){var c=RegExp(``,`ig`);c.lastIndex=t;var l=c.exec(e),u=l?l.index:-1;if(u<0)return t+1;var d=e.substring(t+1,u);return s&&(d=d.replace(b,r)),a.characters(d,0,d.length),u}return t+1}function E(e,t){for(var n in e)s(e,n)&&(t[n]=e[n])}function D(e,t){var r=t;function i(t){return t||=0,e.charAt(r+t)}function a(e){e||=1,r+=e}function o(){for(var t=0;r`?(o.skip(1),r.startDTD(l.name,l.publicId,l.systemId,l.internalSubset),r.endDTD(),o.getIndex()):i.fatalError(`doctype not terminated with > at position `+o.getIndex());default:return i.fatalError(`Not well-formed XML starting with "0)return i.fatalError(`processing instruction at position `+t+` is an xml declaration which is only at the start of the document`);if(!n.XMLDecl.test(e.substring(t)))return i.fatalError(`xml declaration is not well-formed`)}return r.processingInstruction(a[1],a[2]),t+a[0].length}function j(){this.attributeNames=Object.create(null)}j.prototype={setTagName:function(e){if(!n.QName_exact.test(e))throw Error(`invalid tagName:`+e);this.tagName=e},addValue:function(e,t,r){if(!n.QName_exact.test(e))throw Error(`invalid attribute:`+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}},e.XMLReader=y,e.parseUtils=D,e.parseDoctypeCommentOrCData=k})),jI=t((e=>{var t=TI(),n=OI(),r=EI(),i=kI(),a=AI(),o=n.DOMImplementation,s=t.hasDefaultHTMLNamespace,c=t.isHTMLMimeType,l=t.isValidMimeType,u=t.MIME_TYPE,d=t.NAMESPACE,f=r.ParseError,p=a.XMLReader;function m(e){return e.replace(/\r[\n\u0085]/g,` +`).replace(/[\r\u0085\u2028\u2029]/g,` +`)}function h(e){if(e||={},e.locator===void 0&&(e.locator=!0),this.assign=e.assign||t.assign,this.domHandler=e.domHandler||g,this.onError=e.onError||e.errorHandler,e.errorHandler&&typeof e.errorHandler!=`function`)throw TypeError(`errorHandler object is no longer supported, switch to onError!`);e.errorHandler&&e.errorHandler(`warning`,"The `errorHandler` option has been deprecated, use `onError` instead!",this),this.normalizeLineEndings=e.normalizeLineEndings||m,this.locator=!!e.locator,this.xmlns=this.assign(Object.create(null),e.xmlns)}h.prototype.parseFromString=function(e,n){if(!l(n))throw TypeError(`DOMParser.parseFromString: the provided mimeType "`+n+`" is not valid.`);var r=this.assign(Object.create(null),this.xmlns),a=i.XML_ENTITIES,o=r[``]||null;s(n)?(a=i.HTML_ENTITIES,o=d.HTML):n===u.XML_SVG_IMAGE&&(o=d.SVG),r[``]=o,r.xml=r.xml||d.XML;var c=new this.domHandler({mimeType:n,defaultNamespace:o,onError:this.onError}),f=this.locator?{}:void 0;this.locator&&c.setDocumentLocator(f);var m=new p;return m.errorHandler=c,m.domBuilder=c,!t.isHTMLMimeType(n)&&typeof e!=`string`&&m.errorHandler.fatalError(`source is not a string`),m.parse(this.normalizeLineEndings(String(e)),r,a),c.doc.documentElement||m.errorHandler.fatalError(`missing root element`),c.doc};function g(e){var t=e||{};this.mimeType=t.mimeType||u.XML_APPLICATION,this.defaultNamespace=t.defaultNamespace||null,this.cdata=!1,this.currentElement=void 0,this.doc=void 0,this.locator=void 0,this.onError=t.onError}function _(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}g.prototype={startDocument:function(){var e=new o;this.doc=c(this.mimeType)?e.createHTMLDocument(!1):e.createDocument(this.defaultNamespace,``)},startElement:function(e,t,n,r){var i=this.doc,a=i.createElementNS(e,n||t),o=r.length;b(this,a),this.currentElement=a,this.locator&&_(this.locator,a);for(var s=0;s=t+n||t?new java.lang.String(e,t,n)+``:e}`endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl`.replace(/\w+/g,function(e){g.prototype[e]=function(){return null}});function b(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}function x(e){if(e===`error`)throw`onErrorStopParsing`}function S(){throw`onWarningStopParsing`}e.__DOMHandler=g,e.DOMParser=h,e.normalizeLineEndings=m,e.onErrorStopParsing=x,e.onWarningStopParsing=S})),MI=t((e=>{var t=TI();e.assign=t.assign,e.hasDefaultHTMLNamespace=t.hasDefaultHTMLNamespace,e.isHTMLMimeType=t.isHTMLMimeType,e.isValidMimeType=t.isValidMimeType,e.MIME_TYPE=t.MIME_TYPE,e.NAMESPACE=t.NAMESPACE;var n=EI();e.DOMException=n.DOMException,e.DOMExceptionName=n.DOMExceptionName,e.ExceptionCode=n.ExceptionCode,e.ParseError=n.ParseError;var r=OI();e.Attr=r.Attr,e.CDATASection=r.CDATASection,e.CharacterData=r.CharacterData,e.Comment=r.Comment,e.Document=r.Document,e.DocumentFragment=r.DocumentFragment,e.DocumentType=r.DocumentType,e.DOMImplementation=r.DOMImplementation,e.Element=r.Element,e.Entity=r.Entity,e.EntityReference=r.EntityReference,e.LiveNodeList=r.LiveNodeList,e.NamedNodeMap=r.NamedNodeMap,e.Node=r.Node,e.NodeList=r.NodeList,e.Notation=r.Notation,e.ProcessingInstruction=r.ProcessingInstruction,e.Text=r.Text,e.XMLSerializer=r.XMLSerializer;var i=jI();e.DOMParser=i.DOMParser,e.normalizeLineEndings=i.normalizeLineEndings,e.onErrorStopParsing=i.onErrorStopParsing,e.onWarningStopParsing=i.onWarningStopParsing}))();const NI=e=>typeof e==`string`?e:(e??[]).filter(e=>e.type===`text`).map(e=>e.text).join(` +`);function PI(e){let t=e.messages.filter(e=>e.role!==`assistant`||![`error`,`aborted`].includes(e.stopReason));return[{role:`system`,content:e.systemPrompt},...t.map(e=>e.role===`toolResult`?{role:`tool`,content:JSON.stringify({name:e.toolName,isError:e.isError,output:NI(e.content)})}:e.role===`assistant`?{role:`assistant`,reasoning_content:e.content.filter(e=>e.type===`thinking`).map(e=>e.thinking).join(` +`),content:e.content.map(e=>e.type===`text`?e.text:e.type===`toolCall`?``:``).join(``),tool_calls:e.content.filter(e=>e.type===`toolCall`).map(e=>({type:`function`,function:{name:e.name,arguments:e.arguments}}))}:{role:`user`,content:NI(e.content)})]}function FI(e,t){let n=t;for(;n`,n);if(r<0)throw Error(`Incomplete tool call. No command was executed. Try again with a shorter task.`);if(t<0||t>r)return r+11;let i=e.indexOf(`]]>`,t+9);if(i<0)throw Error(`Incomplete CDATA in tool call. No command was executed.`);n=i+3}}function II(e,t){let n=null,r=0;for(let i=t;i=n.length&&(n=null):n=r,i+=t.length+1;continue}}if(n){i++;continue}if(e[i]==="`"){let t=/^`+/.exec(e.slice(i))[0].length;r?r===t&&(r=0):r=t,i+=t;continue}if(!r&&/^\n?/.exec(e);if(!t&&!n)return{thinking:``,answer:e,complete:!0};let r=n?.[0].length??0,i=e.indexOf(``,r);return i<0?{thinking:e.slice(r),answer:``,complete:!1}:{thinking:e.slice(r,i),answer:e.slice(i+8),complete:!0}}function RI(e,t,n){e=e.replace(/<\|im_end\|>$|<\/s>$/,``);let r=LI(e,n);if(!r.complete)throw Error(`The model used its response budget before finishing its thoughts. Try a smaller task.`);e=r.answer;let i=r.thinking.trim()?[{type:`thinking`,thinking:r.thinking.trim()}]:[],a=0;for(;ao.push(t)}).parseFromString(e.slice(n,r),`application/xml`);if(o.length||s.doctype||s.documentElement.tagName!==`function`)throw Error(`Malformed model tool call.`);let c=s.documentElement,l=c.getAttribute(`name`),u=t.find(e=>e.name===l);if(!u)throw Error(`Unknown model tool: `+l);let d=Object.create(null);for(let e of Array.from(c.childNodes)){if(e.nodeType===3&&!e.textContent.trim())continue;if(e.nodeType!==1||e.tagName!==`param`)throw Error(`Unexpected content in tool call.`);let t=e.getAttribute(`name`);if(Object.hasOwn(d,t)||!Object.hasOwn(u.parameters.properties,t))throw Error(`Unknown or duplicate tool parameter: `+t);if(Array.from(e.childNodes).some(e=>![3,4].includes(e.nodeType)))throw Error(`Tool values containing XML must use CDATA.`);d[t]=u.parameters.properties[t].type===`string`?e.textContent:JSON.parse(e.textContent)}i.push({type:`toolCall`,id:crypto.randomUUID(),name:l,arguments:d}),a=r}return i}function zI(e,t,n){let r=[...e.messages],i=0;for(;;){let a=t(PI({...e,messages:r}));if(a.input_ids.dims[1]<=n)return{inputs:a,dropped:i};let o=r.findIndex((e,t)=>t>0&&e.role===`user`);if(o<0)throw Error(`This task exceeds the browser context budget. Start a new chat or use smaller files and shorter tool output.`);r.splice(0,o),i+=o}}const BI=8192;function VI(e=.95){if(!(e>0&&e<=1))throw Error(`topP must be in (0, 1].`);let t;return(n,r)=>{if(e===1)return r;let i=r.dims.at(-1);t??=new Float32Array(i),t.length!==i&&(t=new Float32Array(i));for(let n=0;n=l?t[u++]=a[e]:d+=Math.exp(a[e]-o);if(d<=c)break;l-=8}while(1);t.subarray(0,u).sort();let f=0;for(;fc)break;d=e,f++}let p=f?t[f-1]:l,m=0;for(let e=f-1;e>=0&&t[e]===p;e--)m++;for(let e=0;e0)&&(a[e]=-1/0)}return r}}var HI=class{constructor(e=1e3,t=250){this.windowMs=e,this.minimumMs=t,this.total=0,this.firstAt=null,this.points=[]}add(e,t){e>0&&(this.firstAt??=t,this.total+=e,this.points.push({at:t,total:this.total}),this.prune(t))}prune(e){let t=e-this.windowMs;for(;this.points.length>1&&this.points[1].at<=t;)this.points.shift()}rate(e){if(this.firstAt===null||e-this.firstAt{let i=await navigator.gpu?.requestAdapter({powerPreference:`high-performance`});if(!i)throw Error(`WebGPU is unavailable. Try an up-to-date browser with GPU acceleration enabled.`);if(!i.features.has(`shader-f16`))throw Error(`This model requires WebGPU shader-f16 support on your device.`);if(c){let e=GPUAdapter.prototype.requestDevice;GPUAdapter.prototype.requestDevice=function(t={}){return e.call(this,{...t,requiredLimits:{...t.requiredLimits,maxStorageBufferBindingSize:128*1024**2,maxBufferSize:256*1024**2}})}}r={vendor:i.info.vendor,architecture:i.info.architecture,maxStorageBufferBindingSize:i.limits.maxStorageBufferBindingSize,features:[...i.features]},e({type:`device`,device:r});let d=o&&[`localhost`,`127.0.0.1`].includes(new URL(s).hostname);jb.allowRemoteModels=!0,jb.allowLocalModels=!1,jb.remoteHost=d?s+`/`:`https://huggingface.co/`,jb.remotePathTemplate=d?`models/{model}/`:`{model}/resolve/${mI}/`;let f=d?`minicpm5-webgpu`:hI;jb.customCache=await bI(jb.remoteHost+jb.remotePathTemplate.replace(`{model}`,f),{signal:u,cachedOnly:l,onProgress:t=>e({type:`load_progress`,...t})}),jb.useCustomCache=!0,jb.useBrowserCache=!1,jb.backends.onnx.wasm.wasmPaths=a,jb.backends.onnx.wasm.numThreads=1,u.throwIfAborted(),e({type:`load_progress`,phase:`compile`}),[n,t]=await Promise.all([WT.from_pretrained(f),rF.from_pretrained(f,{device:`webgpu`,dtype:`q4f16`})]),u.throwIfAborted(),e({type:`load_progress`,phase:`warmup`});let p=n(`Hello`);await t.generate({...p,max_new_tokens:1,do_sample:!1,top_k:0}),u.throwIfAborted();let m=jb.backends.onnx.webgpu.device;r.actualLimits={maxStorageBufferBindingSize:m?.limits.maxStorageBufferBindingSize,maxBufferSize:m?.limits.maxBufferSize},m?.lost.then(t=>{t.reason!==`destroyed`&&e({type:`fatal`,error:`GPU device was lost. Reload this page to reload the cached model.`})}),e({type:`loaded`,device:r,cachedBytes:jb.customCache.cachedBytes})})().catch(async e=>{throw await t?.dispose().catch(()=>{}),t=void 0,n=void 0,u.aborted?new DOMException(`Stopped.`,`AbortError`):e}).finally(()=>{i=void 0}),i)}function s(r,i,o={}){let s=new yl,c={role:`assistant`,api:r.api,provider:r.provider,model:r.id,timestamp:Date.now(),content:[],usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}};return(async()=>{let r=()=>a.interrupt(),l=new HI,u,d=0,f=(t=!1)=>{let n=performance.now();!t&&n-d<80||(d=n,e({type:`context_usage`,inputTokens:c.usage.input,outputTokens:c.usage.output}))};try{if(!t)throw Error(`Load the model first.`);a.reset(),o.signal?.throwIfAborted(),o.signal?.addEventListener(`abort`,r,{once:!0}),e({type:`inference_activity`,phase:`prefill`});let d=Math.min(o.maxTokens??UI,UI),p=i.tools??[],m=p.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}})),{inputs:h,dropped:g}=zI(i,e=>n.apply_chat_template(e,{tools:m,enable_thinking:!0,add_generation_prompt:!0,return_dict:!0}),BI-d);g&&e({type:`context_trim`,dropped:g}),c.usage.input=h.input_ids.dims[1],c.usage.totalTokens=c.usage.input,f(!0),s.push({type:`start`,partial:structuredClone(c)});let _=``,v=``,y=!1,b=``,x=!1,S=!1,C=0,w=performance.now(),T,E=new KF(n,{skip_prompt:!0,skip_special_tokens:!1,token_callback_function:t=>{if(!t.length)return;let n=performance.now();T??=n-w,l.add(t.length,n),u===void 0&&(e({type:`inference_activity`,phase:`decode`,rate:null,outputTokens:l.total}),u=setInterval(()=>e({type:`inference_activity`,phase:`decode`,rate:l.rate(performance.now()),outputTokens:l.total}),250)),c.usage.output+=t.length,c.usage.totalTokens=c.usage.input+c.usage.output,f()},callback_function:e=>{_+=e;let t=LI(_,{thinkingPrefilled:!0}),n=t.complete?t.thinking:t.thinking.slice(0,Math.max(0,t.thinking.length-8));if(n.length>b.length&&(x||(c.content=[{type:`thinking`,thinking:``}],s.push({type:`thinking_start`,contentIndex:0,partial:structuredClone(c)}),x=!0,C=1),c.content[0].thinking=n,s.push({type:`thinking_delta`,contentIndex:0,delta:n.slice(b.length),partial:structuredClone(c)}),b=n),!t.complete)return;x&&!S&&(s.push({type:`thinking_end`,contentIndex:0,content:b,partial:structuredClone(c)}),S=!0);let r=t.answer.split(`<`)[0];r.length<=v.length||(y||=(c.content.push({type:`text`,text:``}),s.push({type:`text_start`,contentIndex:C,partial:structuredClone(c)}),!0),c.content[C].text=r,s.push({type:`text_delta`,contentIndex:C,delta:r.slice(v.length),partial:structuredClone(c)}),v=r)}}),D=(await t.generate({...h,max_new_tokens:d,do_sample:!0,temperature:1,top_p:.95,top_k:0,repetition_penalty:1,logits_processor:[VI(.95)],eos_token_id:[1,130073],streamer:E,stopping_criteria:a})).tolist()[0].slice(h.input_ids.dims[1]).map(Number);c.usage.output=D.length,c.usage.totalTokens=c.usage.input+D.length,f(!0),o.signal?.throwIfAborted(),_=n.decode(D,{skip_special_tokens:!1});let O=RI(_,p,{thinkingPrefilled:!0});y&&s.push({type:`text_end`,contentIndex:C,content:v,partial:structuredClone(c)}),c.content=O;let k=O.some(e=>e.type===`toolCall`),A=[1,130073].includes(D.at(-1));if(k&&!A)throw Error(`The tool response exceeded the output limit. No tool was executed. Try a smaller edit.`);c.stopReason=k?`toolUse`:A?`stop`:`length`;for(let[e,t]of O.entries())t.type===`toolCall`&&(s.push({type:`toolcall_start`,contentIndex:e,partial:structuredClone(c)}),s.push({type:`toolcall_end`,contentIndex:e,toolCall:t,partial:structuredClone(c)}));e({type:`generation`,raw:_,thinking:!0,sampling:{temperature:1,topP:.95,topK:0,minP:0,repetitionPenalty:1},inputTokens:c.usage.input,outputTokens:D.length,elapsedMs:performance.now()-w,firstTokenMs:T,stopReason:c.stopReason}),s.push({type:`done`,reason:c.stopReason,message:c}),s.end(c)}catch(e){c.usage.input&&f(!0),c.content=c.content.filter(e=>e.type!==`toolCall`),c.stopReason=o.signal?.aborted?`aborted`:`error`,c.errorMessage=o.signal?.aborted?`Stopped.`:String(e.message??e),s.push({type:`error`,reason:c.stopReason,error:c}),s.end(c)}finally{clearInterval(u),e({type:`inference_activity`,phase:`end`}),o.signal?.removeEventListener(`abort`,r)}})(),s}return{load:o,streamFn:s,stop:()=>a.interrupt(),get device(){return r}}}var KI=t((e=>{(function(){var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function n(e){return i(o(e),arguments)}function r(e,t){return n.apply(null,[e].concat(t||[]))}function i(e,r){for(var i=1,a=e.length,o,s=``,c=0,l,u,d,f,p,m,h;c=0),u.type){case`b`:o=parseInt(o,10).toString(2);break;case`c`:o=String.fromCharCode(parseInt(o,10));break;case`d`:case`i`:o=parseInt(o,10);break;case`j`:o=JSON.stringify(o,null,u.width?parseInt(u.width):0);break;case`e`:o=u.precision?parseFloat(o).toExponential(u.precision):parseFloat(o).toExponential();break;case`f`:o=u.precision?parseFloat(o).toFixed(u.precision):parseFloat(o);break;case`g`:o=u.precision?String(Number(o.toPrecision(u.precision))):parseFloat(o);break;case`o`:o=(parseInt(o,10)>>>0).toString(8);break;case`s`:o=String(o),o=u.precision?o.substring(0,u.precision):o;break;case`t`:o=String(!!o),o=u.precision?o.substring(0,u.precision):o;break;case`T`:o=Object.prototype.toString.call(o).slice(8,-1).toLowerCase(),o=u.precision?o.substring(0,u.precision):o;break;case`u`:o=parseInt(o,10)>>>0;break;case`v`:o=o.valueOf(),o=u.precision?o.substring(0,u.precision):o;break;case`x`:o=(parseInt(o,10)>>>0).toString(16);break;case`X`:o=(parseInt(o,10)>>>0).toString(16).toUpperCase()}t.json.test(u.type)?s+=o:(t.number.test(u.type)&&(!m||u.sign)?(h=m?`+`:`-`,o=o.toString().replace(t.sign,``)):h=``,f=u.pad_char?u.pad_char===`0`?`0`:u.pad_char.charAt(1):` `,p=u.width-(h+o).length,d=u.width&&p>0?f.repeat(p):``,s+=u.align?h+o+d:f===`0`?h+d+o:d+h+o)}return s}var a=Object.create(null);function o(e){if(a[e])return a[e];for(var n=e,r,i=[],o=0;n;){if((r=t.text.exec(n))!==null)i.push(r[0]);else if((r=t.modulo.exec(n))!==null)i.push(`%`);else if((r=t.placeholder.exec(n))!==null){if(r[2]){o|=1;var s=[],c=r[2],l=[];if((l=t.key.exec(c))!==null)for(s.push(l[1]);(c=c.substring(l[0].length))!==``;)if((l=t.key_access.exec(c))!==null)s.push(l[1]);else if((l=t.index_access.exec(c))!==null)s.push(l[1]);else throw SyntaxError(`[sprintf] failed to parse named argument key`);else throw SyntaxError(`[sprintf] failed to parse named argument key`);r[2]=s}else o|=2;if(o===3)throw Error(`[sprintf] mixing positional and named placeholders is not (yet) supported`);i.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}else throw SyntaxError(`[sprintf] unexpected placeholder`);n=n.substring(r[0].length)}return a[e]=i}e!==void 0&&(e.sprintf=n,e.vsprintf=r),typeof window<`u`&&(window.sprintf=n,window.vsprintf=r,typeof define==`function`&&define.amd&&define(function(){return{sprintf:n,vsprintf:r}}))})()}))();const qI=(e,t,n)=>{let r=e instanceof RegExp?JI(e,n):e,i=t instanceof RegExp?JI(t,n):t,a=r!==null&&i!=null&&YI(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},JI=(e,t)=>{let n=t.match(e);return n?n[0]:null},YI=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},XI=`\0SLASH`+Math.random()+`\0`,ZI=`\0OPEN`+Math.random()+`\0`,QI=`\0CLOSE`+Math.random()+`\0`,$I=`\0COMMA`+Math.random()+`\0`,eL=`\0PERIOD`+Math.random()+`\0`,tL=new RegExp(XI,`g`),nL=new RegExp(ZI,`g`),rL=new RegExp(QI,`g`),iL=new RegExp($I,`g`),aL=new RegExp(eL,`g`),oL=/\\\\/g,sL=/\\{/g,cL=/\\}/g,lL=/\\,/g,uL=/\\\./g;function dL(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function fL(e){return e.replace(oL,XI).replace(sL,ZI).replace(cL,QI).replace(lL,$I).replace(uL,eL)}function pL(e){return e.replace(tL,`\\`).replace(nL,`{`).replace(rL,`}`).replace(iL,`,`).replace(aL,`.`)}function mL(e){if(!e)return[``];let t=[],n=qI(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=mL(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function hL(e,t={}){if(!e)return[];let{max:n=1e5,maxLength:r=4e6}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),SL(fL(e),n,r,!0).map(pL)}function gL(e){return`{`+e+`}`}function _L(e){return/^-?0\d/.test(e)}function vL(e,t){return e<=t}function yL(e,t){return e>=t}function bL(e,t,n,r,i,a){let o=[],s=0;for(let c=0;c=r)return o;let u=e[c]+t+n[l];if(!a||u){if(s+u.length>i)return o;o.push(u),s+=u.length}}return o}function xL(e,t,n,r){let i=e.split(/\.\./),a=[];if(i[0]===void 0||i[1]===void 0)return a;let o=dL(i[0]),s=dL(i[1]),c=Math.max(i[0].length,i[1].length),l=i.length===3&&i[2]!==void 0?Math.max(Math.abs(dL(i[2])),1):1,u=vL;s0){let r=Array(t+1).join(`0`);n=e<0?`-`+r+n.slice(1):r+n}}if(f+n.length>r)break;a.push(n),f+=n.length}return a}function SL(e,t,n,r){let i=[``],a=!1,o=!0;for(;;){let s=qI(`{`,`}`,e);if(!s)return bL(i,e,[``],t,n,a);let c=s.pre;if(/\$$/.test(c)){if(i=bL(i,c+`{`+s.body+`}`,[``],t,n,a&&!s.post.length),o=!1,!s.post.length)break;e=s.post;continue}let l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),d=l||u,f=s.body.indexOf(`,`)>=0;if(!d&&!f){if(s.post.match(/,(?!,).*\}/)){e=s.pre+`{`+s.body+QI+s.post,r=!0;continue}return bL(i,c+`{`+s.body+`}`+s.post,[``],t,n,a)}o&&=(a=r&&!d,!1);let p;if(d)p=xL(s.body,u,t,n);else{let r=mL(s.body);if(r.length===1&&r[0]!==void 0&&(r=SL(r[0],t,n,!1).map(gL),r.length===1)){if(i=bL(i,c+r[0],[``],t,n,a&&!s.post.length),!s.post.length)break;e=s.post;continue}let o=a&&!s.post.length&&!c;for(let e=0;o&&e=t||l+r.length>n)break outer;p.push(r),l+=r.length}}}}if(i=bL(i,c,p,t,n,a&&!s.post.length),!s.post.length)break;e=s.post}return i}const CL=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},wL={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},TL=e=>e.replace(/[[\]\\-]/g,`\\$&`),EL=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),DL=e=>e.join(``),OL=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;ad?r.push(TL(d)+`-`+TL(t)):t===d&&r.push(TL(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(TL(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(TL(t)),a++}if(un?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var AL;const jL=new Set([`!`,`?`,`+`,`*`,`@`]),ML=e=>jL.has(e),NL=e=>ML(e.type),PL=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),FL=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),IL=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),LL=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),RL=`(?!\\.)`,zL=new Set([`[`,`.`]),BL=new Set([`..`,`.`]),VL=new Set(`().*{}+?[]^$\\!`),HL=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),UL=`[^/]+?`;let WL=0;var GL=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++WL;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.#l=this.type?this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&rtypeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;ttypeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?AL.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&BL.has(this.#r[0]))){let n=zL,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?RL:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,kL(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,kL(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?RL:``)+UL;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?RL:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,kL(i),this.#t=!!this.#t,this.#n]}#x(){if(NL(this)){let e=0,t=!1;do{t=!0;for(let e=0;e{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;sn?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),qL=(e,t,n={})=>(CL(t),!n.nocomment&&t.charAt(0)===`#`?!1:new xR(t,n).match(e)),JL=/^\*+([^+@!?*[(]*)$/,YL=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),XL=e=>t=>t.endsWith(e),ZL=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),QL=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),$L=/^\*+\.\*+$/,eR=e=>!e.startsWith(`.`)&&e.includes(`.`),tR=e=>e!==`.`&&e!==`..`&&e.includes(`.`),nR=/^\.\*+$/,rR=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),iR=/^\*+$/,aR=e=>e.length!==0&&!e.startsWith(`.`),oR=e=>e.length!==0&&e!==`.`&&e!==`..`,sR=/^\?+([^+@!?*[(]*)?$/,cR=([e,t=``])=>{let n=fR([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},lR=([e,t=``])=>{let n=pR([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},uR=([e,t=``])=>{let n=pR([e]);return t?e=>n(e)&&e.endsWith(t):n},dR=([e,t=``])=>{let n=fR([e]);return t?e=>n(e)&&e.endsWith(t):n},fR=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},pR=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},mR=typeof process==`object`&&process?{}.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,hR={win32:{sep:`\\`},posix:{sep:`/`}};qL.sep=mR===`win32`?hR.win32.sep:hR.posix.sep;const gR=Symbol(`globstar **`);qL.GLOBSTAR=gR,qL.filter=(e,t={})=>n=>qL(n,e,t);const _R=(e,t={})=>Object.assign({},e,t);qL.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return qL;let t=qL;return Object.assign((n,r,i={})=>t(n,r,_R(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,_R(e,n))}static defaults(n){return t.defaults(_R(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,_R(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,_R(e,r))}},unescape:(n,r={})=>t.unescape(n,_R(e,r)),escape:(n,r={})=>t.escape(n,_R(e,r)),filter:(n,r={})=>t.filter(n,_R(e,r)),defaults:n=>t.defaults(_R(e,n)),makeRe:(n,r={})=>t.makeRe(n,_R(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,_R(e,r)),match:(n,r,i={})=>t.match(n,r,_R(e,i)),sep:t.sep,GLOBSTAR:gR})};const vR=(e,t={})=>(CL(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:hL(e,{max:t.braceExpandMax}));qL.braceExpand=vR,qL.makeRe=(e,t={})=>new xR(e,t).makeRe(),qL.match=(e,t,n={})=>{let r=new xR(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const yR=/[?*]|[+@!]\(.*?\)|\[|\]/,bR=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var xR=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){CL(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||mR,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!yR.test(e[2]))&&!yR.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;nr&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;ee.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r=2&&(e=this.levelTwoFileOptimize(e)),t.includes(gR)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(gR,i),o=t.lastIndexOf(gR),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?bR(e):e===gR?gR:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e===gR&&a!==gR&&(a===void 0?i!==void 0&&i!==gR?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==gR&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=gR))});let i=t.filter(e=>e!==gR);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return qL.defaults(e).Minimatch}};qL.AST=GL,qL.Minimatch=xR,qL.escape=KL,qL.unescape=kL;var SR=t(((e,t)=>{t.exports={}}))();function CR(e){for(var t=1;t0&&e[t-1]===` +`;)t--;return e.substring(0,t)}function DR(e){return ER(TR(e))}var OR=`ADDRESS.ARTICLE.ASIDE.AUDIO.BLOCKQUOTE.BODY.CANVAS.CENTER.DD.DIR.DIV.DL.DT.FIELDSET.FIGCAPTION.FIGURE.FOOTER.FORM.FRAMESET.H1.H2.H3.H4.H5.H6.HEADER.HGROUP.HR.HTML.ISINDEX.LI.MAIN.MENU.NAV.NOFRAMES.NOSCRIPT.OL.OUTPUT.P.PRE.SECTION.TABLE.TBODY.TD.TFOOT.TH.THEAD.TR.UL`.split(`.`);function kR(e){return IR(e,OR)}var AR=[`AREA`,`BASE`,`BR`,`COL`,`COMMAND`,`EMBED`,`HR`,`IMG`,`INPUT`,`KEYGEN`,`LINK`,`META`,`PARAM`,`SOURCE`,`TRACK`,`WBR`];function jR(e){return IR(e,AR)}function MR(e){return LR(e,AR)}var NR=[`A`,`TABLE`,`THEAD`,`TBODY`,`TFOOT`,`TH`,`TD`,`IFRAME`,`SCRIPT`,`AUDIO`,`VIDEO`];function PR(e){return IR(e,NR)}function FR(e){return LR(e,NR)}function IR(e,t){return t.indexOf(e.nodeName)>=0}function LR(e,t){return e.getElementsByTagName&&t.some(function(t){return e.getElementsByTagName(t).length})}var RR=[[/\\/g,`\\\\`],[/\*/g,`\\*`],[/^-/g,`\\-`],[/^\+ /g,`\\+ `],[/^(=+)/g,`\\$1`],[/^(#{1,6}) /g,`\\$1 `],[/`/g,"\\`"],[/^~~~/g,`\\~~~`],[/\[/g,`\\[`],[/\]/g,`\\]`],[/^>/g,`\\>`],[/_/g,`\\_`],[/^(\d+)\. /g,`$1\\. `]];function zR(e){return RR.reduce(function(e,t){return e.replace(t[0],t[1])},e)}var BR={};BR.paragraph={filter:`p`,replacement:function(e){return` + +`+e+` + +`}},BR.lineBreak={filter:`br`,replacement:function(e,t,n){return n.br+` +`}},BR.heading={filter:[`h1`,`h2`,`h3`,`h4`,`h5`,`h6`],replacement:function(e,t,n){var r=Number(t.nodeName.charAt(1));if(n.headingStyle===`setext`&&r<3){var i=wR(r===1?`=`:`-`,e.length);return` + +`+e+` +`+i+` + +`}return` + +`+wR(`#`,r)+` `+e+` + +`}},BR.blockquote={filter:`blockquote`,replacement:function(e){return e=DR(e).replace(/^/gm,`> `),` + +`+e+` + +`}},BR.list={filter:[`ul`,`ol`],replacement:function(e,t){var n=t.parentNode;return n.nodeName===`LI`&&n.lastElementChild===t?` +`+e:` + +`+e+` + +`}},BR.listItem={filter:`li`,replacement:function(e,t,n){var r=n.bulletListMarker+` `,i=t.parentNode;if(i.nodeName===`OL`){var a=i.getAttribute(`start`),o=Array.prototype.indexOf.call(i.children,t);r=(a?Number(a)+o:o+1)+`. `}var s=/\n$/.test(e);return e=DR(e)+(s?` +`:``),e=e.replace(/\n/gm,` +`+` `.repeat(r.length)),r+e+(t.nextSibling?` +`:``)}},BR.indentedCodeBlock={filter:function(e,t){return t.codeBlockStyle===`indented`&&e.nodeName===`PRE`&&e.firstChild&&e.firstChild.nodeName===`CODE`},replacement:function(e,t,n){return` + + `+t.firstChild.textContent.replace(/\n/g,` + `)+` + +`}},BR.fencedCodeBlock={filter:function(e,t){return t.codeBlockStyle===`fenced`&&e.nodeName===`PRE`&&e.firstChild&&e.firstChild.nodeName===`CODE`},replacement:function(e,t,n){for(var r=((t.firstChild.getAttribute(`class`)||``).match(/language-(\S+)/)||[null,``])[1],i=t.firstChild.textContent,a=n.fence.charAt(0),o=3,s=RegExp(`^`+a+`{3,}`,`gm`),c;c=s.exec(i);)c[0].length>=o&&(o=c[0].length+1);var l=wR(a,o);return` + +`+l+r+` +`+i.replace(/\n$/,``)+` +`+l+` + +`}},BR.horizontalRule={filter:`hr`,replacement:function(e,t,n){return` + +`+n.hr+` + +`}},BR.inlineLink={filter:function(e,t){return t.linkStyle===`inlined`&&e.nodeName===`A`&&e.getAttribute(`href`)},replacement:function(e,t){var n=HR(t.getAttribute(`href`)),r=UR(VR(t.getAttribute(`title`))),i=r?` "`+r+`"`:``;return`[`+e+`](`+n+i+`)`}},BR.referenceLink={filter:function(e,t){return t.linkStyle===`referenced`&&e.nodeName===`A`&&e.getAttribute(`href`)},replacement:function(e,t,n){var r=HR(t.getAttribute(`href`)),i=VR(t.getAttribute(`title`));i&&=` "`+UR(i)+`"`;var a,o;switch(n.linkReferenceStyle){case`collapsed`:a=`[`+e+`][]`,o=`[`+e+`]: `+r+i;break;case`shortcut`:a=`[`+e+`]`,o=`[`+e+`]: `+r+i;break;default:var s=this.references.length+1;a=`[`+e+`][`+s+`]`,o=`[`+s+`]: `+r+i}return this.references.push(o),a},references:[],append:function(e){var t=``;return this.references.length&&(t=` + +`+this.references.join(` +`)+` + +`,this.references=[]),t}},BR.emphasis={filter:[`em`,`i`],replacement:function(e,t,n){return e.trim()?n.emDelimiter+e+n.emDelimiter:``}},BR.strong={filter:[`strong`,`b`],replacement:function(e,t,n){return e.trim()?n.strongDelimiter+e+n.strongDelimiter:``}},BR.code={filter:function(e){var t=e.previousSibling||e.nextSibling,n=e.parentNode.nodeName===`PRE`&&!t;return e.nodeName===`CODE`&&!n},replacement:function(e){if(!e)return``;e=e.replace(/\r?\n|\r/g,` `);for(var t=/^`|^ .*?[^ ].* $|`$/.test(e)?` `:``,n="`",r=e.match(/`+/gm)||[];r.indexOf(n)!==-1;)n+="`";return n+t+e+t+n}},BR.image={filter:`img`,replacement:function(e,t){var n=zR(VR(t.getAttribute(`alt`))),r=HR(t.getAttribute(`src`)||``),i=VR(t.getAttribute(`title`)),a=i?` "`+UR(i)+`"`:``;return r?`![`+n+`](`+r+a+`)`:``}};function VR(e){return e?e.replace(/(\n+\s*)+/g,` +`):``}function HR(e){var t=e.replace(/([<>()])/g,`\\$1`);return t.indexOf(` `)>=0?`<`+t+`>`:t}function UR(e){return e.replace(/"/g,`\\"`)}function WR(e){for(var t in this.options=e,this._keep=[],this._remove=[],this.blankRule={replacement:e.blankReplacement},this.keepReplacement=e.keepReplacement,this.defaultRule={replacement:e.defaultReplacement},this.array=[],e.rules)this.array.push(e.rules[t])}WR.prototype={add:function(e,t){this.array.unshift(t)},keep:function(e){this._keep.unshift({filter:e,replacement:this.keepReplacement})},remove:function(e){this._remove.unshift({filter:e,replacement:function(){return``}})},forNode:function(e){if(e.isBlank)return this.blankRule;var t;return(t=GR(this.array,e,this.options))||(t=GR(this._keep,e,this.options))||(t=GR(this._remove,e,this.options))?t:this.defaultRule},forEach:function(e){for(var t=0;t-1)return!0}else if(typeof r==`function`){if(r.call(e,t,n))return!0}else throw TypeError("`filter` needs to be a string, array, or function")}function qR(e){var t=e.element,n=e.isBlock,r=e.isVoid,i=e.isPre||function(e){return e.nodeName===`PRE`};if(t.firstChild&&!i(t)){for(var a=null,o=!1,s=null,c=YR(s,t,i);c!==t;){if(c.nodeType===3||c.nodeType===4){var l=c.data.replace(/[ \r\n\t]+/g,` `);if((!a||/ $/.test(a.data))&&!o&&l[0]===` `&&(l=l.substr(1)),!l){c=JR(c);continue}c.data=l,a=c}else if(c.nodeType===1)n(c)||c.nodeName===`BR`?(a&&(a.data=a.data.replace(/ $/,``)),a=null,o=!1):r(c)||i(c)?(a=null,o=!0):a&&(o=!1);else{c=JR(c);continue}var u=YR(s,c,i);s=c,c=u}a&&(a.data=a.data.replace(/ $/,``),a.data||JR(a))}}function JR(e){var t=e.nextSibling||e.parentNode;return e.parentNode.removeChild(e),t}function YR(e,t,n){return e&&e.parentNode===t||n(t)?t.nextSibling||t.parentNode:t.firstChild||t.nextSibling||t.parentNode}var XR=typeof window<`u`?window:{};function ZR(){var e=XR.DOMParser,t=!1;try{new e().parseFromString(``,`text/html`)&&(t=!0)}catch{}return t}function QR(){var e=function(){};return $R()?e.prototype.parseFromString=function(e){var t=new window.ActiveXObject(`htmlfile`);return t.designMode=`on`,t.open(),t.write(e),t.close(),t}:e.prototype.parseFromString=function(e){var t=document.implementation.createHTMLDocument(``);return t.open(),t.write(e),t.close(),t},e}function $R(){var e=!1;try{document.implementation.createHTMLDocument(``).open()}catch{XR.ActiveXObject&&(e=!0)}return e}var ez=ZR()?XR.DOMParser:QR();function tz(e,t){var n=typeof e==`string`?rz().parseFromString(``+e+``,`text/html`).getElementById(`turndown-root`):e.cloneNode(!0);return qR({element:n,isBlock:kR,isVoid:jR,isPre:t.preformattedCode?iz:null}),n}var nz;function rz(){return nz||=new ez,nz}function iz(e){return e.nodeName===`PRE`||e.nodeName===`CODE`}function az(e,t){return e.isBlock=kR(e),e.isCode=e.nodeName===`CODE`||e.parentNode.isCode,e.isBlank=oz(e),e.flankingWhitespace=sz(e,t),e}function oz(e){return!jR(e)&&!PR(e)&&/^\s*$/i.test(e.textContent)&&!MR(e)&&!FR(e)}function sz(e,t){if(e.isBlock||t.preformattedCode&&e.isCode)return{leading:``,trailing:``};var n=cz(e.textContent);return n.leadingAscii&&lz(`left`,e,t)&&(n.leading=n.leadingNonAscii),n.trailingAscii&&lz(`right`,e,t)&&(n.trailing=n.trailingNonAscii),{leading:n.leading,trailing:n.trailing}}function cz(e){var t=e.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:t[1],leadingAscii:t[2],leadingNonAscii:t[3],trailing:t[4],trailingNonAscii:t[5],trailingAscii:t[6]}}function lz(e,t,n){var r,i,a;return e===`left`?(r=t.previousSibling,i=/ $/):(r=t.nextSibling,i=/^ /),r&&(r.nodeType===3?a=i.test(r.nodeValue):n.preformattedCode&&r.nodeName===`CODE`?a=!1:r.nodeType===1&&!kR(r)&&(a=i.test(r.textContent))),a}var uz=Array.prototype.reduce;function dz(e){if(!(this instanceof dz))return new dz(e);var t={rules:BR,headingStyle:`setext`,hr:`* * *`,bulletListMarker:`*`,codeBlockStyle:`indented`,fence:"```",emDelimiter:`_`,strongDelimiter:`**`,linkStyle:`inlined`,linkReferenceStyle:`full`,br:` `,preformattedCode:!1,blankReplacement:function(e,t){return t.isBlock?` + +`:``},keepReplacement:function(e,t){return t.isBlock?` + +`+t.outerHTML+` + +`:t.outerHTML},defaultReplacement:function(e,t){return t.isBlock?` + +`+e+` + +`:e}};this.options=CR({},t,e),this.rules=new WR(this.options)}dz.prototype={turndown:function(e){if(!gz(e))throw TypeError(e+` is not a string, or an element/document/fragment node.`);if(e===``)return``;var t=fz.call(this,new tz(e,this.options));return pz.call(this,t)},use:function(e){if(Array.isArray(e))for(var t=0;t()=>(e&&(t=e(e=0)),t),Cz=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),wz=(e,t)=>{for(var n in t)vz(e,n,{get:t[n],enumerable:!0})},Tz=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of bz(t))!Sz.call(e,i)&&i!==n&&vz(e,i,{get:()=>t[i],enumerable:!(r=yz(t,i))||r.enumerable});return e},Ez=(e,t,n)=>(n=e==null?{}:_z(xz(e)),Tz(t||!e||!e.__esModule?vz(n,`default`,{value:e,enumerable:!0}):n,e)),Dz={};wz(Dz,{AsyncLocalStorage:()=>kz,Module:()=>Az,lookup:()=>Oz});function Oz(){throw Error(`node:dns is not available in browser environments`)}var kz,Az,jz=B(()=>{kz=void 0,Az=void 0});function Mz(){return Pz||Nz(),Pz}function Nz(){let e=[{prop:`Function`,target:globalThis,violationType:`function_constructor`,strategy:`throw`,reason:`Function constructor allows arbitrary code execution`},{prop:`eval`,target:globalThis,violationType:`eval`,strategy:`throw`,reason:`eval() allows arbitrary code execution`},{prop:`setTimeout`,target:globalThis,violationType:`setTimeout`,strategy:`throw`,reason:`setTimeout with string argument allows code execution`},{prop:`setInterval`,target:globalThis,violationType:`setInterval`,strategy:`throw`,reason:`setInterval with string argument allows code execution`},{prop:`setImmediate`,target:globalThis,violationType:`setImmediate`,strategy:`throw`,reason:`setImmediate could be used to escape sandbox context`},{prop:`env`,target:process,violationType:`process_env`,strategy:`throw`,reason:`process.env could leak sensitive environment variables`,allowedKeys:new Set([`NODE_V8_COVERAGE`,`NODE_DEBUG`,`NODE_DEBUG_NATIVE`,`NODE_COMPILE_CACHE`,`NODE_ENV`,`WATCH_REPORT_DEPENDENCIES`,`FORCE_COLOR`,`DEBUG`,`UNDICI_NO_FG`,`JEST_WORKER_ID`,`__MINIMATCH_TESTING_PLATFORM__`,`LOG_TOKENS`,`LOG_STREAM`])},{prop:`binding`,target:process,violationType:`process_binding`,strategy:`throw`,reason:`process.binding provides access to native Node.js modules`},{prop:`_linkedBinding`,target:process,violationType:`process_binding`,strategy:`throw`,reason:`process._linkedBinding provides access to native Node.js modules`},{prop:`dlopen`,target:process,violationType:`process_dlopen`,strategy:`throw`,reason:`process.dlopen allows loading native addons`},{prop:`getBuiltinModule`,target:process,violationType:`process_get_builtin_module`,strategy:`throw`,reason:`process.getBuiltinModule allows loading native Node.js modules (fs, child_process, vm)`},{prop:`exit`,target:process,violationType:`process_exit`,strategy:`throw`,reason:`process.exit could terminate the interpreter`},{prop:`abort`,target:process,violationType:`process_exit`,strategy:`throw`,reason:`process.abort could crash the interpreter`},{prop:`kill`,target:process,violationType:`process_kill`,strategy:`throw`,reason:`process.kill could signal other processes`},{prop:`setuid`,target:process,violationType:`process_setuid`,strategy:`throw`,reason:`process.setuid could escalate privileges`},{prop:`setgid`,target:process,violationType:`process_setuid`,strategy:`throw`,reason:`process.setgid could escalate privileges`},{prop:`seteuid`,target:process,violationType:`process_setuid`,strategy:`throw`,reason:`process.seteuid could escalate effective user privileges`},{prop:`setegid`,target:process,violationType:`process_setuid`,strategy:`throw`,reason:`process.setegid could escalate effective group privileges`},{prop:`initgroups`,target:process,violationType:`process_setuid`,strategy:`throw`,reason:`process.initgroups could modify supplementary group IDs`},{prop:`setgroups`,target:process,violationType:`process_setuid`,strategy:`throw`,reason:`process.setgroups could modify supplementary group IDs`},{prop:`umask`,target:process,violationType:`process_umask`,strategy:`throw`,reason:`process.umask could modify file creation permissions`},{prop:`argv`,target:process,violationType:`process_argv`,strategy:`throw`,reason:`process.argv may contain secrets in CLI arguments`},{prop:`cwd`,target:process,violationType:`process_chdir`,strategy:`throw`,reason:`process.cwd could disclose real host working directory path`},{prop:`chdir`,target:process,violationType:`process_chdir`,strategy:`throw`,reason:`process.chdir could confuse the interpreter's CWD tracking`},{prop:`report`,target:process,violationType:`process_report`,strategy:`throw`,reason:`process.report could disclose full environment, host paths, and system info`},{prop:`loadEnvFile`,target:process,violationType:`process_env`,strategy:`throw`,reason:`process.loadEnvFile could load env files bypassing env proxy`},{prop:`setUncaughtExceptionCaptureCallback`,target:process,violationType:`process_exception_handler`,strategy:`throw`,reason:`setUncaughtExceptionCaptureCallback could intercept security errors`},...[`on`,`once`,`addListener`,`prependListener`,`prependOnceListener`].map(e=>({prop:e,target:process,violationType:`process_exception_handler`,strategy:`throw`,reason:`process-global listeners can outlive the sandbox and lose its security context`})),{prop:`send`,target:process,violationType:`process_send`,strategy:`throw`,reason:`process.send could communicate with parent process in IPC contexts`},{prop:`channel`,target:process,violationType:`process_channel`,strategy:`throw`,reason:`process.channel could access IPC channel to parent process`},{prop:`cpuUsage`,target:process,violationType:`process_timing`,strategy:`throw`,reason:`process.cpuUsage could enable timing side-channel attacks`},{prop:`memoryUsage`,target:process,violationType:`process_timing`,strategy:`throw`,reason:`process.memoryUsage could enable timing side-channel attacks`},{prop:`hrtime`,target:process,violationType:`process_timing`,strategy:`throw`,reason:`process.hrtime could enable timing side-channel attacks`},{prop:`WeakRef`,target:globalThis,violationType:`weak_ref`,strategy:`throw`,reason:`WeakRef could be used to leak references outside sandbox`},{prop:`FinalizationRegistry`,target:globalThis,violationType:`finalization_registry`,strategy:`throw`,reason:`FinalizationRegistry could be used to leak references outside sandbox`},{prop:`Reflect`,target:globalThis,violationType:`reflect`,strategy:`freeze`,reason:`Reflect provides introspection capabilities`},{prop:`Proxy`,target:globalThis,violationType:`proxy`,strategy:`throw`,reason:`Proxy allows intercepting and modifying object behavior`},{prop:`WebAssembly`,target:globalThis,violationType:`webassembly`,strategy:`throw`,reason:`WebAssembly allows executing arbitrary compiled code`},{prop:`SharedArrayBuffer`,target:globalThis,violationType:`shared_array_buffer`,strategy:`throw`,reason:`SharedArrayBuffer could enable side-channel communication or timing attacks`},{prop:`Atomics`,target:globalThis,violationType:`atomics`,strategy:`throw`,reason:`Atomics could enable side-channel communication or timing attacks`},{prop:`performance`,target:globalThis,violationType:`performance_timing`,strategy:`throw`,reason:`performance.now() provides sub-millisecond timing for side-channel attacks`},{prop:`stdout`,target:process,violationType:`process_stdout`,strategy:`throw`,reason:`process.stdout could bypass interpreter output to write to host stdout`},{prop:`stderr`,target:process,violationType:`process_stderr`,strategy:`throw`,reason:`process.stderr could bypass interpreter output to write to host stderr`},{prop:`__defineGetter__`,target:Object.prototype,violationType:`prototype_mutation`,strategy:`throw`,reason:`__defineGetter__ allows prototype pollution via getter injection`},{prop:`__defineSetter__`,target:Object.prototype,violationType:`prototype_mutation`,strategy:`throw`,reason:`__defineSetter__ allows prototype pollution via setter injection`},{prop:`__lookupGetter__`,target:Object.prototype,violationType:`prototype_mutation`,strategy:`throw`,reason:`__lookupGetter__ enables introspection for prototype pollution attacks`},{prop:`__lookupSetter__`,target:Object.prototype,violationType:`prototype_mutation`,strategy:`throw`,reason:`__lookupSetter__ enables introspection for prototype pollution attacks`},{prop:`JSON`,target:globalThis,violationType:`json_mutation`,strategy:`freeze`,reason:`Freeze JSON to prevent mutation of parsing/serialization`},{prop:`Math`,target:globalThis,violationType:`math_mutation`,strategy:`freeze`,reason:`Freeze Math to prevent mutation of math utilities`}];try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&e.push({prop:`constructor`,target:Object.getPrototypeOf(async()=>{}),violationType:`async_function_constructor`,strategy:`throw`,reason:`AsyncFunction constructor allows arbitrary async code execution`})}catch{}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&e.push({prop:`constructor`,target:Object.getPrototypeOf(function*(){}),violationType:`generator_function_constructor`,strategy:`throw`,reason:`GeneratorFunction constructor allows arbitrary generator code execution`})}catch{}try{let t=Object.getPrototypeOf(async function*(){}).constructor;t&&t!==Function&&t!==Object.getPrototypeOf(async()=>{}).constructor&&e.push({prop:`constructor`,target:Object.getPrototypeOf(async function*(){}),violationType:`async_generator_function_constructor`,strategy:`throw`,reason:`AsyncGeneratorFunction constructor allows arbitrary async generator code execution`})}catch{}let t=e.filter(e=>{try{return e.target[e.prop]!==void 0}catch{return!1}});return Pz??=new Set(t.map(({violationType:e})=>e)),t}var Pz,Fz=B(()=>{});function Iz(){return Math.floor(Lz+Rz())}var Lz,Rz,zz=B(()=>{Lz=performance.timeOrigin,Rz=performance.now.bind(performance)});function Bz(e){let t=e?.find(e=>Hz.has(e));if(t)throw RangeError(`defenseInDepth.excludeViolationTypes cannot disable the non-excludable "${t}" protection`)}function Vz(e,t,n){let r=n&&!Hz.has(t)?` + +If this access is required by trusted host-runtime code, add "${t}" to defenseInDepth.excludeViolationTypes.`:``;return e+Uz+r}var Hz,Uz,Wz=B(()=>{Hz=new Set([`function_constructor`,`async_function_constructor`,`generator_function_constructor`,`async_generator_function_constructor`]),Uz=` + +This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`});function Gz(){return typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function Kz(e,t,...n){return tB.run(e,()=>t(...n))}function qz(){return!Xz&&typeof Qz?.registerHooks==`function`}function Jz(e){let t=typeof e==`boolean`?{enabled:e}:e??{};if(Bz(t.excludeViolationTypes),t.enabled!==void 0&&t.enabled!==!0&&t.enabled!==!1&&t.enabled!==`auto`)throw RangeError(`defenseInDepth.enabled must be true, false, or "auto"`);let n={...rB,...t},r=n.enabled===`auto`?`auto`:n.enabled?`enabled`:`disabled`,i={...n,enabled:r!==`disabled`,requested:r};return i.excludeViolationTypes&&=[...new Set(i.excludeViolationTypes)].sort(),i}function Yz(e,t){if(e.enabled!==t.enabled||e.auditMode!==t.auditMode||e.processLifetimeIntrinsicHardening!==t.processLifetimeIntrinsicHardening||e.onViolation!==t.onViolation)return!1;let n=e.excludeViolationTypes??[],r=t.excludeViolationTypes??[];return n.length===r.length&&n.every((e,t)=>e===r[t])}var Xz,Zz,Qz,$z,eB,tB,nB,rB,iB,aB=B(()=>{if(jz(),jz(),Fz(),zz(),Wz(),Xz=!0,Zz=null,Qz=null,$z=null,!Xz)try{Zz=void 0,Qz=Dz,$z=Qz.Module??Qz.default??null}catch{}eB=class extends Error{violation;constructor(e,t){super(Vz(e,t.type,t.type===`error_prepare_stack_trace`||Mz().has(t.type))),this.violation=t,this.name=`SecurityViolationError`}},tB=!Xz&&Zz?new Zz:null,nB=1e3,rB={enabled:!0,auditMode:!1,processLifetimeIntrinsicHardening:!1},iB=class e{static instance=null;static importHooksRegistered=!1;static trustedExecutionDepth=new Map;config;refCount=0;patchFailures=[];activeExecutionIds=new Set;contextCache=new Map;originalDescriptors=[];temporaryIntrinsicDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(e){this.config=e}static getInstance(t){let n=Jz(t);if(!e.instance)e.instance=new e(n);else{let t=e.instance.config;if(!Yz(n,t))throw Error(`DefenseInDepthBox config conflict: all resolved defense options, including exclusions and the violation callback, must match across Bash instances. Call DefenseInDepthBox.resetInstance() between incompatible configurations.`)}return e.instance}static resetInstance(){e.instance&&=(e.instance.forceDeactivate(),null),e.trustedExecutionDepth.clear()}static isInSandboxedContext(){return tB?tB?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(tB)return tB?.getStore()?.executionId}static enterTrustedScope(t){let n=e.trustedExecutionDepth.get(t)??0;e.trustedExecutionDepth.set(t,n+1)}static leaveTrustedScope(t){let n=e.trustedExecutionDepth.get(t);if(n){if(n===1){e.trustedExecutionDepth.delete(t);return}e.trustedExecutionDepth.set(t,n-1)}}static isTrustedScopeActive(t){return t?(e.trustedExecutionDepth.get(t)??0)>0:!1}static isTrustedContext(t){return!t||t.forceUntrusted?!1:t.trusted===!0||e.isTrustedScopeActive(t.executionId)}isExecutionIdActive(e){return this.activeExecutionIds.has(e)}getCachedContext(e){let t=this.contextCache.get(e);return t||(t={sandboxActive:!0,executionId:e},this.contextCache.set(e,t)),t}static bindCurrentContext(t){if(!tB)return t;let n=tB.getStore(),r=n?.sandboxActive===!0?n.executionId:void 0;if(!r)return t;let i=e.instance?.getCachedContext(r)??{sandboxActive:!0,executionId:r},a=n?.forceUntrusted?{...i,forceUntrusted:!0}:i;return((...n)=>{let i=e.instance;if(!(i&&!i.isExecutionIdActive(r)&&(i.recordViolation(`bound_callback_after_deactivate`,`bound callback`,`Bound callback blocked after originating execution was deactivated`),!i.config.auditMode)))return Kz(a,t,...n)})}isEnabled(){return this.getStatus().state===`enabled`}getStatus(){let e=qz();return this.config.requested===`disabled`?{requested:`disabled`,state:`disabled`,level:`none`,contextualDynamicImportProtection:e,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?`process-lifetime`:`scoped-best-effort`}:!tB||Xz?{requested:this.config.requested,state:`unsupported`,level:`none`,contextualDynamicImportProtection:!1,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?`process-lifetime`:`scoped-best-effort`,reason:`context-aware ESM loader hooks (node:module.registerHooks) are unavailable`}:{requested:this.config.requested,state:`enabled`,level:this.config.auditMode?`none`:e?`full`:`best-effort`,contextualDynamicImportProtection:e,processLifetimeIntrinsicHardening:this.config.processLifetimeIntrinsicHardening===!0,intrinsicProtection:this.config.processLifetimeIntrinsicHardening?`process-lifetime`:`scoped-best-effort`,reason:this.config.auditMode?`audit mode records violations but does not block them`:e?void 0:`best-effort protection; context-aware ESM loader hooks are unavailable`}}updateConfig(e){if(this.refCount>0)throw Error(`DefenseInDepthBox configuration cannot change while protection is active`);this.config=Jz({...this.config,...e})}activate(){if(!Xz&&this.config.enabled&&!tB)throw Error(`DefenseInDepthBox: enabled protection requires node:async_hooks and node:module`);if(Xz||!this.config.enabled){let e=Gz(),t=!1;return{run:e=>t?Promise.reject(Error(`DefenseInDepthBox handle is deactivated and cannot run new work`)):e(),deactivate:()=>{t=!0},executionId:e}}if(this.refCount++,this.refCount===1){try{this.applyPatches()}catch(e){throw this.restorePatches(),this.activeExecutionIds.clear(),this.contextCache.clear(),this.refCount=0,e}this.activationTime=Date.now()}let e=Gz(),t=!1;return{run:n=>t?Promise.reject(Error(`DefenseInDepthBox handle is deactivated and cannot run new work`)):(this.activeExecutionIds.add(e),tB.run({sandboxActive:!0,executionId:e},n)),deactivate:()=>{t||(t=!0,this.activeExecutionIds.delete(e),this.contextCache.delete(e),this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0))},executionId:e}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.activeExecutionIds.clear(),this.contextCache.clear(),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}getPatchFailures(){return[...this.patchFailures]}clearViolations(){this.violations=[]}getPathForTarget(e,t){return e===globalThis?`globalThis.${t}`:e===process?`process.${t}`:e===Error?`Error.${t}`:e===Function.prototype?`Function.prototype.${t}`:e===Object.prototype?`Object.prototype.${t}`:`.${t}`}static runTrusted(t){if(!tB)return t();let n=tB.getStore();if(!n)return t();let{executionId:r}=n;return tB.run({...n,trusted:!0,forceUntrusted:!1},()=>{e.enterTrustedScope(r);try{let n=t();return typeof n==`object`&&n&&`finally`in n&&typeof n.finally==`function`?n.finally(()=>{e.leaveTrustedScope(r)}):(e.leaveTrustedScope(r),n)}catch(t){throw e.leaveTrustedScope(r),t}})}static async runTrustedAsync(t){if(!tB)return t();let n=tB.getStore();if(!n)return t();let{executionId:r}=n;return tB.run({...n,trusted:!0,forceUntrusted:!1},async()=>{e.enterTrustedScope(r);try{return await t()}finally{e.leaveTrustedScope(r)}})}static async runUntrustedAsync(e){if(!tB)return e();let t=tB.getStore();return t?tB.run({...t,trusted:!1,forceUntrusted:!0},e):e()}shouldBlock(){if(Xz||this.config.auditMode||!tB)return!1;let t=tB?.getStore();return!(t?.sandboxActive!==!0||e.isTrustedContext(t))}shouldAudit(){if(!this.config.auditMode||!tB)return!1;let t=tB.getStore();return t?.sandboxActive===!0&&!e.isTrustedContext(t)}recordViolation(e,t,n){let r={timestamp:Iz(),type:e,message:n,path:t,stack:Error().stack,executionId:tB?.getStore()?.executionId};if(this.violations.length{let i=`${t} ${e} is blocked during script execution`,a=r.recordViolation(n,t,i);throw new eB(i,a)};return new Proxy(e,{set(e,t,n,a){return r.shouldBlock()&&i(`modification`),Reflect.set(e,t,n,a)},defineProperty(e,t,n){return r.shouldBlock()&&i(`defineProperty`),Reflect.defineProperty(e,t,n)},deleteProperty(e,t){return r.shouldBlock()&&i(`deletion`),Reflect.deleteProperty(e,t)},setPrototypeOf(e,t){return r.shouldBlock()&&i(`setPrototypeOf`),Reflect.setPrototypeOf(e,t)},preventExtensions(e){return r.shouldBlock()&&i(`preventExtensions`),Reflect.preventExtensions(e)}})}applyPatches(){this.patchFailures=[];let e=Nz(),t=new Set(this.config.excludeViolationTypes??[]),n=new Set([`process_send`,`process_channel`,`process_stdout`,`process_stderr`]),r=[];for(let i of e)if(!t.has(i.violationType)&&!n.has(i.violationType)){if(i.strategy===`freeze`){r.push(i);continue}this.applyPatch(i)}this.protectConstructorChain(),t.has(`error_prepare_stack_trace`)||this.protectErrorPrepareStackTrace(),this.protectPromiseThen(),qz()&&this.protectDynamicImport(),this.protectModuleLoad(),this.protectModuleResolveFilename(),this.protectProcessMainModule(),this.protectProcessExecPath(),this.protectProxyRevocable();let i=[`Function.prototype.constructor`,`Module._load`,`Module._resolveFilename`],a=this.patchFailures.filter(e=>i.includes(e));if(a.length>0)throw this.restorePatches(),Error(`DefenseInDepthBox: critical patches failed: ${a.join(`, `)}`);this.config.processLifetimeIntrinsicHardening||this.protectReversibleIntrinsics(r);for(let e of r)this.applyPatch(e,this.config.processLifetimeIntrinsicHardening===!0);this.config.processLifetimeIntrinsicHardening&&this.lockWellKnownSymbols()}protectReversibleIntrinsics(e){let t=new Set,n=(e,t)=>{let n=Object.getOwnPropertyDescriptor(e,t);!n||!(`value`in n)||n.writable!==!0||n.configurable!==!0||(this.temporaryIntrinsicDescriptors.push({target:e,prop:t,descriptor:n}),Object.defineProperty(e,t,{...n,writable:!1}))};for(let{target:r,prop:i}of e){let e=r[i];if(typeof e==`object`&&e){t.add(e);for(let t of Reflect.ownKeys(e))n(e,t)}}let r=[];for(let e of[Array,Map,Set,RegExp,Promise])r.push([e,Symbol.species]);for(let e of[Array.prototype,String.prototype,Map.prototype,Set.prototype])r.push([e,Symbol.iterator]);r.push([Symbol.prototype,Symbol.toPrimitive],[Date.prototype,Symbol.toPrimitive],[Function.prototype,Symbol.hasInstance],[Array.prototype,Symbol.unscopables]);for(let e of[Symbol.match,Symbol.matchAll,Symbol.replace,Symbol.search,Symbol.split])r.push([RegExp.prototype,e]);for(let e of[Map.prototype,Set.prototype,Promise.prototype,ArrayBuffer.prototype])r.push([e,Symbol.toStringTag]);for(let[e,i]of r)t.add(e),n(e,i);let i=(e,n,r)=>{let i=Object.getOwnPropertyDescriptor(e,n);if(!i||!(`value`in i)||typeof i.value!=`function`||i.configurable!==!0)return;let a=i.value,o=this,s=function(...e){let i=e[0];if(o.shouldBlock()&&typeof i==`object`&&i&&t.has(i)){let e=`${r}.${n}`,t=`${e} is blocked for protected intrinsics during script execution`,i=o.recordViolation(`prototype_mutation`,e,t);throw new eB(t,i)}return Reflect.apply(a,this,e)};this.temporaryIntrinsicDescriptors.push({target:e,prop:n,descriptor:i}),Object.defineProperty(e,n,{...i,value:s,writable:!1})};for(let e of[`assign`,`defineProperties`,`defineProperty`,`freeze`,`preventExtensions`,`seal`,`setPrototypeOf`])i(Object,e,`Object`);for(let e of[`defineProperty`,`deleteProperty`,`preventExtensions`,`set`,`setPrototypeOf`])i(Reflect,e,`Reflect`)}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,`Function.prototype.constructor`,`function_constructor`);try{let e=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&this.patchPrototypeConstructor(e.prototype,`AsyncFunction.prototype.constructor`,`async_function_constructor`)}catch(e){this.patchFailures.push(`AsyncFunction.prototype.constructor`),console.debug(`[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:`,e instanceof Error?e.message:e)}try{let e=Object.getPrototypeOf(function*(){}).constructor;e&&e!==Function&&this.patchPrototypeConstructor(e.prototype,`GeneratorFunction.prototype.constructor`,`generator_function_constructor`)}catch(e){this.patchFailures.push(`GeneratorFunction.prototype.constructor`),console.debug(`[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:`,e instanceof Error?e.message:e)}try{let e=Object.getPrototypeOf(async function*(){}).constructor,t=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&e!==t&&this.patchPrototypeConstructor(e.prototype,`AsyncGeneratorFunction.prototype.constructor`,`async_generator_function_constructor`)}catch(e){this.patchFailures.push(`AsyncGeneratorFunction.prototype.constructor`),console.debug(`[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:`,e instanceof Error?e.message:e)}}protectErrorPrepareStackTrace(){let e=this;try{let t=Object.getOwnPropertyDescriptor(Error,`prepareStackTrace`);this.originalDescriptors.push({target:Error,prop:`prepareStackTrace`,descriptor:t});let n=t?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return n},set(t){if(e.shouldBlock()){let t=`Error.prepareStackTrace modification is blocked during script execution`,n=e.recordViolation(`error_prepare_stack_trace`,`Error.prepareStackTrace`,t);throw new eB(t,n)}e.shouldAudit()&&e.recordViolation(`error_prepare_stack_trace`,`Error.prepareStackTrace`,`Error.prepareStackTrace set (audit mode)`),n=t},configurable:!0})}catch(e){this.patchFailures.push(`Error.prepareStackTrace`),console.debug(`[DefenseInDepthBox] Could not protect Error.prepareStackTrace:`,e instanceof Error?e.message:e)}}protectPromiseThen(){let e=this;try{let t=function(...e){return tB.run(this.captured,()=>{if(!this.box.isExecutionIdActive(this.executionId)){if(this.box.recordViolation(`promise_then_after_deactivate`,`Promise.then`,`Promise.then callback is blocked after defense deactivation`),this.box.config.auditMode)return Reflect.apply(this.cb,void 0,e);if(this.kind===`fulfilled`)return e[0];throw e[0]}return Reflect.apply(this.cb,void 0,e)})},n=Object.getOwnPropertyDescriptor(Promise.prototype,`then`);this.originalDescriptors.push({target:Promise.prototype,prop:`then`,descriptor:n});let r=n?.value;if(typeof r!=`function`)return;Object.defineProperty(Promise.prototype,"then",{value:function(n,i){if(!tB)return Reflect.apply(r,this,[n,i]);let a=tB.getStore(),o=a?.sandboxActive===!0&&a.trusted!==!0?a.executionId:void 0;if(!o)return Reflect.apply(r,this,[n,i]);let s=e.getCachedContext(o),c=a?.forceUntrusted?{...s,forceUntrusted:!0}:s,l=(n,r)=>typeof n==`function`?t.bind({box:e,executionId:o,captured:c,cb:n,kind:r}):n;return Reflect.apply(r,this,[l(n,`fulfilled`),l(i,`rejected`)])},writable:!0,configurable:!0})}catch(e){this.patchFailures.push(`Promise.prototype.then`),console.debug(`[DefenseInDepthBox] Could not protect Promise.prototype.then:`,e instanceof Error?e.message:e)}}patchPrototypeConstructor(e,t,n){let r=this;try{let i=Object.getOwnPropertyDescriptor(e,`constructor`);this.originalDescriptors.push({target:e,prop:`constructor`,descriptor:i});let a=i?.value;Object.defineProperty(e,"constructor",{get(){if(r.shouldBlock()){let e=`${t} access is blocked during script execution`,i=r.recordViolation(n,t,e);throw new eB(e,i)}return r.shouldAudit()&&r.recordViolation(n,t,`${t} accessed (audit mode)`),a},set(e){if(r.shouldBlock()){let e=`${t} modification is blocked during script execution`,i=r.recordViolation(n,t,e);throw new eB(e,i)}Object.defineProperty(this,"constructor",{value:e,writable:!0,configurable:!0})},configurable:!0})}catch(e){this.patchFailures.push(t),console.debug(`[DefenseInDepthBox] Could not patch ${t}:`,e instanceof Error?e.message:e)}}protectProcessMainModule(){if(typeof process>`u`)return;let e=this;try{let t=Object.getOwnPropertyDescriptor(process,`mainModule`);this.originalDescriptors.push({target:process,prop:`mainModule`,descriptor:t});let n=t?.value;n!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(e.shouldBlock()){let t=`process.mainModule access is blocked during script execution`,n=e.recordViolation(`process_main_module`,`process.mainModule`,t);throw new eB(t,n)}return e.shouldAudit()&&e.recordViolation(`process_main_module`,`process.mainModule`,`process.mainModule accessed (audit mode)`),n},set(t){if(e.shouldBlock()){let t=`process.mainModule modification is blocked during script execution`,n=e.recordViolation(`process_main_module`,`process.mainModule`,t);throw new eB(t,n)}Object.defineProperty(process,"mainModule",{value:t,writable:!0,configurable:!0})},configurable:!0})}catch(e){this.patchFailures.push(`process.mainModule`),console.debug(`[DefenseInDepthBox] Could not protect process.mainModule:`,e instanceof Error?e.message:e)}}protectProcessExecPath(){if(typeof process>`u`)return;let e=this;try{let t=Object.getOwnPropertyDescriptor(process,`execPath`);this.originalDescriptors.push({target:process,prop:`execPath`,descriptor:t});let n=t?.value??process.execPath;Object.defineProperty(process,"execPath",{get(){if(e.shouldBlock()){let t=`process.execPath access is blocked during script execution`,n=e.recordViolation(`process_exec_path`,`process.execPath`,t);throw new eB(t,n)}return e.shouldAudit()&&e.recordViolation(`process_exec_path`,`process.execPath`,`process.execPath accessed (audit mode)`),n},set(t){if(e.shouldBlock()){let t=`process.execPath modification is blocked during script execution`,n=e.recordViolation(`process_exec_path`,`process.execPath`,t);throw new eB(t,n)}Object.defineProperty(process,"execPath",{value:t,writable:!0,configurable:!0})},configurable:!0})}catch(e){this.patchFailures.push(`process.execPath`),console.debug(`[DefenseInDepthBox] Could not protect process.execPath:`,e instanceof Error?e.message:e)}}lockWellKnownSymbols(){let e=(e,t)=>{try{let n=Object.getOwnPropertyDescriptor(e,t);if(n?.configurable){if(`value`in n){Object.defineProperty(e,t,{...n,configurable:!1,writable:!1});return}Object.defineProperty(e,t,{...n,configurable:!1})}}catch{}};for(let t of[Array,Map,Set,RegExp,Promise])e(t,Symbol.species);for(let t of[Array.prototype,String.prototype,Map.prototype,Set.prototype])e(t,Symbol.iterator);e(Symbol.prototype,Symbol.toPrimitive),e(Date.prototype,Symbol.toPrimitive);for(let t of[Symbol.match,Symbol.matchAll,Symbol.replace,Symbol.search,Symbol.split])e(RegExp.prototype,t);e(Function.prototype,Symbol.hasInstance),e(Array.prototype,Symbol.unscopables);for(let t of[Map.prototype,Set.prototype,Promise.prototype,ArrayBuffer.prototype])e(t,Symbol.toStringTag)}protectProxyRevocable(){let e=this;try{let t=Proxy.revocable;if(typeof t!=`function`)return;let n=Object.getOwnPropertyDescriptor(Proxy,`revocable`);this.originalDescriptors.push({target:Proxy,prop:`revocable`,descriptor:n}),Object.defineProperty(Proxy,"revocable",{value:function(n,r){if(e.shouldBlock()){let t=`Proxy.revocable is blocked during script execution`,n=e.recordViolation(`proxy`,`Proxy.revocable`,t);throw new eB(t,n)}return e.shouldAudit()&&e.recordViolation(`proxy`,`Proxy.revocable`,`Proxy.revocable called (audit mode)`),t(n,r)},writable:!1,configurable:!0})}catch(e){this.patchFailures.push(`Proxy.revocable`),console.debug(`[DefenseInDepthBox] Could not protect Proxy.revocable:`,e instanceof Error?e.message:e)}}protectDynamicImport(){if(!(Xz||e.importHooksRegistered))try{let t=Qz;if(!t)throw Error(`node:module is unavailable`);let n=new Set;for(let e of t.builtinModules??[]){let t=e.startsWith(`node:`)?e.slice(5):e;n.add(t);let r=t.indexOf(`/`);r>0&&n.add(t.slice(0,r))}let r=e=>{if(e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`file:`)||e.startsWith(`data:`)||e.startsWith(`blob:`)||e.startsWith(`http:`)||e.startsWith(`https:`))return!1;let r=e.startsWith(`node:`)?e.slice(5):e;if(!r)return!1;if(typeof t.isBuiltin==`function`&&t.isBuiltin(r)||n.has(r))return!0;let i=r.indexOf(`/`);return i>0&&n.has(r.slice(0,i))},i=t=>{let n=tB?.getStore();return t.config.auditMode===!0&&n?.sandboxActive===!0&&!e.isTrustedContext(n)};if(typeof t.registerHooks==`function`){t.registerHooks({resolve(t,n,a){let o=e.instance;if(!o)return a(t,n);if((t.startsWith(`data:`)||t.startsWith(`blob:`))&&o.shouldBlock()){let e=`import(${t.startsWith(`data:`)?`data:`:`blob:`})`,n=`dynamic import of ${t.startsWith(`data:`)?`data:`:`blob:`} URLs is blocked by defense-in-depth`,r=o.recordViolation(`dynamic_import_builtin`,e,n);throw new eB(n,r)}if(r(t)){let e=`import(${t})`,n=`dynamic import of Node.js builtin '${t}' is blocked during script execution`;if(o.shouldBlock()){let t=o.recordViolation(`dynamic_import_builtin`,e,n);throw new eB(n,t)}i(o)&&o.recordViolation(`dynamic_import_builtin`,e,`dynamic import of Node.js builtin '${t}' called (audit mode)`)}return a(t,n)}}),e.importHooksRegistered=!0;return}throw Error(`context-aware ESM loader hooks (node:module.registerHooks) are unavailable`)}catch(e){throw Error(`DefenseInDepthBox: could not register dynamic-import hooks: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}protectModuleLoad(){this.protectModuleMethod(`_load`,`module_load`)}protectModuleResolveFilename(){this.protectModuleMethod(`_resolveFilename`,`module_resolve_filename`)}protectModuleMethod(e,t){if(Xz)return;let n=`Module.${e}`;try{let r=$z,i=r?.[e];if(!r||typeof i!=`function`)throw Error(`node:module Module class or method is unavailable`);let a=Object.getOwnPropertyDescriptor(r,e);if(!a)throw Error(`method has no own property descriptor`);if(a.configurable===!1&&a.writable===!1)throw Error(`method is non-configurable and non-writable`);let o=this.createBlockingProxy(i,n,t);this.originalDescriptors.push({target:r,prop:e,descriptor:a}),Object.defineProperty(r,e,{...a,value:o});let s=Object.getOwnPropertyDescriptor(r,e);if(r[e]!==o||s?.value!==o)throw Error(`installed patch failed verification`)}catch{this.patchFailures.push(n)}}applyPatch(e,t=!1){let{target:n,prop:r,violationType:i,strategy:a}=e;try{let o=n[r];if(o===void 0)return;let s=Object.getOwnPropertyDescriptor(n,r);if(this.originalDescriptors.push({target:n,prop:r,descriptor:s}),a===`freeze`){if(typeof o==`object`&&o){t&&Object.freeze(o);let e=this.getPathForTarget(n,r),a=this.createReadonlyObjectProxy(o,e,i);Object.defineProperty(n,r,{...s,value:a})}}else{let t=this.getPathForTarget(n,r),a=typeof o==`function`?this.createBlockingProxy(o,t,i):this.createBlockingObjectProxy(o,t,i,e.allowedKeys);Object.defineProperty(n,r,{value:a,writable:!0,configurable:!0})}}catch(e){let t=this.getPathForTarget(n,r);this.patchFailures.push(t),console.debug(`[DefenseInDepthBox] Could not patch ${t}:`,e instanceof Error?e.message:e)}}restorePatches(){for(let e=this.temporaryIntrinsicDescriptors.length-1;e>=0;e--){let{target:t,prop:n,descriptor:r}=this.temporaryIntrinsicDescriptors[e];try{Object.defineProperty(t,n,r)}catch(e){console.debug(`[DefenseInDepthBox] Could not restore temporary intrinsic ${String(n)}:`,e instanceof Error?e.message:e)}}this.temporaryIntrinsicDescriptors=[];for(let e=this.originalDescriptors.length-1;e>=0;e--){let{target:t,prop:n,descriptor:r}=this.originalDescriptors[e];try{r?Object.defineProperty(t,n,r):delete t[n]}catch(e){let r=this.getPathForTarget(t,n);console.debug(`[DefenseInDepthBox] Could not restore ${r}:`,e instanceof Error?e.message:e)}}this.originalDescriptors=[]}}});function oB(e){return typeof e==`function`?iB.bindCurrentContext(e):e}function sB(e,t){if(t===1/0)return;let n=oB(e),r={cleared:!1,remainingMs:Math.max(0,t),timer:void 0},i=()=>{if(r.cleared)return;let e=Math.min(r.remainingMs,pB);r.timer=lB(()=>{r.cleared||(r.remainingMs-=e,r.remainingMs>0?i():n())},e)};return i(),r}function cB(e){e&&(e.cleared=!0,e.timer!==void 0&&uB(e.timer))}var lB,uB,dB,fB,pB,mB=B(()=>{aB(),lB=globalThis.setTimeout.bind(globalThis),uB=globalThis.clearTimeout.bind(globalThis),globalThis.setInterval.bind(globalThis),globalThis.clearInterval.bind(globalThis),dB=((e,t,...n)=>lB(oB(e),t,...n)),fB=uB,pB=2147483647});function hB(...e){let t=[...new Set(e.filter(e=>e!==void 0))];if(t.length===0)return{signal:void 0,cleanup(){}};if(t.length===1)return{signal:t[0],cleanup(){}};let n=new AbortController,r=[];for(let e of t){if(e.aborted){n.abort(e.reason);break}let t=()=>n.abort(e.reason);e.addEventListener(`abort`,t,{once:!0}),r.push([e,t])}return{signal:n.signal,cleanup(){for(let[e,t]of r)e.removeEventListener(`abort`,t)}}}var gB=B(()=>{});function _B(e,t,n){if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<0||e>t)throw RangeError(`${n}: byte conversion limit exceeded (${t} bytes)`)}function V(e){let t=0;for(let n=0;n=55296&&r<=56319&&n+1=56320&&r<=57343?(t+=4,n++):t+=3}else t+=3}return t}function vB(e,t=DB){let n=e;if(!n)return n;_B(n.length,t,`UTF-8 decode`);let r=!1;for(let e=0;e255)return n;t>127&&(r=!0)}if(!r)return n;let i=new Uint8Array(n.length);for(let e=0;e{TB=new TextDecoder(`utf-8`,{fatal:!0}),EB=new TextEncoder,DB=536870912,OB=``});function AB(e){return e instanceof MB||e instanceof NB||e instanceof PB}var jB,MB,NB,PB,FB,IB,LB,RB,zB,BB,VB,H,HB,UB,WB,U=B(()=>{kB(),jB=class extends Error{stdout;stderr;internalOutputAccounting={stdout:0,stderr:0};constructor(e,t=``,n=``){super(e),this.stdout=t,this.stderr=n}prependOutput(e,t){this.stdout=e+this.stdout,this.stderr=t+this.stderr,this.internalOutputAccounting.stdout+=V(e),this.internalOutputAccounting.stderr+=V(t)}},MB=class extends jB{levels;name=`BreakError`;constructor(e=1,t=``,n=``){super(`break`,t,n),this.levels=e}},NB=class extends jB{levels;name=`ContinueError`;constructor(e=1,t=``,n=``){super(`continue`,t,n),this.levels=e}},PB=class extends jB{exitCode;name=`ReturnError`;constructor(e=0,t=``,n=``){super(`return`,t,n),this.exitCode=e}},FB=class extends jB{exitCode;name=`ErrexitError`;constructor(e,t=``,n=``){super(`errexit: command exited with status ${e}`,t,n),this.exitCode=e}},IB=class extends jB{varName;name=`NounsetError`;constructor(e,t=``){super(`${e}: unbound variable`,t,`bash: ${e}: unbound variable +`),this.varName=e}},LB=class extends jB{exitCode;name=`ExitError`;constructor(e,t=``,n=``){super(`exit`,t,n),this.exitCode=e}},RB=class extends jB{name=`ArithmeticError`;fatal;constructor(e,t=``,n=``,r=!1){super(e,t,n),this.stderr=n||`bash: ${e} +`,this.fatal=r}},zB=class extends jB{name=`BadSubstitutionError`;constructor(e,t=``,n=``){super(e,t,n),this.stderr=n||`bash: ${e}: bad substitution +`}},BB=class extends jB{name=`GlobError`;constructor(e,t=``,n=``){super(`no match: ${e}`,t,n),this.stderr=n||`bash: no match: ${e} +`}},VB=class extends jB{name=`BraceExpansionError`;constructor(e,t=``,n=``){super(e,t,n),this.stderr=n||`bash: ${e} +`}},H=class extends jB{limitType;name=`ExecutionLimitError`;static EXIT_CODE=126;constructor(e,t,n=``,r=``){super(e,n,r),this.limitType=t,this.stderr=r||`bash: ${e} +`}},HB=class extends jB{name=`ExecutionAbortedError`;constructor(e=``,t=``){super(`execution aborted`,e,t)}},UB=class extends jB{name=`SubshellExitError`;constructor(e=``,t=``){super(`subshell exit`,e,t)}},WB=class extends jB{exitCode;name=`PosixFatalError`;constructor(e,t=``,n=``){super(`posix fatal error`,t,n),this.exitCode=e}}});function GB(e,t,n){let r=n===`width`?Math.abs(e):e;if(!Number.isFinite(e)||!Number.isSafeInteger(e)||r<0||r>t)throw new H(`format ${n} limit exceeded (${t} bytes)`,`string_length`)}function KB(e,t,n,r=YB){GB(t,r,`width`),n!==-1&&GB(n,r,`precision`);let i=e;n>=0&&i.length>n&&(i=i.slice(0,n));let a=Math.abs(t);if(a>i.length){if(V(i)+a-i.length>r)throw new H(`formatted value size limit exceeded (${r} bytes)`,`string_length`);i=t<0?i.padEnd(a,` `):i.padStart(a,` `)}if(V(i)>r)throw new H(`formatted value size limit exceeded (${r} bytes)`,`string_length`);return i}function qB(e,t,n=YB){let r=t,i=0,a=-1,o=!1;for(r0&&(i=-i),GB(i,n,`width`),a!==-1&&GB(a,n,`precision`),[i,a,r-t]}function JB(e,t=YB){if(V(e)>t)throw new H(`escaped string size limit exceeded (${t} bytes)`,`string_length`);let n=``,r=0;for(;r0){try{let e=new TextDecoder(`utf-8`,{fatal:!0});n+=e.decode(new Uint8Array(t))}catch{for(let e of t)n+=String.fromCharCode(e)}r=i}else n+=e[r],r++;break}case`u`:{let t=``,i=r+2;for(;i{kB(),U(),kB(),YB=10485760}),ZB={};wz(ZB,{echoCommand:()=>$B,flagsForFuzzing:()=>eV});function QB(e){let t=``,n=0;for(;n=e.length){t+=`\\`;break}let r=e[n+1];switch(r){case`\\`:t+=`\\`,n+=2;break;case`n`:t+=` +`,n+=2;break;case`t`:t+=` `,n+=2;break;case`r`:t+=`\r`,n+=2;break;case`a`:t+=`\x07`,n+=2;break;case`b`:t+=`\b`,n+=2;break;case`f`:t+=`\f`,n+=2;break;case`v`:t+=`\v`,n+=2;break;case`e`:case`E`:t+=`\x1B`,n+=2;break;case`c`:return{output:t,stop:!0};case`0`:{let r=``,i=n+2;for(;i{$B={name:`echo`,async execute(e,t){let n=!1,r=t.xpgEcho??!1,i=0;for(;i{U(),aB()});function iV(e){let t=`${e.name} - ${e.summary} + +`;if(t+=`Usage: ${e.usage} +`,e.description){if(t+=` +Description: +`,typeof e.description==`string`)for(let n of e.description.split(` +`))t+=n?` ${n} +`:` +`;else if(e.description.length>0)for(let n of e.description)t+=n?` ${n} +`:` +`}if(e.options&&e.options.length>0){t+=` +Options: +`;for(let n of e.options)t+=` ${n} +`}if(e.examples&&e.examples.length>0){t+=` +Examples: +`;for(let n of e.examples)t+=` ${n} +`}if(e.notes&&e.notes.length>0){t+=` +Notes: +`;for(let n of e.notes)t+=` ${n} +`}return{stdout:t,stderr:``,exitCode:0}}function aV(e){return e.includes(`--help`)}function oV(e,t){return{stdout:``,stderr:t.startsWith(`--`)?`${e}: unrecognized option '${t}' +`:`${e}: invalid option -- '${t.replace(/^-/,``)}' +`,exitCode:1}}var sV=B(()=>{});function cV(e,t,n){let r=new Map,i=new Map;for(let[e,t]of Object.entries(n)){let n={name:e,type:t.type};t.short&&r.set(t.short,n),t.long&&i.set(t.long,n)}let a=Object.create(null);for(let[e,t]of Object.entries(n))t.default===void 0?t.type===`boolean`&&(a[e]=!1):a[e]=t.default;let o=[],s=!1;for(let n=0;n=t.length)return{ok:!1,error:{stdout:``,stderr:`${e}: option '--${o}' requires an argument +`,exitCode:1}};s=t[++n]}a[u]=d===`number`?parseInt(s,10):s}}else{let i=c.slice(1);for(let o=0;o{sV()}),uV=B(()=>{});function dV(e,t,n){if(!Number.isSafeInteger(t)||t<0||t>e.limits.maxInputBytes)throw new H(`${n}: input size limit exceeded (${e.limits.maxInputBytes} bytes)`,`string_length`);e.executionScope?.consumeInput(t,n)}async function fV(e,t,n){let{cmdName:r,allowStdinMarker:i=!0,stopOnError:a=!1,batchSize:o=100}=n;if(t.length===0)return{files:[{filename:``,content:e.stdin}],stderr:``,exitCode:0};let s=[],c=``,l=0;for(let n=0;n{if(i&&t===`-`)return{filename:`-`,content:e.stdin,error:null};try{let n=e.fs.resolvePath(e.cwd,t);return{filename:t,content:await xB(e.fs,n),error:null}}catch{return{filename:t,content:OB,error:`${r}: ${t}: No such file or directory +`}}}));for(let e of d)if(e.error){if(c+=e.error,l=1,a)return{files:s,stderr:c,exitCode:l}}else s.push({filename:e.filename,content:e.content})}return{files:s,stderr:c,exitCode:l}}async function pV(e,t,n){let r=await fV(e,t,{...n,stopOnError:!0});return r.exitCode===0?{ok:!0,content:r.files.map(e=>e.content).join(``)}:{ok:!1,error:{stdout:``,stderr:r.stderr,exitCode:r.exitCode}}}var mV=B(()=>{kB(),U(),uV()}),hV={};wz(hV,{catCommand:()=>xV,flagsForFuzzing:()=>SV});function gV(e){if(e>=32){if(e<127)return String.fromCharCode(e);if(e===127)return`^?`;let t=e-128;return t>=32?t===127?`M-^?`:`M-${String.fromCharCode(t)}`:`M-^${String.fromCharCode(t+64)}`}return`^${String.fromCharCode(e+64)}`}function _V(e,t,n){if(!t.showNonprinting&&!t.showTabs)return e;let r=``,i=e=>{if(e.length>n-r.length)throw new H(`cat: output size limit exceeded`,`output_size`);r+=e};for(let n=0;nr)throw new H(`cat: array element limit exceeded (${r})`,`array_elements`);let a=e.split(` +`),o=``,s=1,c=!1,l=e=>{if(e.length>n-o.length)throw new H(`cat: output size limit exceeded (${n} bytes)`,`output_size`);o+=e};for(let e=0;e{kB(),rV(),U(),lV(),mV(),sV(),yV={name:`cat`,summary:`concatenate files and print on the standard output`,usage:`cat [OPTION]... [FILE]...`,options:[`-A, --show-all equivalent to -vET`,`-b, --number-nonblank number nonempty output lines, overrides -n`,`-e equivalent to -vE`,`-E, --show-ends display $ at end of each line`,`-n, --number number all output lines`,`-s, --squeeze-blank suppress repeated empty output lines`,`-t equivalent to -vT`,`-T, --show-tabs display TAB characters as ^I`,`-u (ignored)`,`-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB`,` --help display this help and exit`]},bV={number:{short:`n`,long:`number`,type:`boolean`},numberNonblank:{short:`b`,long:`number-nonblank`,type:`boolean`},showEnds:{short:`E`,long:`show-ends`,type:`boolean`},showTabs:{short:`T`,long:`show-tabs`,type:`boolean`},showNonprinting:{short:`v`,long:`show-nonprinting`,type:`boolean`},showAll:{short:`A`,long:`show-all`,type:`boolean`},squeeze:{short:`s`,long:`squeeze-blank`,type:`boolean`},vE:{short:`e`,type:`boolean`},vT:{short:`t`,type:`boolean`},ignored:{short:`u`,type:`boolean`}},xV={name:`cat`,async execute(e,t){if(aV(e))return iV(yV);let n=cV(`cat`,e,bV);if(!n.ok)return n.error;let r=n.result.flags,i=r.showEnds||r.showAll||r.vE,a=r.showTabs||r.showAll||r.vT,o=r.showNonprinting||r.showAll||r.vE||r.vT,s=r.squeeze,c=r.numberNonblank,l=r.number&&!c,u={numberAll:l,numberNonblank:c,showEnds:i,showTabs:a,showNonprinting:o,squeeze:s},d=n.result.positional,f=t.limits.maxStringLength,p=Math.min(f,t.limits.maxOutputSize),m=d.length===0?[`-`]:d,h=``,g=0,_=0,v,y=i||a||o||s||l||c,b=``;for(let e of m)try{let n=e===`-`?t.stdin:await xB(t.fs,t.fs.resolvePath(t.cwd,e)),r=n.length,i=Math.min(y?f:p,t.limits.maxInputBytes);if(r>i-_)throw new H(`cat: ${y?`input`:`output`} size limit exceeded (${i} bytes)`,y?`string_length`:`output_size`);e!==`-`&&dV(t,r,`cat`),_+=r,b+=n}catch(t){nV(t),h+=`cat: ${e}: No such file or directory +`,g=1}return v=y?vV(b,u,p,t.limits.maxArrayElements):b,{stdout:v,stderr:h,exitCode:g,stdoutEncoding:`binary`}}},SV={name:`cat`,flags:[{flag:`-n`,type:`boolean`},{flag:`-A`,type:`boolean`},{flag:`-b`,type:`boolean`},{flag:`-s`,type:`boolean`},{flag:`-v`,type:`boolean`},{flag:`-e`,type:`boolean`},{flag:`-t`,type:`boolean`}],stdinType:`text`,needsFiles:!0}});function wV(e){return e instanceof Error?e.message:String(e)}var TV=B(()=>{});function EV(e,t,n,r={}){let i=new Date(t*1e3),a=DV(i,n),o=``,s=0,c=0,l=0,u=new Map,d=e=>{let t=V(e);if(r.maxOutputBytes!==void 0&&t>r.maxOutputBytes-s)throw new H(`strftime: output size limit exceeded (${r.maxOutputBytes} bytes)`,`output_size`);o+=e,s+=t};for(;cr.maxOperations)throw new H(`strftime: iteration limit exceeded (${r.maxOperations})`,`iterations`);if(e[c]===`%`&&c+1t.find(t=>t.type===e)?.value??``,i=new Map([[`Sun`,0],[`Mon`,1],[`Tue`,2],[`Wed`,3],[`Thu`,4],[`Fri`,5],[`Sat`,6]]),a=r(`weekday`),o=(e,t)=>{let n=Number.parseInt(e,10);return Number.isNaN(n)?t:n};return{year:o(r(`year`),e.getFullYear()),month:o(r(`month`),e.getMonth()+1),day:o(r(`day`),e.getDate()),hour:o(r(`hour`),e.getHours())%24,minute:o(r(`minute`),e.getMinutes()),second:o(r(`second`),e.getSeconds()),weekday:i.get(a)??e.getDay()}}catch{return{year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),weekday:e.getDay()}}}function OV(e,t,n,r){let i=(e,t=2)=>String(e).padStart(t,`0`),a=jV(t.year,t.month,t.day),o=MV(t.year,t.month,t.day,t.weekday,0),s=MV(t.year,t.month,t.day,t.weekday,1);switch(n){case`a`:return[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`][t.weekday];case`A`:return[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][t.weekday];case`b`:case`h`:return[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`][t.month-1];case`B`:return[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`][t.month-1];case`c`:return`${[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`][t.weekday]} ${[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`][t.month-1]} ${String(t.day).padStart(2,` `)} ${i(t.hour)}:${i(t.minute)}:${i(t.second)} ${t.year}`;case`C`:return i(Math.floor(t.year/100));case`d`:return i(t.day);case`D`:return`${i(t.month)}/${i(t.day)}/${i(t.year%100)}`;case`e`:return String(t.day).padStart(2,` `);case`F`:return`${t.year}-${i(t.month)}-${i(t.day)}`;case`g`:return i(PV(t.year,t.month,t.day)%100);case`G`:return String(PV(t.year,t.month,t.day));case`H`:return i(t.hour);case`I`:return i(t.hour%12||12);case`j`:return String(a).padStart(3,`0`);case`k`:return String(t.hour).padStart(2,` `);case`l`:return String(t.hour%12||12).padStart(2,` `);case`m`:return i(t.month);case`M`:return i(t.minute);case`n`:return` +`;case`N`:return`000000000`;case`p`:return t.hour<12?`AM`:`PM`;case`P`:return t.hour<12?`am`:`pm`;case`r`:return`${i(t.hour%12||12)}:${i(t.minute)}:${i(t.second)} ${t.hour<12?`AM`:`PM`}`;case`R`:return`${i(t.hour)}:${i(t.minute)}`;case`s`:return String(Math.floor(e.getTime()/1e3));case`S`:return i(t.second);case`t`:return` `;case`T`:return`${i(t.hour)}:${i(t.minute)}:${i(t.second)}`;case`u`:return String(t.weekday===0?7:t.weekday);case`U`:return i(o);case`V`:return i(NV(t.year,t.month,t.day));case`w`:return String(t.weekday);case`W`:return i(s);case`x`:return`${i(t.month)}/${i(t.day)}/${i(t.year%100)}`;case`X`:return`${i(t.hour)}:${i(t.minute)}:${i(t.second)}`;case`y`:return i(t.year%100);case`Y`:return String(t.year);case`z`:return kV(e,r);case`Z`:return AV(e,r);case`%`:return`%`;default:return null}}function kV(e,t){if(!t){let t=-e.getTimezoneOffset(),n=t>=0?`+`:`-`,r=Math.floor(Math.abs(t)/60),i=Math.abs(t)%60;return`${n}${String(r).padStart(2,`0`)}${String(i).padStart(2,`0`)}`}try{let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,timeZoneName:`longOffset`}).formatToParts(e).find(e=>e.type===`timeZoneName`);if(n){let e=n.value.match(/GMT([+-])(\d{2}):(\d{2})/);if(e)return`${e[1]}${e[2]}${e[3]}`;if(n.value===`GMT`||n.value===`UTC`)return`+0000`}}catch{}let n=-e.getTimezoneOffset(),r=n>=0?`+`:`-`,i=Math.floor(Math.abs(n)/60),a=Math.abs(n)%60;return`${r}${String(i).padStart(2,`0`)}${String(a).padStart(2,`0`)}`}function AV(e,t){try{return new Intl.DateTimeFormat(`en-US`,{timeZone:t,timeZoneName:`short`}).formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??`UTC`}catch{return`UTC`}}function jV(e,t,n){let r=[31,28,31,30,31,30,31,31,30,31,30,31];(e%4==0&&e%100!=0||e%400==0)&&(r[1]=29);let i=n;for(let e=0;e{U(),XB()}),IV={};wz(IV,{flagsForFuzzing:()=>$V,printfCommand:()=>ZV});function LV(e){let t=``,n=0;for(;n=194){let i=(r&31)<<6|e[n+1]&63;t+=String.fromCharCode(i),n+=2;continue}t+=String.fromCharCode(r),n++;continue}if((r&240)==224){if(n+2=55296&&i<=57343){t+=String.fromCharCode(r),n++;continue}t+=String.fromCharCode(i),n+=3;continue}t+=String.fromCharCode(r),n++;continue}if((r&248)==240&&r<=244){if(n+31114111){t+=String.fromCharCode(r),n++;continue}t+=String.fromCodePoint(i),n+=4;continue}t+=String.fromCharCode(r),n++;continue}t+=String.fromCharCode(r),n++}return t}function RV(e,t,n,r,i=10485760){let a=``,o=0,s=0,c=!1,l=``,u=0,d=e=>{let t=V(e);if(t>i-u)throw new H(`printf: output size limit exceeded (${i} bytes)`,`string_length`);a+=e,u+=t};for(;o=0?GB(e,i-u,`precision`):Number.isSafeInteger(e)||GB(e,i-u,`precision`),s++,_=_.replace(`.*`,`.${e}`)}BV(_,i-u);let v=t[n+s]||``;s++;let{value:y,parseError:b,parseErrMsg:x,stopped:S}=zV(_,g,v,i-u);if(d(y),b&&(c=!0,x&&(l=x)),S)return{result:a,argsConsumed:s,error:c,errMsg:l,stopped:!0}}else d(e[o]),o++;return{result:a,argsConsumed:s,error:c,errMsg:l,stopped:!1}}function zV(e,t,n,r){let i=!1,a=``;switch(t){case`d`:case`i`:{let t=VV(n);return i=QV,i&&(a=`printf: ${n}: invalid number +`),{value:HV(e,t),parseError:i,parseErrMsg:a}}case`o`:{let t=VV(n);return i=QV,i&&(a=`printf: ${n}: invalid number +`),{value:UV(e,t),parseError:i,parseErrMsg:a}}case`u`:{let t=VV(n);i=QV,i&&(a=`printf: ${n}: invalid number +`);let r=t<0?t>>>0:t;return{value:HV(e.replace(`u`,`d`),r),parseError:i,parseErrMsg:a}}case`x`:case`X`:{let t=VV(n);return i=QV,i&&(a=`printf: ${n}: invalid number +`),{value:WV(e,t),parseError:i,parseErrMsg:a}}case`e`:case`E`:case`f`:case`F`:case`g`:case`G`:return{value:JV(e,t,parseFloat(n)||0),parseError:!1,parseErrMsg:``};case`c`:{if(n===``)return{value:``,parseError:!1,parseErrMsg:``};let e=new TextEncoder().encode(n)[0];return{value:String.fromCharCode(e),parseError:!1,parseErrMsg:``}}case`s`:return{value:KV(e,n,r),parseError:!1,parseErrMsg:``};case`q`:return{value:qV(e,n,r),parseError:!1,parseErrMsg:``};case`b`:{let e=YV(n,r);return{value:e.value,parseError:!1,parseErrMsg:``,stopped:e.stopped}}default:try{return{value:(0,KI.sprintf)(e,n),parseError:!1,parseErrMsg:``}}catch{return{value:``,parseError:!0,parseErrMsg:`printf: [sprintf] unexpected placeholder +`}}}}function BV(e,t){let n=e.match(/^%[-+0 #' ]*(\d*)(?:\.(\d*))?/);if(!n)return;let r=n[1]?Number(n[1]):0,i=n[2]===void 0?-1:Number(n[2]);GB(r,t,`width`),i!==-1&&GB(i,t,`precision`)}function VV(e){QV=!1;let t=e.trimStart(),n=t!==t.trimEnd();if(e=t.trimEnd(),e.startsWith(`'`)&&e.length>=2||e.startsWith(`"`)&&e.length>=2)return e.charCodeAt(1);if(e.startsWith(`\\'`)&&e.length>=3||e.startsWith(`\\"`)&&e.length>=3)return e.charCodeAt(2);if(e.startsWith(`+`)&&(e=e.slice(1)),e.startsWith(`0x`)||e.startsWith(`0X`)){let t=parseInt(e,16);return Number.isNaN(t)?(QV=!0,0):(n&&(QV=!0),t)}if(e.startsWith(`0`)&&e.length>1&&/^-?0[0-7]+$/.test(e))return n&&(QV=!0),parseInt(e,8)||0;if(/^\d+#/.test(e)){QV=!0;let t=e.match(/^(\d+)#/);return t?parseInt(t[1],10):0}if(e!==``&&!/^-?\d+$/.test(e)){QV=!0;let t=parseInt(e,10);return Number.isNaN(t)?0:t}return n&&(QV=!0),parseInt(e,10)||0}function HV(e,t){let n=e.match(/^%([- +#0']*)(\d*)(\.(\d*))?[diu]$/);if(!n)return(0,KI.sprintf)(e.replace(/\.\d*/,``),t);let r=n[1]||``,i=n[2]?parseInt(n[2],10):0,a=n[3]===void 0?-1:n[4]?parseInt(n[4],10):0,o=t<0,s=String(Math.abs(t));a>=0&&(s=s.padStart(a,`0`));let c=``;o?c=`-`:r.includes(`+`)?c=`+`:r.includes(` `)&&(c=` `);let l=c+s;return i>l.length&&(l=r.includes(`-`)?l.padEnd(i,` `):r.includes(`0`)&&a<0?c+s.padStart(i-c.length,`0`):l.padStart(i,` `)),l}function UV(e,t){let n=e.match(/^%([- +#0']*)(\d*)(\.(\d*))?o$/);if(!n)return(0,KI.sprintf)(e,t);let r=n[1]||``,i=n[2]?parseInt(n[2],10):0,a=n[3]===void 0?-1:n[4]?parseInt(n[4],10):0,o=Math.abs(t).toString(8);a>=0&&(o=o.padStart(a,`0`)),r.includes(`#`)&&!o.startsWith(`0`)&&(o=`0${o}`);let s=o;return i>s.length&&(s=r.includes(`-`)?s.padEnd(i,` `):r.includes(`0`)&&a<0?s.padStart(i,`0`):s.padStart(i,` `)),s}function WV(e,t){let n=e.includes(`X`),r=e.match(/^%([- +#0']*)(\d*)(\.(\d*))?[xX]$/);if(!r)return(0,KI.sprintf)(e,t);let i=r[1]||``,a=r[2]?parseInt(r[2],10):0,o=r[3]===void 0?-1:r[4]?parseInt(r[4],10):0,s=Math.abs(t).toString(16);n&&(s=s.toUpperCase()),o>=0&&(s=s.padStart(o,`0`));let c=``;i.includes(`#`)&&t!==0&&(c=n?`0X`:`0x`);let l=c+s;return a>l.length&&(l=i.includes(`-`)?l.padEnd(a,` `):i.includes(`0`)&&o<0?c+s.padStart(a-c.length,`0`):l.padStart(a,` `)),l}function GV(e,t){if(e===``){if(t<2)throw new H(`printf: output size limit exceeded (${t} bytes)`,`string_length`);return`''`}if(/^[a-zA-Z0-9_./-]+$/.test(e)){if(V(e)>t)throw new H(`printf: output size limit exceeded (${t} bytes)`,`string_length`);return e}let n=/[\x00-\x1f\x7f-\xff]/.test(e),r=n?3:0;for(let i of e){let e=i.charCodeAt(0);if(r+=n?i===`'`||i===`\\`||i===` +`||i===` `||i===`\r`||i===`\x07`||i===`\b`||i===`\f`||i===`\v`||i===`\x1B`||i===`"`?2:e<32||e>=127&&e<=255?4:V(i):V(i)+ +!!` |&;<>()$\`\\"'*?[#~=%!{}`.includes(i),r>t)throw new H(`printf: output size limit exceeded (${t} bytes)`,`string_length`)}if(n){let t=`$'`;for(let n of e){let e=n.charCodeAt(0);t+=n===`'`?`\\'`:n===`\\`?`\\\\`:n===` +`?`\\n`:n===` `?`\\t`:n===`\r`?`\\r`:n===`\x07`?`\\a`:n===`\b`?`\\b`:n===`\f`?`\\f`:n===`\v`?`\\v`:n===`\x1B`?`\\E`:e<32||e>=127&&e<=255?`\\${e.toString(8).padStart(3,`0`)}`:n===`"`?`\\"`:n}return t+=`'`,t}let i=``;for(let t of e)` |&;<>()$\`\\"'*?[#~=%!{}`.includes(t)?i+=`\\${t}`:i+=t;return i}function KV(e,t,n){let r=e.match(/^%(-?)(\d*)(\.(\d*))?s$/);if(!r)return(0,KI.sprintf)(e.replace(/0+(?=\d)/,``),t);let i=r[1]===`-`,a=r[2]?parseInt(r[2],10):0,o=r[3]===void 0?-1:r[4]?parseInt(r[4],10):0;return KB(t,i?-a:a,o,n)}function qV(e,t,n){let r=GV(t,n),i=e.match(/^%(-?)(\d*)q$/);if(!i)return r;let a=i[1]===`-`,o=i[2]?parseInt(i[2],10):0;return KB(r,a?-o:o,-1,n)}function JV(e,t,n){let r=e.match(/^%([- +#0']*)(\d*)(\.(\d*))?[eEfFgG]$/);if(!r)return(0,KI.sprintf)(e,n);let i=r[1]||``,a=r[2]?parseInt(r[2],10):0,o=r[3]===void 0?6:r[4]?parseInt(r[4],10):0,s,c=t.toLowerCase();if(c===`e`?(s=n.toExponential(o),s=s.replace(/e([+-])(\d)$/,`e$10$2`),t===`E`&&(s=s.toUpperCase())):c===`f`?(s=n.toFixed(o),i.includes(`#`)&&o===0&&!s.includes(`.`)&&(s+=`.`)):c===`g`?(s=n.toPrecision(o||1),i.includes(`#`)||(s=s.replace(/\.?0+$/,``),s=s.replace(/\.?0+e/,`e`)),s=s.replace(/e([+-])(\d)$/,`e$10$2`),t===`G`&&(s=s.toUpperCase())):s=n.toString(),n>=0&&(i.includes(`+`)?s=`+${s}`:i.includes(` `)&&(s=` ${s}`)),a>s.length){if(i.includes(`-`))s=s.padEnd(a,` `);else if(i.includes(`0`)){let e=s.match(/^[+ -]/)?.[0]||``;s=e+(e?s.slice(1):s).padStart(a-e.length,`0`)}else s=s.padStart(a,` `)}return s}function YV(e,t){if(V(e)>t)throw new H(`printf: output size limit exceeded (${t} bytes)`,`string_length`);let n=``,r=0;for(;r0?(n+=LV(t),r=i):(n+=`\\x`,r+=2);break}case`u`:{let t=``,i=r+2;for(;i{U(),TV(),sV(),XB(),FV(),XV={name:`printf`,summary:`format and print data`,usage:`printf [-v var] FORMAT [ARGUMENT...]`,options:[` -v var assign the output to shell variable VAR rather than display it`,` --help display this help and exit`],notes:[`FORMAT controls the output like in C printf.`,`Escape sequences: \\n (newline), \\t (tab), \\\\ (backslash)`,`Format specifiers: %s (string), %d (integer), %f (float), %x (hex), %o (octal), %% (literal %)`,`Width and precision: %10s (width 10), %.2f (2 decimal places), %010d (zero-padded)`,`Flags: %- (left-justify), %+ (show sign), %0 (zero-pad)`]},ZV={name:`printf`,async execute(e,t){if(aV(e))return iV(XV);if(e.length===0)return{stdout:``,stderr:`printf: usage: printf format [arguments] +`,exitCode:2,internalStdinConsumed:0};let n=null,r=0;for(;r=e.length)return{stdout:``,stderr:`printf: -v: option requires an argument +`,exitCode:1,internalStdinConsumed:0};if(n=e[r+1],!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\[[^\]\n]+\])?$/.test(n)||/[;\r\\]/.test(n)||n.includes(`..`))return{stdout:``,stderr:`printf: \`${n}': not a valid identifier +`,exitCode:2,internalStdinConsumed:0};r+=2}else{if(t.startsWith(`-`)&&t!==`-`)break;break}}if(r>=e.length)return{stdout:``,stderr:`printf: usage: printf format [arguments] +`,exitCode:1,internalStdinConsumed:0};let i=e[r],a=e.slice(r+1);try{let e=Math.min(t.limits.maxStringLength,t.limits.maxOutputSize),r=JB(i,e),o=``,s=0,c=0,l=!1,u=``,d=t.env.get(`TZ`);do{let{result:t,argsConsumed:n,error:i,errMsg:f,stopped:p}=RV(r,a,c,d,e-s),m=V(t);if(m>e-s)throw new H(`printf: output size limit exceeded (${e} bytes)`,`string_length`);if(o+=t,s+=m,c+=n,i&&(l=!0,f&&(u=f)),p)break}while(c0);if(c===0&&a.length,n){let e=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(['"]?)(.+?)\2\]$/);if(e){let n=e[1],r=e[3];if(r=r.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(e,n)=>t.env.get(n)??``),t.assignShellVariable)await t.assignShellVariable(n,o,r);else throw Error(`printf -v array assignment requires an interpreter assignment gateway`)}else if(t.assignShellVariable)await t.assignShellVariable(n,o);else{if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n))throw Error(`${n}: not a valid identifier`);t.env.set(n,o)}return{stdout:``,stderr:u,exitCode:+!!l,internalStdinConsumed:0}}return{stdout:o,stderr:u,exitCode:+!!l,internalStdinConsumed:0}}catch(e){if(e instanceof H||typeof e==`object`&&e&&`name`in e&&e.name===`ExitError`)throw e;return{stdout:``,stderr:`printf: ${wV(e)} +`,exitCode:1,internalStdinConsumed:0}}}},QV=!1,$V={name:`printf`,flags:[{flag:`-v`,type:`value`,valueHint:`string`}],stdinType:`none`,needsArgs:!0}});function tH(e,t){if(!Number.isSafeInteger(e)||e<0)throw new H(`${t}: invalid bounded allocation count`,`array_elements`)}function nH(e){return new H(`${e}: invalid bounded allocation count`,`array_elements`)}function rH(e,t,n){tH(e,n),tH(t,n);let r=e+t;if(!Number.isSafeInteger(r))throw nH(n);return r}function iH(e,t,n){if(tH(e,n),tH(t,n),e!==0&&t>Math.floor((2**53-1)/e))throw nH(n);return e*t}function aH(e,t,n,r){let i=new oH(n,r);for(let n=0;n0&&i.append(t),i.append(e[n]);return i.build()}var oH,sH=B(()=>{kB(),U(),oH=class{maxBytes;label;createLimitError;reservedBytes;chunks=[];usedBytes=0;constructor(e,t,n=void 0,r=0){this.maxBytes=e,this.label=t,this.createLimitError=n,this.reservedBytes=r,tH(e,t),tH(r,t),r>e&&this.fail()}fail(){throw this.createLimitError?.()??new H(`${this.label}: output size limit exceeded (${this.maxBytes} bytes)`,`output_size`)}get byteLength(){return this.usedBytes}get remainingBytes(){return this.maxBytes-this.reservedBytes-this.usedBytes}reserve(e){tH(e,this.label),e>this.remainingBytes&&this.fail()}append(e){let t=V(e);return this.reserve(t),e&&this.chunks.push(e),this.usedBytes+=t,this}repeat(e,t){tH(t,this.label);let n=V(e);return n!==0&&t>Math.floor(this.remainingBytes/n)&&this.fail(),this.append(e.repeat(t))}reset(){this.chunks.length=0,this.usedBytes=0}build(){return this.chunks.join(``)}}});function cH(e){if(!e||e===`/`)return`/`;let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e;t.startsWith(`/`)||(t=`/${t}`);let n=t.split(`/`).filter(e=>e&&e!==`.`),r=[];for(let e of n)e===`..`?r.pop():r.push(e);return`/${r.join(`/`)}`||`/`}function lH(e,t){let n=cH(e),r=cH(t);return r===n||n===`/`||r.startsWith(`${n}/`)}function uH(e,t){if(e.includes(`\0`))throw Error(`ENOENT: path contains null byte, ${t} '${e}'`)}function dH(e){let t=cH(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function fH(e,t){return t.startsWith(`/`)?cH(t):cH(e===`/`?`/${t}`:`${e}/${t}`)}function pH(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function mH(e,t){return t.startsWith(`/`)?cH(t):cH(pH(dH(e),t))}var hH=B(()=>{});function gH(e,t,n){if(!e)return e;let r=e.replace(/\n\s+at\s.*/g,``);return n&&(r=r.replace(/\bfile:\/\/\/?[^\s'",)}\]:]+/g,``)),r=r.replace(t?/(?:\/(?:Users|home|private|var|opt|Library|System|usr|etc|tmp|nix|snap|workspace|root|srv|mnt|app))\b[^\s'",)}\]:]*/g:/(?:\/(?:Users|home|private|var|opt|Library|System|usr|etc|tmp|nix|snap))\b[^\s'",)}\]:]*/g,``),r=r.replace(/node:internal\/[^\s'",)}\]:]+/g,``),r=r.replace(/[A-Z]:\\[^\s'",)}\]:]+/g,``),n&&(r=r.replace(/\\\\[^\s\\]+\\[^\s'",)}\]:]+/g,``)),r}function _H(e){return gH(e,!1,!1)}var vH=B(()=>{});function yH(e){if(e.identity!==void 0)return`identity:${e.identity}`;if(e.dev!==void 0&&e.ino!==void 0)return`inode:${String(e.dev)}:${String(e.ino)}`}function bH(e){let t=e instanceof Error?e.message:String(e);return t.includes(`ENOENT`)||t.includes(`no such file`)}async function xH(e,t,n){let r=cH(t),i;try{i=await e.stat(r)}catch(e){if(!bH(e))return{existence:`unknown`}}if(i!==void 0){let t=yH(i);try{return{existence:`existing`,canonicalPath:cH(await e.realpath(r)),stableIdentity:t}}catch{return t===void 0?{existence:`unknown`}:{existence:`existing`,stableIdentity:t}}}let a=[],o=r;for(;;){n?.checkpoint();let t=dH(o);if(t===o)return{existence:`unknown`};a.unshift(o.slice(t===`/`?1:t.length+1)),o=t;try{let t=cH(await e.realpath(o));return{existence:`missing`,canonicalPath:a.reduce((e,t)=>pH(e,t),t)}}catch(e){if(!bH(e))return{existence:`missing`}}}}async function SH(e,t,n){let[r,i]=await Promise.all([xH(e,t),xH(e,n)]);return r.existence===`unknown`||i.existence===`unknown`?`unknown`:r.existence===`missing`||i.existence===`missing`?r.existence===i.existence?r.canonicalPath!==void 0&&r.canonicalPath===i.canonicalPath?`same`:`unknown`:`different`:r.stableIdentity!==void 0&&i.stableIdentity!==void 0?r.stableIdentity===i.stableIdentity?`same`:`different`:r.canonicalPath!==void 0&&r.canonicalPath===i.canonicalPath?`same`:`unknown`}async function CH(e,t,n,r){let[i,a]=await Promise.all([xH(e,t,r),xH(e,n,r)]);return i.existence!==`existing`||i.canonicalPath===void 0||a.existence===`unknown`||a.canonicalPath===void 0?`unknown`:lH(i.canonicalPath,a.canonicalPath)?`inside`:`outside`}async function wH(e,t){let n=e.budget??new EH(e),r=[{kind:`enter`,path:cH(e.root),depth:0}],i=new Set;for(;r.length>0;){n.checkpoint(0);let a=r.pop();if(!a)break;if(a.kind===`leave`){e.includeLeave&&await t({path:a.path,depth:a.depth,stat:a.stat,isSymlink:a.isSymlink,phase:`leave`}),a.identity&&i.delete(a.identity);continue}n.visit(a.depth);let o=await e.fs.lstat(a.path),s=o.isSymbolicLink,c=s&&e.symlinks===`follow`?await e.fs.stat(a.path):o;if(await t({path:a.path,depth:a.depth,stat:c,isSymlink:s,phase:`enter`}),!c.isDirectory||s&&e.symlinks!==`follow`)continue;let l=yH(c)??await e.fs.realpath(a.path).then(cH).catch(()=>{});if(l!==void 0){if(i.has(l))throw new TH(e.site,a.path,`symbolic-link directory cycle detected`);i.add(l)}r.push({kind:`leave`,path:a.path,depth:a.depth,stat:c,isSymlink:s,identity:l});let u=await e.fs.readdir(a.path);n.checkpoint(),u.sort((e,t)=>e.localeCompare(t));for(let e=u.length-1;e>=0;e--)r.push({kind:`enter`,path:pH(a.path,u[e]),depth:a.depth+1})}}var TH,EH,DH=B(()=>{U(),hH(),vH(),TH=class extends Error{operation;virtualPath;name=`FileSystemPolicyError`;constructor(e,t,n){super(`${e}: ${_H(n)}`),this.operation=e,this.virtualPath=t}},EH=class{options;entries=0;discoveredEntries=1;work=0;constructor(e){this.options=e}checkpoint(e=1){if(this.options.signal?.aborted)throw new HB;if(this.options.executionScope?.throwIfAborted(this.options.site),!Number.isSafeInteger(e)||e<0||e>this.options.limits.maxTraversalWork-this.work)throw new H(`${this.options.site}: ${this.options.label??`filesystem traversal work`} limit exceeded (${this.options.limits.maxTraversalWork})`,`iterations`);this.work+=e,this.options.executionScope?.consumeWork(e,`${this.options.site} filesystem traversal`)}visit(e){if(this.checkpoint(),e>this.options.limits.maxTraversalDepth)throw new H(`${this.options.site}: ${this.options.label??`filesystem traversal`} depth limit exceeded (${this.options.limits.maxTraversalDepth})`,`recursion`);if(++this.entries>this.options.limits.maxTraversalEntries)throw new H(`${this.options.site}: ${this.options.label??`filesystem traversal`} entry limit exceeded (${this.options.limits.maxTraversalEntries})`,`iterations`)}discover(e){if(!Number.isSafeInteger(e)||e<0||e>this.options.limits.maxTraversalEntries-this.discoveredEntries)throw new H(`${this.options.site}: ${this.options.label??`filesystem traversal`} entry limit exceeded (${this.options.limits.maxTraversalEntries})`,`iterations`);this.checkpoint(e),this.discoveredEntries+=e}}}),OH={};wz(OH,{flagsForFuzzing:()=>zH,lsCommand:()=>RH});function kH(e,t,n){if(V(n)>e.limits.maxOutputSize-V(t))throw new H(`ls: output size limit exceeded (${e.limits.maxOutputSize} bytes)`,`output_size`);return t+n}function AH(e,t){let n=new oH(e.limits.maxOutputSize,`ls`);for(let e=0;e0&&n.append(` +`),n.append(t[e]);return t.length>0&&n.append(` +`),n.build()}function jH(e){if(e<1024)return String(e);if(e<1048576){let t=e/1024;return t<10?`${t.toFixed(1)}K`:`${Math.round(t)}K`}if(e<1073741824){let t=e/1048576;return t<10?`${t.toFixed(1)}M`:`${Math.round(t)}M`}let t=e/1073741824;return t<10?`${t.toFixed(1)}G`:`${Math.round(t)}G`}function MH(e){let t=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`][e.getMonth()],n=String(e.getDate()).padStart(2,` `);return e>new Date(new Date().getTime()-15552e6)?`${t} ${n} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}`:`${t} ${n} ${e.getFullYear()}`}function NH(e){return e.isDirectory?`/`:e.isSymbolicLink?`@`:e.mode&73?`*`:``}async function PH(e,t,n,r,i,a=!1,o=!1,s=!1,c=!1,l){let u=n||r,d=t.fs.getAllPaths(),f=t.fs.resolvePath(t.cwd,`.`),p=[];for(let t of d){l?.visit(t.split(`/`).length-1);let n=(t===f||f===`/`||t.startsWith(`${f}/`))&&t.slice(f===`/`?1:f.length+1)||t;if(qL(n,e)||qL(t,e)){let e=n.split(`/`).pop()||n;if(!u&&e.startsWith(`.`))continue;p.push(n||t)}}if(p.length===0)return{stdout:``,stderr:`ls: ${e}: No such file or directory +`,exitCode:2};if(s){let e=[];for(let n of p){let r=t.fs.resolvePath(t.cwd,n);try{let i=await t.fs.stat(r);e.push({path:n,size:i.size??0})}catch{e.push({path:n,size:0})}}e.sort((e,t)=>t.size-e.size),p.length=0,p.push(...e.map(e=>e.path))}else p.sort();if(a&&p.reverse(),i){let e=[];for(let n of p){let r=t.fs.resolvePath(t.cwd,n);try{let i=await t.fs.stat(r),a=i.isDirectory?`drwxr-xr-x`:`-rw-r--r--`,s=c?NH(await t.fs.lstat(r)):i.isDirectory?`/`:``,l=i.size??0,u=o?jH(l).padStart(5):String(l).padStart(5),d=MH(i.mtime??new Date(0));e.push(`${a} 1 user user ${u} ${d} ${n}${s}`)}catch{e.push(`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${n}`)}}return{stdout:AH(t,e),stderr:``,exitCode:0}}if(c){let e=[];for(let n of p){let r=t.fs.resolvePath(t.cwd,n);try{let i=await t.fs.lstat(r);e.push(`${n}${NH(i)}`)}catch{e.push(n)}}return{stdout:AH(t,e),stderr:``,exitCode:0}}return{stdout:AH(t,p),stderr:``,exitCode:0}}async function FH(e,t,n,r,i,a,o,s=!1,c=!1,l=!1,u=!1,d=!1,f=new EH({limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:`ls`}),p=0,m=new Set){let h=n||r,g=t.fs.resolvePath(t.cwd,e);try{f.visit(p);let d=await t.fs.stat(g);if(!d.isDirectory){let n=u?NH(await t.fs.lstat(g)):``;if(i){let t=d.size??0;return{stdout:`-rw-r--r-- 1 user user ${c?jH(t).padStart(5):String(t).padStart(5)} ${MH(d.mtime??new Date(0))} ${e}${n} +`,stderr:``,exitCode:0}}return{stdout:`${e}${n} +`,stderr:``,exitCode:0}}let _=d.identity??(d.dev!==void 0&&d.ino!==void 0?`${String(d.dev)}:${String(d.ino)}`:await t.fs.realpath(g).catch(()=>{}));if(_!==void 0&&m.has(_))return{stdout:``,stderr:`ls: ${e}: symbolic link cycle detected +`,exitCode:2};let v=new Set(m);_!==void 0&&v.add(_);let y=await t.fs.readdir(g);if(f.checkpoint(),h||(y=y.filter(e=>!e.startsWith(`.`))),l){let e=[];for(let n of y){let r=g===`/`?`/${n}`:`${g}/${n}`;try{let i=await t.fs.stat(r);e.push({name:n,size:i.size??0})}catch{e.push({name:n,size:0})}}e.sort((e,t)=>t.size-e.size),y=e.map(e=>e.name)}else y.sort();n&&(y=[`.`,`..`,...y]),s&&y.reverse();let b=``,x=``,S=0;if((a||o)&&(b=kH(t,b,`${e}: +`)),i){b=kH(t,b,`total ${y.length} +`);let e=y.filter(e=>e===`.`||e===`..`),n=y.filter(e=>e!==`.`&&e!==`..`);for(let n of e)b=kH(t,b,`drwxr-xr-x 1 user user 0 Jan 1 00:00 ${n} +`);let r=[];for(let e=0;e{let n=g===`/`?`/${e}`:`${g}/${e}`;try{let r=await t.fs.stat(n),i=r.isDirectory?`drwxr-xr-x`:`-rw-r--r--`,a=u?NH(await t.fs.lstat(n)):r.isDirectory?`/`:``,o=r.size??0;return{name:e,line:`${i} 1 user user ${c?jH(o).padStart(5):String(o).padStart(5)} ${MH(r.mtime??new Date(0))} ${e}${a} +`}}catch{return{name:e,line:`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${e} +`}}}));r.push(...a)}let i=new Map(n.map((e,t)=>[e,t]));r.sort((e,t)=>(i.get(e.name)??0)-(i.get(t.name)??0));for(let{line:e}of r)b=kH(t,b,e)}else if(u){let e=[],n=y.filter(e=>e!==`.`&&e!==`..`),r=y.filter(e=>e===`.`||e===`..`);for(let t of r)e.push(`${t}/`);for(let r=0;r{let n=g===`/`?`/${e}`:`${g}/${e}`;try{return`${e}${NH(await t.fs.lstat(n))}`}catch{return e}}));e.push(...a)}b=kH(t,b,AH(t,e))}else b=kH(t,b,AH(t,y));if(a){let o=y.filter(e=>e!==`.`&&e!==`..`),d=[];if(t.fs.readdirWithFileTypes)d=(await t.fs.readdirWithFileTypes(g)).filter(e=>e.isDirectory&&o.includes(e.name)).map(e=>({name:e.name,isDirectory:!0}));else for(let e=0;e{let n=g===`/`?`/${e}`:`${g}/${e}`;try{return{name:e,isDirectory:(await t.fs.stat(n)).isDirectory}}catch{return{name:e,isDirectory:!1}}}));d.push(...r.filter(e=>e.isDirectory))}d.sort((e,t)=>e.name.localeCompare(t.name)),s&&d.reverse();let m=[];for(let o=0;o{let d=await FH(e===`.`?`./${o.name}`:`${e}/${o.name}`,t,n,r,i,a,!1,s,c,l,u,!0,f,p+1,v);return{name:o.name,result:d}}));m.push(...g)}m.sort((e,t)=>e.name.localeCompare(t.name)),s&&m.reverse();for(let{result:e}of m)b=kH(t,b,` +`),b=kH(t,b,e.stdout),x=kH(t,x,e.stderr),e.exitCode!==0&&(S=e.exitCode)}return{stdout:b,stderr:x,exitCode:S}}catch(t){if(t instanceof H||t instanceof HB)throw t;return{stdout:``,stderr:`ls: ${e}: No such file or directory +`,exitCode:2}}}var IH,LH,RH,zH,BH=B(()=>{sH(),kB(),DH(),U(),lV(),uV(),sV(),IH={name:`ls`,summary:`list directory contents`,usage:`ls [OPTION]... [FILE]...`,options:[`-a, --all do not ignore entries starting with .`,`-A, --almost-all do not list . and ..`,`-d, --directory list directories themselves, not their contents`,`-F, --classify append indicator (one of */=>@) to entries`,`-h, --human-readable with -l, print sizes like 1K 234M 2G etc.`,`-l use a long listing format`,`-r, --reverse reverse order while sorting`,`-R, --recursive list subdirectories recursively`,`-S sort by file size, largest first`,`-t sort by time, newest first`,`-1 list one file per line`,` --help display this help and exit`]},LH={showAll:{short:`a`,long:`all`,type:`boolean`},showAlmostAll:{short:`A`,long:`almost-all`,type:`boolean`},longFormat:{short:`l`,type:`boolean`},humanReadable:{short:`h`,long:`human-readable`,type:`boolean`},recursive:{short:`R`,long:`recursive`,type:`boolean`},reverse:{short:`r`,long:`reverse`,type:`boolean`},sortBySize:{short:`S`,type:`boolean`},classifyFiles:{short:`F`,long:`classify`,type:`boolean`},directoryOnly:{short:`d`,long:`directory`,type:`boolean`},sortByTime:{short:`t`,type:`boolean`},onePerLine:{short:`1`,type:`boolean`}},RH={name:`ls`,async execute(e,t){if(aV(e))return iV(IH);let n=cV(`ls`,e,LH);if(!n.ok)return n.error;let r=n.result.flags.showAll,i=n.result.flags.showAlmostAll,a=n.result.flags.longFormat,o=n.result.flags.humanReadable,s=n.result.flags.recursive,c=n.result.flags.reverse,l=n.result.flags.sortBySize,u=n.result.flags.classifyFiles,d=n.result.flags.directoryOnly;n.result.flags.sortByTime,n.result.flags.onePerLine;let f=n.result.positional;f.length===0&&f.push(`.`);let p=``,m=``,h=0,g=new EH({limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:`ls`});for(let e=0;e0&&p&&!p.endsWith(` + +`)&&(p=kH(t,p,` +`)),d){let e=t.fs.resolvePath(t.cwd,n);try{let r=await t.fs.stat(e);if(a){let i=r.isDirectory?`drwxr-xr-x`:`-rw-r--r--`,a=u?NH(await t.fs.lstat(e)):r.isDirectory?`/`:``,s=r.size??0,c=o?jH(s).padStart(5):String(s).padStart(5),l=MH(r.mtime??new Date(0));p=kH(t,p,`${i} 1 user user ${c} ${l} ${n}${a} +`)}else{let r=u?NH(await t.fs.lstat(e)):``;p=kH(t,p,`${n}${r} +`)}}catch{m=kH(t,m,`ls: cannot access '${n}': No such file or directory +`),h=2}continue}if(n.includes(`*`)||n.includes(`?`)||n.includes(`[`)){let e=await PH(n,t,r,i,a,c,o,l,u,g);p=kH(t,p,e.stdout),m=kH(t,m,e.stderr),e.exitCode!==0&&(h=e.exitCode)}else{let e=await FH(n,t,r,i,a,s,f.length>1,c,o,l,u,!1,g,0,new Set);p=kH(t,p,e.stdout),m=kH(t,m,e.stderr),e.exitCode!==0&&(h=e.exitCode)}}return{stdout:p,stderr:m,exitCode:h}}},zH={name:`ls`,flags:[{flag:`-a`,type:`boolean`},{flag:`-A`,type:`boolean`},{flag:`-l`,type:`boolean`},{flag:`-h`,type:`boolean`},{flag:`-R`,type:`boolean`},{flag:`-r`,type:`boolean`},{flag:`-S`,type:`boolean`},{flag:`-F`,type:`boolean`},{flag:`-d`,type:`boolean`},{flag:`-t`,type:`boolean`},{flag:`-1`,type:`boolean`}],needsFiles:!0}}),VH={};wz(VH,{flagsForFuzzing:()=>WH,mkdirCommand:()=>UH});var HH,UH,WH,GH=B(()=>{vH(),TV(),lV(),HH={recursive:{short:`p`,long:`parents`,type:`boolean`},verbose:{short:`v`,long:`verbose`,type:`boolean`}},UH={name:`mkdir`,async execute(e,t){let n=cV(`mkdir`,e,HH);if(!n.ok)return n.error;let r=n.result.flags.recursive,i=n.result.flags.verbose,a=n.result.positional;if(a.length===0)return{stdout:``,stderr:`mkdir: missing operand +`,exitCode:1};let o=``,s=``,c=0;for(let e of a)try{let n=t.fs.resolvePath(t.cwd,e);await t.fs.mkdir(n,{recursive:r}),i&&(o+=`mkdir: created directory '${e}' +`)}catch(t){let n=wV(t);n.includes(`ENOENT`)||n.includes(`no such file`)?s+=`mkdir: cannot create directory '${e}': No such file or directory +`:n.includes(`EEXIST`)||n.includes(`already exists`)?s+=`mkdir: cannot create directory '${e}': File exists +`:s+=`mkdir: cannot create directory '${e}': ${_H(n)} +`,c=1}return{stdout:o,stderr:s,exitCode:c}}},WH={name:`mkdir`,flags:[{flag:`-p`,type:`boolean`},{flag:`-v`,type:`boolean`}],needsArgs:!0}}),KH={};wz(KH,{flagsForFuzzing:()=>$H,rmdirCommand:()=>QH});async function qH(e,t,n,r,i){let a=``,o=``,s=e.fs.resolvePath(e.cwd,t),c=await JH(e,s,t,r);if(a+=c.stdout,o+=c.stderr,c.exitCode!==0)return{stdout:a,stderr:o,exitCode:c.exitCode};if(n){let n=s,o=t;for(;;){i.visit(0);let t=YH(n),s=YH(o);if(t===n||t===`/`||t===`.`||s===`.`||s===``)break;let c=await JH(e,t,s,r);if(a+=c.stdout,c.exitCode!==0)break;n=t,o=s}}return{stdout:a,stderr:o,exitCode:0}}async function JH(e,t,n,r){try{if(!await e.fs.exists(t))return{stdout:``,stderr:`rmdir: failed to remove '${n}': No such file or directory +`,exitCode:1};if(!(await e.fs.stat(t)).isDirectory)return{stdout:``,stderr:`rmdir: failed to remove '${n}': Not a directory +`,exitCode:1};if((await e.fs.readdir(t)).length>0)return{stdout:``,stderr:`rmdir: failed to remove '${n}': Directory not empty +`,exitCode:1};await e.fs.rm(t,{recursive:!1,force:!1});let i=``;return r&&(i=`rmdir: removing directory, '${n}' +`),{stdout:i,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`rmdir: failed to remove '${n}': ${wV(e)} +`,exitCode:1}}}function YH(e){let t=e.replace(/\/+$/,``),n=t.lastIndexOf(`/`);return n===-1?`.`:n===0?`/`:t.substring(0,n)}var XH,ZH,QH,$H,eU=B(()=>{DH(),TV(),lV(),XH=`Usage: rmdir [-pv] DIRECTORY... +Remove empty directories. + +Options: + -p, --parents Remove DIRECTORY and its ancestors + -v, --verbose Output a diagnostic for every directory processed`,ZH={parents:{short:`p`,long:`parents`,type:`boolean`},verbose:{short:`v`,long:`verbose`,type:`boolean`},help:{long:`help`,type:`boolean`}},QH={name:`rmdir`,async execute(e,t){let n=cV(`rmdir`,e,ZH);if(!n.ok)return n.error;if(n.result.flags.help)return{stdout:`${XH} +`,stderr:``,exitCode:0};let r=n.result.flags.parents,i=n.result.flags.verbose,a=n.result.positional;if(a.length===0)return{stdout:``,stderr:`rmdir: missing operand +`,exitCode:1};let o=``,s=``,c=0,l=new EH({limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:`rmdir`,label:`parent traversal`});for(let e of a){let n=await qH(t,e,r,i,l);o+=n.stdout,s+=n.stderr,n.exitCode!==0&&(c=n.exitCode)}return{stdout:o,stderr:s,exitCode:c}}},$H={name:`rmdir`,flags:[{flag:`-p`,type:`boolean`},{flag:`-v`,type:`boolean`}],needsArgs:!0}}),tU={};wz(tU,{flagsForFuzzing:()=>iU,touchCommand:()=>rU});function nU(e){let t=e.replace(/\//g,`-`),n=new Date(t);if(!Number.isNaN(n.getTime()))return n;let r=t.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(r){let[,e,t,i]=r;if(n=new Date(Number.parseInt(e,10),Number.parseInt(t,10)-1,Number.parseInt(i,10)),!Number.isNaN(n.getTime()))return n}let i=t.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/);if(i){let[,e,t,r,a,o,s]=i;if(n=new Date(Number.parseInt(e,10),Number.parseInt(t,10)-1,Number.parseInt(r,10),Number.parseInt(a,10),Number.parseInt(o,10),Number.parseInt(s,10)),!Number.isNaN(n.getTime()))return n}return null}var rU,iU,aU=B(()=>{TV(),sV(),rU={name:`touch`,async execute(e,t){let n=[],r=null,i=!1;for(let t=0;t=e.length)return{stdout:``,stderr:`touch: option requires an argument -- 'd' +`,exitCode:1};r=e[++t]}else if(a.startsWith(`--date=`))r=a.slice(7);else if(a===`-c`||a===`--no-create`)i=!0;else if(a===`-a`||a===`-m`||a===`-r`||a===`-t`)(a===`-r`||a===`-t`)&&t++;else{if(a.startsWith(`--`))return oV(`touch`,a);if(a.startsWith(`-`)&&a.length>1){let n=!1;for(let o of a.slice(1))if(o===`c`)i=!0;else if(o!==`a`&&o!==`m`){if(o===`d`){if(t+1>=e.length)return{stdout:``,stderr:`touch: option requires an argument -- 'd' +`,exitCode:1};r=e[++t],n=!0;break}if(o===`r`||o===`t`){t++,n=!0;break}return oV(`touch`,`-${o}`)}if(n)continue}else n.push(a)}}if(n.length===0)return{stdout:``,stderr:`touch: missing file operand +`,exitCode:1};let a=null;if(r!==null&&(a=nU(r),a===null))return{stdout:``,stderr:`touch: invalid date format '${r}' +`,exitCode:1};let o=``,s=0;for(let e of n)try{let n=t.fs.resolvePath(t.cwd,e);if(!await t.fs.exists(n)){if(i)continue;await t.fs.writeFile(n,``)}let r=a??new Date;await t.fs.utimes(n,r,r)}catch(t){o+=`touch: cannot touch '${e}': ${wV(t)} +`,s=1}return{stdout:``,stderr:o,exitCode:s}}},iU={name:`touch`,flags:[{flag:`-c`,type:`boolean`},{flag:`-a`,type:`boolean`},{flag:`-m`,type:`boolean`},{flag:`-d`,type:`value`,valueHint:`string`}],needsArgs:!0}}),oU={};wz(oU,{flagsForFuzzing:()=>lU,rmCommand:()=>cU});var sU,cU,lU,uU=B(()=>{vH(),TV(),lV(),sU={recursive:{short:`r`,long:`recursive`,type:`boolean`},recursiveUpper:{short:`R`,type:`boolean`},force:{short:`f`,long:`force`,type:`boolean`},verbose:{short:`v`,long:`verbose`,type:`boolean`}},cU={name:`rm`,async execute(e,t){let n=cV(`rm`,e,sU);if(!n.ok)return n.error;let r=n.result.flags.recursive||n.result.flags.recursiveUpper,i=n.result.flags.force,a=n.result.flags.verbose,o=n.result.positional;if(o.length===0)return i?{stdout:``,stderr:``,exitCode:0}:{stdout:``,stderr:`rm: missing operand +`,exitCode:1};let s=``,c=``,l=0;for(let e of o)try{let n=t.fs.resolvePath(t.cwd,e);if((await t.fs.stat(n)).isDirectory&&!r){c+=`rm: cannot remove '${e}': Is a directory +`,l=1;continue}await t.fs.rm(n,{recursive:r,force:i}),a&&(s+=`removed '${e}' +`)}catch(t){if(!i){let n=wV(t);n.includes(`ENOENT`)||n.includes(`no such file`)?c+=`rm: cannot remove '${e}': No such file or directory +`:n.includes(`ENOTEMPTY`)||n.includes(`not empty`)?c+=`rm: cannot remove '${e}': Directory not empty +`:c+=`rm: cannot remove '${e}': ${_H(n)} +`,l=1}}return{stdout:s,stderr:c,exitCode:l}}},lU={name:`rm`,flags:[{flag:`-r`,type:`boolean`},{flag:`-R`,type:`boolean`},{flag:`-f`,type:`boolean`},{flag:`-v`,type:`boolean`}],needsArgs:!0}}),dU={};wz(dU,{cpCommand:()=>mU,flagsForFuzzing:()=>hU});var fU,pU,mU,hU,gU=B(()=>{hH(),DH(),U(),TV(),lV(),sV(),fU={name:`cp`,summary:`copy files and directories`,usage:`cp [OPTION]... SOURCE... DEST`,options:[`-r, -R, --recursive copy directories recursively`,`-n, --no-clobber do not overwrite an existing file`,`-p, --preserve preserve file attributes`,`-v, --verbose explain what is being done`,` --help display this help and exit`]},pU={recursive:{short:`r`,long:`recursive`,type:`boolean`},recursiveUpper:{short:`R`,type:`boolean`},noClobber:{short:`n`,long:`no-clobber`,type:`boolean`},preserve:{short:`p`,long:`preserve`,type:`boolean`},verbose:{short:`v`,long:`verbose`,type:`boolean`}},mU={name:`cp`,async execute(e,t){if(aV(e))return iV(fU);let n=cV(`cp`,e,pU);if(!n.ok)return n.error;let r=n.result.flags.recursive||n.result.flags.recursiveUpper,i=n.result.flags.noClobber;n.result.flags.preserve;let a=n.result.flags.verbose,o=n.result.positional;if(o.length<2)return{stdout:``,stderr:`cp: missing destination file operand +`,exitCode:1};let s=o.pop()??``,c=o,l=t.fs.resolvePath(t.cwd,s),u=``,d=``,f=0,p=new EH({limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:`cp`}),m=!1;try{m=(await t.fs.stat(l)).isDirectory}catch{}if(c.length>1&&!m)return{stdout:``,stderr:`cp: target '${s}' is not a directory +`,exitCode:1};for(let e of c)try{let n=t.fs.resolvePath(t.cwd,e),o=await t.fs.stat(n),s=l;if(m){let t=e.split(`/`).pop()||e;s=l===`/`?`/${t}`:`${l}/${t}`}if(o.isDirectory&&!r){d+=`cp: -r not specified; omitting directory '${e}' +`,f=1;continue}if(o.isDirectory){let r=await CH(t.fs,n,s,p);if(lH(n,s)||r===`inside`){d+=`cp: cannot copy '${e}' into itself, '${s}' +`,f=1;continue}if(r===`unknown`){d+=`cp: cannot safely determine whether '${s}' is inside '${e}' +`,f=1;continue}}if(i)try{await t.fs.stat(s);continue}catch{}let c=await SH(t.fs,n,s);if(c===`same`){d+=`cp: '${e}' and '${s}' are the same file +`,f=1;continue}if(c===`unknown`){d+=`cp: cannot safely determine whether '${e}' and '${s}' are the same file +`,f=1;continue}o.isDirectory&&await wH({fs:t.fs,root:n,limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:`cp`,symlinks:`never`,budget:p},()=>{}),await t.fs.cp(n,s,{recursive:r}),a&&(u+=`'${e}' -> '${s}' +`)}catch(t){if(t instanceof H||t instanceof HB)throw t;let n=wV(t);n.includes(`ENOENT`)||n.includes(`no such file`)?d+=`cp: cannot stat '${e}': No such file or directory +`:d+=`cp: cannot copy '${e}': ${n} +`,f=1}return{stdout:u,stderr:d,exitCode:f}}},hU={name:`cp`,flags:[{flag:`-r`,type:`boolean`},{flag:`-R`,type:`boolean`},{flag:`-n`,type:`boolean`},{flag:`-p`,type:`boolean`},{flag:`-v`,type:`boolean`}],needsArgs:!0,minArgs:2}}),_U={};wz(_U,{flagsForFuzzing:()=>xU,mvCommand:()=>bU});var vU,yU,bU,xU,SU=B(()=>{hH(),DH(),U(),TV(),lV(),sV(),vU={name:`mv`,summary:`move (rename) files`,usage:`mv [OPTION]... SOURCE... DEST`,options:[`-f, --force do not prompt before overwriting`,`-n, --no-clobber do not overwrite an existing file`,`-v, --verbose explain what is being done`,` --help display this help and exit`]},yU={force:{short:`f`,long:`force`,type:`boolean`},noClobber:{short:`n`,long:`no-clobber`,type:`boolean`},verbose:{short:`v`,long:`verbose`,type:`boolean`}},bU={name:`mv`,async execute(e,t){if(aV(e))return iV(vU);let n=cV(`mv`,e,yU);if(!n.ok)return n.error;n.result.flags.force;let r=n.result.flags.noClobber,i=n.result.flags.verbose,a=n.result.positional;if(a.length<2)return{stdout:``,stderr:`mv: missing destination file operand +`,exitCode:1};let o=a.pop()??``,s=a,c=t.fs.resolvePath(t.cwd,o),l=``,u=``,d=0,f=new EH({limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:`mv`}),p=!1;try{p=(await t.fs.stat(c)).isDirectory}catch{}if(s.length>1&&!p)return{stdout:``,stderr:`mv: target '${o}' is not a directory +`,exitCode:1};for(let e of s)try{let n=t.fs.resolvePath(t.cwd,e),a=await t.fs.stat(n),s=c;if(p){let t=e.split(`/`).pop()||e;s=c===`/`?`/${t}`:`${c}/${t}`}if(a.isDirectory){let r=await CH(t.fs,n,s,f);if(lH(n,s)||r===`inside`){u+=`mv: cannot move '${e}' into itself, '${s}' +`,d=1;continue}if(r===`unknown`){u+=`mv: cannot safely determine whether '${s}' is inside '${e}' +`,d=1;continue}}if(r)try{await t.fs.stat(s);continue}catch{}let m=await SH(t.fs,n,s);if(m===`same`)continue;if(m===`unknown`){u+=`mv: cannot safely determine whether '${e}' and '${s}' are the same file +`,d=1;continue}if(a.isDirectory&&await wH({fs:t.fs,root:n,limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:`mv`,symlinks:`never`,budget:f},()=>{}),await t.fs.mv(n,s),i){let t=p?`${o}/${e.split(`/`).pop()||e}`:o;l+=`renamed '${e}' -> '${t}' +`}}catch(t){if(t instanceof H||t instanceof HB)throw t;let n=wV(t);n.includes(`ENOENT`)||n.includes(`no such file`)?u+=`mv: cannot stat '${e}': No such file or directory +`:u+=`mv: cannot move '${e}': ${n} +`,d=1}return{stdout:l,stderr:u,exitCode:d}}},xU={name:`mv`,flags:[{flag:`-f`,type:`boolean`},{flag:`-n`,type:`boolean`},{flag:`-v`,type:`boolean`}],needsArgs:!0,minArgs:2}}),CU={};wz(CU,{flagsForFuzzing:()=>EU,lnCommand:()=>TU});var wU,TU,EU,Bbe=B(()=>{vH(),sV(),wU={name:`ln`,summary:`make links between files`,usage:`ln [OPTIONS] TARGET LINK_NAME`,options:[`-s create a symbolic link instead of a hard link`,`-f remove existing destination files`,`-n treat LINK_NAME as a normal file if it is a symbolic link to a directory`,`-v print name of each linked file`,` --help display this help and exit`]},TU={name:`ln`,async execute(e,t){if(aV(e))return iV(wU);let n=!1,r=!1,i=!1,a=0;for(;a2)return{stdout:``,stderr:`ln: extra operand '${o[2]}' +`,exitCode:1};let s=o[0],c=o[1],l=t.fs.resolvePath(t.cwd,c);if(await t.fs.exists(l)){if(r)try{await t.fs.rm(l,{force:!0})}catch{return{stdout:``,stderr:`ln: cannot remove '${c}': Permission denied +`,exitCode:1}}else return{stdout:``,stderr:`ln: failed to create ${n?`symbolic `:``}link '${c}': File exists +`,exitCode:1}}try{if(n)await t.fs.symlink(s,l);else{let e=t.fs.resolvePath(t.cwd,s);if(!await t.fs.exists(e))return{stdout:``,stderr:`ln: failed to access '${s}': No such file or directory +`,exitCode:1};await t.fs.link(e,l)}}catch(e){let t=e;return t.message.includes(`EPERM`)?{stdout:``,stderr:`ln: '${s}': hard link not allowed for directory +`,exitCode:1}:{stdout:``,stderr:`ln: ${_H(t.message)} +`,exitCode:1}}let u=``;return i&&(u=`'${c}' -> '${s}' +`),{stdout:u,stderr:``,exitCode:0}}},EU={name:`ln`,flags:[{flag:`-s`,type:`boolean`},{flag:`-f`,type:`boolean`},{flag:`-n`,type:`boolean`},{flag:`-v`,type:`boolean`}],needsArgs:!0,minArgs:2}}),DU={};wz(DU,{chmodCommand:()=>AU,flagsForFuzzing:()=>jU});async function Vbe(e,t,n,r,i,a){let o=new EH({limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:`chmod`});await wH({fs:e.fs,root:t,symlinks:`never`,budget:o,limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:`chmod`},async t=>{if(t.depth===0||t.phase!==`enter`)return;let o=n===void 0?r===void 0?420:OU(r,t.stat.mode):n;await e.fs.chmod(t.path,o),i&&a.append(`mode of '${t.path}' changed to ${o.toString(8).padStart(4,`0`)} +`)})}function OU(e,t=420){if(/^[0-7]+$/.test(e))return parseInt(e,8);let n=t&4095,r=e.split(`,`);for(let t of r){let r=t.match(/^([ugoa]*)([+\-=])([rwxXst]*)$/);if(!r)throw Error(`Invalid mode: ${e}`);let i=r[1]||`a`,a=r[2],o=r[3];(i===`a`||i===``)&&(i=`ugo`);let s=0;o.includes(`r`)&&(s|=4),o.includes(`w`)&&(s|=2),(o.includes(`x`)||o.includes(`X`))&&(s|=1);let c=0;o.includes(`s`)&&(i.includes(`u`)&&(c|=2048),i.includes(`g`)&&(c|=1024)),o.includes(`t`)&&(c|=512);for(let e of i){let t=0;e===`u`?t=6:e===`g`?t=3:e===`o`&&(t=0);let r=s<{sH(),rV(),DH(),sV(),kU={name:`chmod`,summary:`change file mode bits`,usage:`chmod [OPTIONS] MODE FILE...`,options:[`-R change files recursively`,`-v output a diagnostic for every file processed`,` --help display this help and exit`]},AU={name:`chmod`,async execute(e,t){if(aV(e))return iV(kU);if(e.length<2)return{stdout:``,stderr:`chmod: missing operand +`,exitCode:1};let n=!1,r=!1,i=0;for(;iPU,pwdCommand:()=>NU});var NU,PU,Ube=B(()=>{NU={name:`pwd`,async execute(e,t){let n=!1;for(let t of e)if(t===`-P`)n=!0;else if(t===`-L`)n=!1;else{if(t===`--`)break;t.startsWith(`-`)}let r=t.cwd;if(n)try{r=await t.fs.realpath(t.cwd)}catch{}return{stdout:`${r} +`,stderr:``,exitCode:0}}},PU={name:`pwd`,flags:[{flag:`-P`,type:`boolean`},{flag:`-L`,type:`boolean`}]}}),FU={};wz(FU,{flagsForFuzzing:()=>RU,readlinkCommand:()=>LU});var IU,LU,RU,Wbe=B(()=>{DH(),U(),sV(),IU={name:`readlink`,summary:`print resolved symbolic links or canonical file names`,usage:`readlink [OPTIONS] FILE...`,options:[`-f canonicalize by following every symlink in every component of the given name recursively`,` --help display this help and exit`]},LU={name:`readlink`,async execute(e,t){if(aV(e))return iV(IU);let n=!1,r=0;for(;re.limits.maxArrayElements)throw new H(`${n}: file operand limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);if(o.length===0)return{stdout:r(e.stdin),stderr:``,exitCode:0,stdoutEncoding:`binary`};let s=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),c=new oH(s,n),l=new oH(s,n),u=0,d=0,f=a||!i&&o.length>1,p=0;for(let t=0;te.limits.maxInputBytes-d)throw new H(`${n}: aggregate input size limit exceeded (${e.limits.maxInputBytes} bytes)`,`string_length`);let a=await xB(e.fs,t);if(a.length>e.limits.maxInputBytes-d)throw new H(`${n}: aggregate input size limit exceeded (${e.limits.maxInputBytes} bytes)`,`string_length`);d+=a.length,e.executionScope?.consumeInput(a.length,n),f&&(p>0&&c.append(` +`),c.append(yB(`==> ${i} <== +`))),c.append(r(a)),p++}catch(e){nV(e),l.append(`${n}: ${i}: No such file or directory +`),u=1}}return{stdout:c.build(),stderr:l.build(),exitCode:u,stdoutEncoding:`binary`}}function Gbe(e,t,n){if(n!==null)return e.slice(0,n);if(t===0)return``;let r=0,i=0,a=e.length;for(;r0?e.slice(0,r):``}function Kbe(e,t,n,r){if(n!==null)return n===0?``:e.slice(-n);let i=e.length;if(i===0)return``;if(r){let n=0,r=1;for(;n=0&&o{sH(),kB(),rV(),U(),sV()}),HU={};wz(HU,{flagsForFuzzing:()=>GU,headCommand:()=>WU});var UU,WU,GU,qbe=B(()=>{sV(),VU(),UU={name:`head`,summary:`output the first part of files`,usage:`head [OPTION]... [FILE]...`,options:[`-c, --bytes=NUM print the first NUM bytes`,`-n, --lines=NUM print the first NUM lines (default 10)`,`-q, --quiet never print headers giving file names`,`-v, --verbose always print headers giving file names`,` --help display this help and exit`]},WU={name:`head`,async execute(e,t){if(aV(e))return iV(UU);let n=zU(e,`head`);if(!n.ok)return n.error;let{lines:r,bytes:i}=n.options;return BU(t,n.options,`head`,e=>Gbe(e,r,i))}},GU={name:`head`,flags:[{flag:`-n`,type:`value`,valueHint:`number`},{flag:`-c`,type:`value`,valueHint:`number`},{flag:`-q`,type:`boolean`},{flag:`-v`,type:`boolean`}],stdinType:`text`,needsFiles:!0}}),KU={};wz(KU,{flagsForFuzzing:()=>YU,tailCommand:()=>JU});var qU,JU,YU,Jbe=B(()=>{VU(),sV(),qU={name:`tail`,summary:`output the last part of files`,usage:`tail [OPTION]... [FILE]...`,options:[`-c, --bytes=NUM print the last NUM bytes`,`-n, --lines=NUM print the last NUM lines (default 10)`,`-n +NUM print starting from line NUM`,`-q, --quiet never print headers giving file names`,`-v, --verbose always print headers giving file names`,` --help display this help and exit`]},JU={name:`tail`,async execute(e,t){if(aV(e))return iV(qU);let n=zU(e,`tail`);if(!n.ok)return n.error;let{lines:r,bytes:i,fromLine:a}=n.options;return BU(t,n.options,`tail`,e=>Kbe(e,r,i,a??!1))}},YU={name:`tail`,flags:[{flag:`-n`,type:`value`,valueHint:`number`},{flag:`-c`,type:`value`,valueHint:`number`},{flag:`-q`,type:`boolean`},{flag:`-v`,type:`boolean`}],stdinType:`text`,needsFiles:!0}}),XU={};wz(XU,{flagsForFuzzing:()=>nW,wcCommand:()=>tW});function ZU(e,t){let n=e,r=n.length,i=t?Array.from(vB(e)).length:r,a=0,o=0,s=!1;for(let e=0;e{kB(),lV(),mV(),sV(),$U={name:`wc`,summary:`print newline, word, and byte counts for each file`,usage:`wc [OPTION]... [FILE]...`,options:[`-c, --bytes print the byte counts`,`-m, --chars print the character counts`,`-l, --lines print the newline counts`,`-w, --words print the word counts`,` --help display this help and exit`]},eW={lines:{short:`l`,long:`lines`,type:`boolean`},words:{short:`w`,long:`words`,type:`boolean`},bytes:{short:`c`,long:`bytes`,type:`boolean`},chars:{short:`m`,long:`chars`,type:`boolean`}},tW={name:`wc`,async execute(e,t){if(aV(e))return iV($U);let n=cV(`wc`,e,eW);if(!n.ok)return n.error;let{lines:r,words:i}=n.result.flags,a=n.result.flags.bytes,o=n.result.flags.chars,s=n.result.positional;!r&&!i&&!a&&!o&&(r=i=a=!0);let c=a||o,l=await fV(t,s,{cmdName:`wc`,stopOnError:!1});if(s.length===0)return{stdout:`${QU(ZU(l.files[0].content,o),r,i,c,``,0)} +`,stderr:``,exitCode:0};let u=[],d=0,f=0,p=0;for(let{filename:e,content:t}of l.files){let n=ZU(t,o);d+=n.lines,f+=n.words,p+=n.third,u.push({filename:e,stats:n})}let m=s.length>1?d:Math.max(...u.map(e=>e.stats.lines)),h=s.length>1?f:Math.max(...u.map(e=>e.stats.words)),g=s.length>1?p:Math.max(...u.map(e=>e.stats.third)),_=s.length>1?3:0;r&&(_=Math.max(_,String(m).length)),i&&(_=Math.max(_,String(h).length)),c&&(_=Math.max(_,String(g).length));let v=``;for(let{filename:e,stats:t}of u)v+=`${QU(t,r,i,c,e,_)} +`;return s.length>1&&(v+=`${QU({lines:d,words:f,third:p},r,i,c,`total`,_)} +`),{stdout:v,stderr:l.stderr,exitCode:l.exitCode}}},nW={name:`wc`,flags:[{flag:`-l`,type:`boolean`},{flag:`-w`,type:`boolean`},{flag:`-c`,type:`boolean`},{flag:`-m`,type:`boolean`}],stdinType:`text`,needsFiles:!0}});function rW(e,t){return(t?`d`:`-`)+[e&256?`r`:`-`,e&128?`w`:`-`,e&64?`x`:`-`,e&32?`r`:`-`,e&16?`w`:`-`,e&8?`x`:`-`,e&4?`r`:`-`,e&2?`w`:`-`,e&1?`x`:`-`].join(``)}var iW=B(()=>{}),aW={};wz(aW,{flagsForFuzzing:()=>lW,statCommand:()=>cW});var oW,sW,cW,lW,Xbe=B(()=>{kB(),rV(),U(),lV(),iW(),sV(),oW={name:`stat`,summary:`display file or file system status`,usage:`stat [OPTION]... FILE...`,options:[`-c FORMAT use the specified FORMAT instead of the default`,` --help display this help and exit`]},sW={format:{short:`c`,type:`string`}},cW={name:`stat`,async execute(e,t){if(aV(e))return iV(oW);let n=cV(`stat`,e,sW);if(!n.ok)return n.error;let r=n.result.flags.format??null,i=n.result.positional;if(i.length===0)return{stdout:``,stderr:`stat: missing operand +`,exitCode:1};let a=``,o=``,s=!1,c=0,l=Math.min(t.limits.maxOutputSize,t.limits.maxStringLength),u=e=>{let t=V(e);if(t>l-c)throw new H(`stat: output size limit exceeded (${l} bytes)`,`output_size`);a+=e,c+=t};for(let e of i){let n=t.fs.resolvePath(t.cwd,e);try{let i=await t.fs.stat(n);if(r){let t=i.mode.toString(8),n=rW(i.mode,i.isDirectory),a=new Map([[`%n`,e],[`%N`,`'${e}'`],[`%s`,String(i.size)],[`%F`,i.isDirectory?`directory`:`regular file`],[`%a`,t],[`%A`,n],[`%u`,`1000`],[`%U`,`user`],[`%g`,`1000`],[`%G`,`group`]]);u(`${r.replace(/%[nNsFaAuUgG]/g,e=>a.get(e)??e)} +`)}else{let t=i.mode.toString(8).padStart(4,`0`),n=rW(i.mode,i.isDirectory);u(` File: ${e} + Size: ${i.size} Blocks: ${Math.ceil(i.size/512)} +Access: (${t}/${n}) +Modify: ${i.mtime.toISOString()} +`)}}catch(t){nV(t),o+=`stat: cannot stat '${e}': No such file or directory +`,s=!0}}return{stdout:a,stderr:o,exitCode:+!!s}}},lW={name:`stat`,flags:[{flag:`-c`,type:`value`,valueHint:`format`},{flag:`-L`,type:`boolean`}],needsArgs:!0}}),W,G,K,uW,dW,fW,pW,mW,hW,gW,_W,vW,yW,bW,xW,SW,CW,wW,TW,EW,DW,OW,kW,AW,jW,MW,NW,PW,FW,q,IW,LW,RW,zW,BW,VW,HW,UW,WW,GW,KW,qW,JW,YW,XW,ZW,QW,$W,eG,tG,nG,rG,iG,aG,oG,sG,cG,lG,uG,dG,fG,pG,Zbe=B(()=>{W=class e{static FOLD_CASE=1;static LITERAL=2;static CLASS_NL=4;static DOT_NL=8;static ONE_LINE=16;static NON_GREEDY=32;static PERL_X=64;static UNICODE_GROUPS=128;static WAS_DOLLAR=256;static MATCH_NL=e.CLASS_NL|e.DOT_NL;static PERL=e.CLASS_NL|e.ONE_LINE|e.PERL_X|e.UNICODE_GROUPS;static POSIX=0;static UNANCHORED=0;static ANCHOR_START=1;static ANCHOR_BOTH=2},G=class{static CODES=new Map([[`\x07`,7],[`\b`,8],[` `,9],[` +`,10],[`\v`,11],[`\f`,12],[`\r`,13],[` `,32],[`"`,34],[`$`,36],[`&`,38],[`(`,40],[`)`,41],[`*`,42],[`+`,43],[`-`,45],[`.`,46],[`0`,48],[`1`,49],[`2`,50],[`3`,51],[`4`,52],[`5`,53],[`6`,54],[`7`,55],[`8`,56],[`9`,57],[`:`,58],[`<`,60],[`>`,62],[`?`,63],[`A`,65],[`B`,66],[`C`,67],[`F`,70],[`P`,80],[`Q`,81],[`U`,85],[`Z`,90],[`[`,91],[`\\`,92],[`]`,93],[`^`,94],[`_`,95],[`a`,97],[`b`,98],[`f`,102],[`i`,105],[`m`,109],[`n`,110],[`r`,114],[`s`,115],[`t`,116],[`v`,118],[`x`,120],[`z`,122],[`{`,123],[`|`,124],[`}`,125]]);static toUpperCase(e){let t=String.fromCodePoint(e).toUpperCase();if(t.length>1)return e;let n=String.fromCodePoint(t.codePointAt(0)).toLowerCase();return n.length>1||n.codePointAt(0)!==e?e:t.codePointAt(0)}static toLowerCase(e){let t=String.fromCodePoint(e).toLowerCase();if(t.length>1)return e;let n=String.fromCodePoint(t.codePointAt(0)).toUpperCase();return n.length>1||n.codePointAt(0)!==e?e:t.codePointAt(0)}},K=class{SIZE=3;constructor(e){this.data=e}getLo(e){return this.data[e*this.SIZE]}getHi(e){return this.data[e*this.SIZE+1]}getStride(e){return this.data[e*this.SIZE+2]}get(e){let t=e*this.SIZE;return[this.data[t],this.data[t+1],this.data[t+2]]}get length(){return this.data.length/this.SIZE}},uW=class e{static CASE_ORBIT=new Map([[75,107],[107,8490],[8490,75],[83,115],[115,383],[383,83],[181,924],[924,956],[956,181],[197,229],[229,8491],[8491,197],[452,453],[453,454],[454,452],[455,456],[456,457],[457,455],[458,459],[459,460],[460,458],[497,498],[498,499],[499,497],[837,921],[921,953],[953,8126],[8126,837],[914,946],[946,976],[976,914],[917,949],[949,1013],[1013,917],[920,952],[952,977],[977,1012],[1012,920],[922,954],[954,1008],[1008,922],[928,960],[960,982],[982,928],[929,961],[961,1009],[1009,929],[931,962],[962,963],[963,931],[934,966],[966,981],[981,934],[937,969],[969,8486],[8486,937],[1042,1074],[1074,7296],[7296,1042],[1044,1076],[1076,7297],[7297,1044],[1054,1086],[1086,7298],[7298,1054],[1057,1089],[1089,7299],[7299,1057],[1058,1090],[1090,7300],[7300,7301],[7301,1058],[1066,1098],[1098,7302],[7302,1066],[1122,1123],[1123,7303],[7303,1122],[7304,42570],[42570,42571],[42571,7304],[7776,7777],[7777,7835],[7835,7776],[223,7838],[7838,223],[8064,8072],[8072,8064],[8065,8073],[8073,8065],[8066,8074],[8074,8066],[8067,8075],[8075,8067],[8068,8076],[8076,8068],[8069,8077],[8077,8069],[8070,8078],[8078,8070],[8071,8079],[8079,8071],[8080,8088],[8088,8080],[8081,8089],[8089,8081],[8082,8090],[8090,8082],[8083,8091],[8091,8083],[8084,8092],[8092,8084],[8085,8093],[8093,8085],[8086,8094],[8094,8086],[8087,8095],[8095,8087],[8096,8104],[8104,8096],[8097,8105],[8105,8097],[8098,8106],[8106,8098],[8099,8107],[8107,8099],[8100,8108],[8108,8100],[8101,8109],[8109,8101],[8102,8110],[8110,8102],[8103,8111],[8111,8103],[8115,8124],[8124,8115],[8131,8140],[8140,8131],[912,8147],[8147,912],[944,8163],[8163,944],[8179,8188],[8188,8179],[64261,64262],[64262,64261],[66560,66600],[66600,66560],[66561,66601],[66601,66561],[66562,66602],[66602,66562],[66563,66603],[66603,66563],[66564,66604],[66604,66564],[66565,66605],[66605,66565],[66566,66606],[66606,66566],[66567,66607],[66607,66567],[66568,66608],[66608,66568],[66569,66609],[66609,66569],[66570,66610],[66610,66570],[66571,66611],[66611,66571],[66572,66612],[66612,66572],[66573,66613],[66613,66573],[66574,66614],[66614,66574],[66575,66615],[66615,66575],[66576,66616],[66616,66576],[66577,66617],[66617,66577],[66578,66618],[66618,66578],[66579,66619],[66619,66579],[66580,66620],[66620,66580],[66581,66621],[66621,66581],[66582,66622],[66622,66582],[66583,66623],[66623,66583],[66584,66624],[66624,66584],[66585,66625],[66625,66585],[66586,66626],[66626,66586],[66587,66627],[66627,66587],[66588,66628],[66628,66588],[66589,66629],[66629,66589],[66590,66630],[66630,66590],[66591,66631],[66631,66591],[66592,66632],[66632,66592],[66593,66633],[66633,66593],[66594,66634],[66634,66594],[66595,66635],[66635,66595],[66596,66636],[66636,66596],[66597,66637],[66637,66597],[66598,66638],[66638,66598],[66599,66639],[66639,66599],[66736,66776],[66776,66736],[66737,66777],[66777,66737],[66738,66778],[66778,66738],[66739,66779],[66779,66739],[66740,66780],[66780,66740],[66741,66781],[66781,66741],[66742,66782],[66782,66742],[66743,66783],[66783,66743],[66744,66784],[66784,66744],[66745,66785],[66785,66745],[66746,66786],[66786,66746],[66747,66787],[66787,66747],[66748,66788],[66788,66748],[66749,66789],[66789,66749],[66750,66790],[66790,66750],[66751,66791],[66791,66751],[66752,66792],[66792,66752],[66753,66793],[66793,66753],[66754,66794],[66794,66754],[66755,66795],[66795,66755],[66756,66796],[66796,66756],[66757,66797],[66797,66757],[66758,66798],[66798,66758],[66759,66799],[66799,66759],[66760,66800],[66800,66760],[66761,66801],[66801,66761],[66762,66802],[66802,66762],[66763,66803],[66803,66763],[66764,66804],[66804,66764],[66765,66805],[66805,66765],[66766,66806],[66806,66766],[66767,66807],[66807,66767],[66768,66808],[66808,66768],[66769,66809],[66809,66769],[66770,66810],[66810,66770],[66771,66811],[66811,66771],[66928,66967],[66967,66928],[66929,66968],[66968,66929],[66930,66969],[66969,66930],[66931,66970],[66970,66931],[66932,66971],[66971,66932],[66933,66972],[66972,66933],[66934,66973],[66973,66934],[66935,66974],[66974,66935],[66936,66975],[66975,66936],[66937,66976],[66976,66937],[66938,66977],[66977,66938],[66940,66979],[66979,66940],[66941,66980],[66980,66941],[66942,66981],[66981,66942],[66943,66982],[66982,66943],[66944,66983],[66983,66944],[66945,66984],[66984,66945],[66946,66985],[66985,66946],[66947,66986],[66986,66947],[66948,66987],[66987,66948],[66949,66988],[66988,66949],[66950,66989],[66989,66950],[66951,66990],[66990,66951],[66952,66991],[66991,66952],[66953,66992],[66992,66953],[66954,66993],[66993,66954],[66956,66995],[66995,66956],[66957,66996],[66996,66957],[66958,66997],[66997,66958],[66959,66998],[66998,66959],[66960,66999],[66999,66960],[66961,67e3],[67e3,66961],[66962,67001],[67001,66962],[66964,67003],[67003,66964],[66965,67004],[67004,66965],[68736,68800],[68800,68736],[68737,68801],[68801,68737],[68738,68802],[68802,68738],[68739,68803],[68803,68739],[68740,68804],[68804,68740],[68741,68805],[68805,68741],[68742,68806],[68806,68742],[68743,68807],[68807,68743],[68744,68808],[68808,68744],[68745,68809],[68809,68745],[68746,68810],[68810,68746],[68747,68811],[68811,68747],[68748,68812],[68812,68748],[68749,68813],[68813,68749],[68750,68814],[68814,68750],[68751,68815],[68815,68751],[68752,68816],[68816,68752],[68753,68817],[68817,68753],[68754,68818],[68818,68754],[68755,68819],[68819,68755],[68756,68820],[68820,68756],[68757,68821],[68821,68757],[68758,68822],[68822,68758],[68759,68823],[68823,68759],[68760,68824],[68824,68760],[68761,68825],[68825,68761],[68762,68826],[68826,68762],[68763,68827],[68827,68763],[68764,68828],[68828,68764],[68765,68829],[68829,68765],[68766,68830],[68830,68766],[68767,68831],[68831,68767],[68768,68832],[68832,68768],[68769,68833],[68833,68769],[68770,68834],[68834,68770],[68771,68835],[68835,68771],[68772,68836],[68836,68772],[68773,68837],[68837,68773],[68774,68838],[68838,68774],[68775,68839],[68839,68775],[68776,68840],[68840,68776],[68777,68841],[68841,68777],[68778,68842],[68842,68778],[68779,68843],[68843,68779],[68780,68844],[68844,68780],[68781,68845],[68845,68781],[68782,68846],[68846,68782],[68783,68847],[68847,68783],[68784,68848],[68848,68784],[68785,68849],[68849,68785],[68786,68850],[68850,68786],[68944,68976],[68976,68944],[68945,68977],[68977,68945],[68946,68978],[68978,68946],[68947,68979],[68979,68947],[68948,68980],[68980,68948],[68949,68981],[68981,68949],[68950,68982],[68982,68950],[68951,68983],[68983,68951],[68952,68984],[68984,68952],[68953,68985],[68985,68953],[68954,68986],[68986,68954],[68955,68987],[68987,68955],[68956,68988],[68988,68956],[68957,68989],[68989,68957],[68958,68990],[68990,68958],[68959,68991],[68991,68959],[68960,68992],[68992,68960],[68961,68993],[68993,68961],[68962,68994],[68994,68962],[68963,68995],[68995,68963],[68964,68996],[68996,68964],[68965,68997],[68997,68965],[71840,71872],[71872,71840],[71841,71873],[71873,71841],[71842,71874],[71874,71842],[71843,71875],[71875,71843],[71844,71876],[71876,71844],[71845,71877],[71877,71845],[71846,71878],[71878,71846],[71847,71879],[71879,71847],[71848,71880],[71880,71848],[71849,71881],[71881,71849],[71850,71882],[71882,71850],[71851,71883],[71883,71851],[71852,71884],[71884,71852],[71853,71885],[71885,71853],[71854,71886],[71886,71854],[71855,71887],[71887,71855],[71856,71888],[71888,71856],[71857,71889],[71889,71857],[71858,71890],[71890,71858],[71859,71891],[71891,71859],[71860,71892],[71892,71860],[71861,71893],[71893,71861],[71862,71894],[71894,71862],[71863,71895],[71895,71863],[71864,71896],[71896,71864],[71865,71897],[71897,71865],[71866,71898],[71898,71866],[71867,71899],[71899,71867],[71868,71900],[71900,71868],[71869,71901],[71901,71869],[71870,71902],[71902,71870],[71871,71903],[71903,71871],[93760,93792],[93792,93760],[93761,93793],[93793,93761],[93762,93794],[93794,93762],[93763,93795],[93795,93763],[93764,93796],[93796,93764],[93765,93797],[93797,93765],[93766,93798],[93798,93766],[93767,93799],[93799,93767],[93768,93800],[93800,93768],[93769,93801],[93801,93769],[93770,93802],[93802,93770],[93771,93803],[93803,93771],[93772,93804],[93804,93772],[93773,93805],[93805,93773],[93774,93806],[93806,93774],[93775,93807],[93807,93775],[93776,93808],[93808,93776],[93777,93809],[93809,93777],[93778,93810],[93810,93778],[93779,93811],[93811,93779],[93780,93812],[93812,93780],[93781,93813],[93813,93781],[93782,93814],[93814,93782],[93783,93815],[93815,93783],[93784,93816],[93816,93784],[93785,93817],[93817,93785],[93786,93818],[93818,93786],[93787,93819],[93819,93787],[93788,93820],[93820,93788],[93789,93821],[93821,93789],[93790,93822],[93822,93790],[93791,93823],[93823,93791],[125184,125218],[125218,125184],[125185,125219],[125219,125185],[125186,125220],[125220,125186],[125187,125221],[125221,125187],[125188,125222],[125222,125188],[125189,125223],[125223,125189],[125190,125224],[125224,125190],[125191,125225],[125225,125191],[125192,125226],[125226,125192],[125193,125227],[125227,125193],[125194,125228],[125228,125194],[125195,125229],[125229,125195],[125196,125230],[125230,125196],[125197,125231],[125231,125197],[125198,125232],[125232,125198],[125199,125233],[125233,125199],[125200,125234],[125234,125200],[125201,125235],[125235,125201],[125202,125236],[125236,125202],[125203,125237],[125237,125203],[125204,125238],[125238,125204],[125205,125239],[125239,125205],[125206,125240],[125240,125206],[125207,125241],[125241,125207],[125208,125242],[125242,125208],[125209,125243],[125243,125209],[125210,125244],[125244,125210],[125211,125245],[125245,125211],[125212,125246],[125246,125212],[125213,125247],[125247,125213],[125214,125248],[125248,125214],[125215,125249],[125249,125215],[125216,125250],[125250,125216],[125217,125251],[125251,125217]]);static C=new K(new Uint32Array([0,31,1,127,159,1,173,888,715,889,896,7,897,899,1,907,909,2,930,1328,398,1367,1368,1,1419,1420,1,1424,1480,56,1481,1487,1,1515,1518,1,1525,1541,1,1564,1757,193,1806,1807,1,1867,1868,1,1970,1983,1,2043,2044,1,2094,2095,1,2111,2140,29,2141,2143,2,2155,2159,1,2191,2198,1,2274,2436,162,2445,2446,1,2449,2450,1,2473,2481,8,2483,2485,1,2490,2491,1,2501,2502,1,2505,2506,1,2511,2518,1,2520,2523,1,2526,2532,6,2533,2559,26,2560,2564,4,2571,2574,1,2577,2578,1,2601,2609,8,2612,2618,3,2619,2621,2,2627,2630,1,2633,2634,1,2638,2640,1,2642,2648,1,2653,2655,2,2656,2661,1,2679,2688,1,2692,2702,10,2706,2729,23,2737,2740,3,2746,2747,1,2758,2766,4,2767,2769,2,2770,2783,1,2788,2789,1,2802,2808,1,2816,2820,4,2829,2830,1,2833,2834,1,2857,2865,8,2868,2874,6,2875,2885,10,2886,2889,3,2890,2894,4,2895,2900,1,2904,2907,1,2910,2916,6,2917,2936,19,2937,2945,1,2948,2955,7,2956,2957,1,2961,2966,5,2967,2968,1,2971,2973,2,2976,2978,1,2981,2983,1,2987,2989,1,3002,3005,1,3011,3013,1,3017,3022,5,3023,3025,2,3026,3030,1,3032,3045,1,3067,3071,1,3085,3089,4,3113,3130,17,3131,3141,10,3145,3150,5,3151,3156,1,3159,3163,4,3164,3166,2,3167,3172,5,3173,3184,11,3185,3190,1,3213,3217,4,3241,3252,11,3258,3259,1,3269,3273,4,3278,3284,1,3287,3292,1,3295,3300,5,3301,3312,11,3316,3327,1,3341,3345,4,3397,3401,4,3408,3411,1,3428,3429,1,3456,3460,4,3479,3481,1,3506,3516,10,3518,3519,1,3527,3529,1,3531,3534,1,3541,3543,2,3552,3557,1,3568,3569,1,3573,3584,1,3643,3646,1,3676,3712,1,3715,3717,2,3723,3748,25,3750,3774,24,3775,3781,6,3783,3791,8,3802,3803,1,3808,3839,1,3912,3949,37,3950,3952,1,3992,4029,37,4045,4059,14,4060,4095,1,4294,4296,2,4297,4300,1,4302,4303,1,4681,4686,5,4687,4695,8,4697,4702,5,4703,4745,42,4750,4751,1,4785,4790,5,4791,4799,8,4801,4806,5,4807,4823,16,4881,4886,5,4887,4955,68,4956,4989,33,4990,4991,1,5018,5023,1,5110,5111,1,5118,5119,1,5789,5791,1,5881,5887,1,5910,5918,1,5943,5951,1,5972,5983,1,5997,6001,4,6004,6015,1,6110,6111,1,6122,6127,1,6138,6143,1,6158,6170,12,6171,6175,1,6265,6271,1,6315,6319,1,6390,6399,1,6431,6444,13,6445,6447,1,6460,6463,1,6465,6467,1,6510,6511,1,6517,6527,1,6572,6575,1,6602,6607,1,6619,6621,1,6684,6685,1,6751,6781,30,6782,6794,12,6795,6799,1,6810,6815,1,6830,6831,1,6863,6911,1,6989,7156,167,7157,7163,1,7224,7226,1,7242,7244,1,7307,7311,1,7355,7356,1,7368,7375,1,7419,7423,1,7958,7959,1,7966,7967,1,8006,8007,1,8014,8015,1,8024,8030,2,8062,8063,1,8117,8133,16,8148,8149,1,8156,8176,20,8177,8181,4,8191,8203,12,8204,8207,1,8234,8238,1,8288,8303,1,8306,8307,1,8335,8349,14,8350,8351,1,8385,8399,1,8433,8447,1,8588,8591,1,9258,9279,1,9291,9311,1,11124,11125,1,11158,11508,350,11509,11512,1,11558,11560,2,11561,11564,1,11566,11567,1,11624,11630,1,11633,11646,1,11671,11679,1,11687,11743,8,11870,11903,1,11930,12020,90,12021,12031,1,12246,12271,1,12352,12439,87,12440,12544,104,12545,12548,1,12592,12687,95,12774,12782,1,12831,42125,29294,42126,42127,1,42183,42191,1,42540,42559,1,42744,42751,1,42958,42959,1,42962,42964,2,42973,42993,1,43053,43055,1,43066,43071,1,43128,43135,1,43206,43213,1,43226,43231,1,43348,43358,1,43389,43391,1,43470,43482,12,43483,43485,1,43519,43575,56,43576,43583,1,43598,43599,1,43610,43611,1,43715,43738,1,43767,43776,1,43783,43784,1,43791,43792,1,43799,43807,1,43815,43823,8,43884,43887,1,44014,44015,1,44026,44031,1,55204,55215,1,55239,55242,1,55292,63743,1,64110,64111,1,64218,64255,1,64263,64274,1,64280,64284,1,64311,64317,6,64319,64325,3,64451,64466,1,64912,64913,1,64968,64974,1,64976,65007,1,65050,65055,1,65107,65127,20,65132,65135,1,65141,65277,136,65278,65280,1,65471,65473,1,65480,65481,1,65488,65489,1,65496,65497,1,65501,65503,1,65511,65519,8,65520,65531,1,65534,65535,1,65548,65575,27,65595,65598,3,65614,65615,1,65630,65663,1,65787,65791,1,65795,65798,1,65844,65846,1,65935,65949,14,65950,65951,1,65953,65999,1,66046,66175,1,66205,66207,1,66257,66271,1,66300,66303,1,66340,66348,1,66379,66383,1,66427,66431,1,66462,66500,38,66501,66503,1,66518,66559,1,66718,66719,1,66730,66735,1,66772,66775,1,66812,66815,1,66856,66863,1,66916,66926,1,66939,66955,16,66963,66966,3,66978,66994,16,67002,67005,3,67006,67007,1,67060,67071,1,67383,67391,1,67414,67423,1,67432,67455,1,67462,67505,43,67515,67583,1,67590,67591,1,67593,67638,45,67641,67643,1,67645,67646,1,67670,67743,73,67744,67750,1,67760,67807,1,67827,67830,3,67831,67834,1,67868,67870,1,67898,67902,1,67904,67967,1,68024,68027,1,68048,68049,1,68100,68103,3,68104,68107,1,68116,68120,4,68150,68151,1,68155,68158,1,68169,68175,1,68185,68191,1,68256,68287,1,68327,68330,1,68343,68351,1,68406,68408,1,68438,68439,1,68467,68471,1,68498,68504,1,68509,68520,1,68528,68607,1,68681,68735,1,68787,68799,1,68851,68857,1,68904,68911,1,68922,68927,1,68966,68968,1,68998,69005,1,69008,69215,1,69247,69290,43,69294,69295,1,69298,69313,1,69317,69371,1,69416,69423,1,69466,69487,1,69514,69551,1,69580,69599,1,69623,69631,1,69710,69713,1,69750,69758,1,69821,69827,6,69828,69839,1,69865,69871,1,69882,69887,1,69941,69960,19,69961,69967,1,70007,70015,1,70112,70133,21,70134,70143,1,70162,70210,48,70211,70271,1,70279,70281,2,70286,70302,16,70314,70319,1,70379,70383,1,70394,70399,1,70404,70413,9,70414,70417,3,70418,70441,23,70449,70452,3,70458,70469,11,70470,70473,3,70474,70478,4,70479,70481,2,70482,70486,1,70488,70492,1,70500,70501,1,70509,70511,1,70517,70527,1,70538,70540,2,70541,70543,2,70582,70593,11,70595,70596,1,70598,70603,5,70614,70617,3,70618,70624,1,70627,70655,1,70748,70754,6,70755,70783,1,70856,70863,1,70874,71039,1,71094,71095,1,71134,71167,1,71237,71247,1,71258,71263,1,71277,71295,1,71354,71359,1,71370,71375,1,71396,71423,1,71451,71452,1,71468,71471,1,71495,71679,1,71740,71839,1,71923,71934,1,71943,71944,1,71946,71947,1,71956,71959,3,71990,71993,3,71994,72007,13,72008,72015,1,72026,72095,1,72104,72105,1,72152,72153,1,72165,72191,1,72264,72271,1,72355,72367,1,72441,72447,1,72458,72639,1,72674,72687,1,72698,72703,1,72713,72759,46,72774,72783,1,72813,72815,1,72848,72849,1,72872,72887,15,72888,72959,1,72967,72970,3,73015,73017,1,73019,73022,3,73032,73039,1,73050,73055,1,73062,73065,3,73103,73106,3,73113,73119,1,73130,73439,1,73465,73471,1,73489,73531,42,73532,73533,1,73563,73647,1,73649,73663,1,73714,73726,1,74650,74751,1,74863,74869,6,74870,74879,1,75076,77711,1,77811,77823,1,78896,78911,1,78934,78943,1,82939,82943,1,83527,90367,1,90426,92159,1,92729,92735,1,92767,92778,11,92779,92781,1,92863,92874,11,92875,92879,1,92910,92911,1,92918,92927,1,92998,93007,1,93018,93026,8,93048,93052,1,93072,93503,1,93562,93759,1,93851,93951,1,94027,94030,1,94088,94094,1,94112,94175,1,94181,94191,1,94194,94207,1,100344,100351,1,101590,101630,1,101641,110575,1,110580,110588,8,110591,110883,292,110884,110897,1,110899,110927,1,110931,110932,1,110934,110947,1,110952,110959,1,111356,113663,1,113771,113775,1,113789,113791,1,113801,113807,1,113818,113819,1,113824,117759,1,118010,118015,1,118452,118527,1,118574,118575,1,118599,118607,1,118724,118783,1,119030,119039,1,119079,119080,1,119155,119162,1,119275,119295,1,119366,119487,1,119508,119519,1,119540,119551,1,119639,119647,1,119673,119807,1,119893,119965,72,119968,119969,1,119971,119972,1,119975,119976,1,119981,119994,13,119996,120004,8,120070,120075,5,120076,120085,9,120093,120122,29,120127,120133,6,120135,120137,1,120145,120486,341,120487,120780,293,120781,121484,703,121485,121498,1,121504,121520,16,121521,122623,1,122655,122660,1,122667,122879,1,122887,122905,18,122906,122914,8,122917,122923,6,122924,122927,1,122990,123022,1,123024,123135,1,123181,123183,1,123198,123199,1,123210,123213,1,123216,123535,1,123567,123583,1,123642,123646,1,123648,124111,1,124154,124367,1,124411,124414,1,124416,124895,1,124903,124908,5,124911,124927,16,125125,125126,1,125143,125183,1,125260,125263,1,125274,125277,1,125280,126064,1,126133,126208,1,126270,126463,1,126468,126496,28,126499,126501,2,126502,126504,2,126515,126520,5,126522,126524,2,126525,126529,1,126531,126534,1,126536,126540,2,126544,126547,3,126549,126550,1,126552,126560,2,126563,126565,2,126566,126571,5,126579,126589,5,126591,126602,11,126620,126624,1,126628,126634,6,126652,126703,1,126706,126975,1,127020,127023,1,127124,127135,1,127151,127152,1,127168,127184,16,127222,127231,1,127406,127461,1,127491,127503,1,127548,127551,1,127561,127567,1,127570,127583,1,127590,127743,1,128728,128731,1,128749,128751,1,128765,128767,1,128887,128890,1,128986,128991,1,129004,129007,1,129009,129023,1,129036,129039,1,129096,129103,1,129114,129119,1,129160,129167,1,129198,129199,1,129212,129215,1,129218,129279,1,129620,129631,1,129646,129647,1,129661,129663,1,129674,129678,1,129735,129741,1,129757,129758,1,129770,129775,1,129785,129791,1,129939,130042,103,130043,131071,1,173792,173823,1,177978,177983,1,178206,178207,1,183970,183983,1,191457,191471,1,192094,194559,1,195102,196607,1,201547,201551,1,205744,917759,1,918e3,1114111,1]));static Cc=new K(new Uint32Array([0,31,1,127,159,1]));static Cf=new K(new Uint32Array([173,1536,1363,1537,1541,1,1564,1757,193,1807,2192,385,2193,2274,81,6158,8203,2045,8204,8207,1,8234,8238,1,8288,8292,1,8294,8303,1,65279,65529,250,65530,65531,1,69821,69837,16,78896,78911,1,113824,113827,1,119155,119162,1,917505,917536,31,917537,917631,1]));static Co=new K(new Uint32Array([57344,63743,1,983040,1048573,1,1048576,1114109,1]));static Cs=new K(new Uint32Array([55296,57343,1]));static L=new K(new Uint32Array([65,90,1,97,122,1,170,181,11,186,192,6,193,214,1,216,246,1,248,705,1,710,721,1,736,740,1,748,750,2,880,884,1,886,887,1,890,893,1,895,902,7,904,906,1,908,910,2,911,929,1,931,1013,1,1015,1153,1,1162,1327,1,1329,1366,1,1369,1376,7,1377,1416,1,1488,1514,1,1519,1522,1,1568,1610,1,1646,1647,1,1649,1747,1,1749,1765,16,1766,1774,8,1775,1786,11,1787,1788,1,1791,1808,17,1810,1839,1,1869,1957,1,1969,1994,25,1995,2026,1,2036,2037,1,2042,2048,6,2049,2069,1,2074,2084,10,2088,2112,24,2113,2136,1,2144,2154,1,2160,2183,1,2185,2190,1,2208,2249,1,2308,2361,1,2365,2384,19,2392,2401,1,2417,2432,1,2437,2444,1,2447,2448,1,2451,2472,1,2474,2480,1,2482,2486,4,2487,2489,1,2493,2510,17,2524,2525,1,2527,2529,1,2544,2545,1,2556,2565,9,2566,2570,1,2575,2576,1,2579,2600,1,2602,2608,1,2610,2611,1,2613,2614,1,2616,2617,1,2649,2652,1,2654,2674,20,2675,2676,1,2693,2701,1,2703,2705,1,2707,2728,1,2730,2736,1,2738,2739,1,2741,2745,1,2749,2768,19,2784,2785,1,2809,2821,12,2822,2828,1,2831,2832,1,2835,2856,1,2858,2864,1,2866,2867,1,2869,2873,1,2877,2908,31,2909,2911,2,2912,2913,1,2929,2947,18,2949,2954,1,2958,2960,1,2962,2965,1,2969,2970,1,2972,2974,2,2975,2979,4,2980,2984,4,2985,2986,1,2990,3001,1,3024,3077,53,3078,3084,1,3086,3088,1,3090,3112,1,3114,3129,1,3133,3160,27,3161,3162,1,3165,3168,3,3169,3200,31,3205,3212,1,3214,3216,1,3218,3240,1,3242,3251,1,3253,3257,1,3261,3293,32,3294,3296,2,3297,3313,16,3314,3332,18,3333,3340,1,3342,3344,1,3346,3386,1,3389,3406,17,3412,3414,1,3423,3425,1,3450,3455,1,3461,3478,1,3482,3505,1,3507,3515,1,3517,3520,3,3521,3526,1,3585,3632,1,3634,3635,1,3648,3654,1,3713,3714,1,3716,3718,2,3719,3722,1,3724,3747,1,3749,3751,2,3752,3760,1,3762,3763,1,3773,3776,3,3777,3780,1,3782,3804,22,3805,3807,1,3840,3904,64,3905,3911,1,3913,3948,1,3976,3980,1,4096,4138,1,4159,4176,17,4177,4181,1,4186,4189,1,4193,4197,4,4198,4206,8,4207,4208,1,4213,4225,1,4238,4256,18,4257,4293,1,4295,4301,6,4304,4346,1,4348,4680,1,4682,4685,1,4688,4694,1,4696,4698,2,4699,4701,1,4704,4744,1,4746,4749,1,4752,4784,1,4786,4789,1,4792,4798,1,4800,4802,2,4803,4805,1,4808,4822,1,4824,4880,1,4882,4885,1,4888,4954,1,4992,5007,1,5024,5109,1,5112,5117,1,5121,5740,1,5743,5759,1,5761,5786,1,5792,5866,1,5873,5880,1,5888,5905,1,5919,5937,1,5952,5969,1,5984,5996,1,5998,6e3,1,6016,6067,1,6103,6108,5,6176,6264,1,6272,6276,1,6279,6312,1,6314,6320,6,6321,6389,1,6400,6430,1,6480,6509,1,6512,6516,1,6528,6571,1,6576,6601,1,6656,6678,1,6688,6740,1,6823,6917,94,6918,6963,1,6981,6988,1,7043,7072,1,7086,7087,1,7098,7141,1,7168,7203,1,7245,7247,1,7258,7293,1,7296,7306,1,7312,7354,1,7357,7359,1,7401,7404,1,7406,7411,1,7413,7414,1,7418,7424,6,7425,7615,1,7680,7957,1,7960,7965,1,7968,8005,1,8008,8013,1,8016,8023,1,8025,8031,2,8032,8061,1,8064,8116,1,8118,8124,1,8126,8130,4,8131,8132,1,8134,8140,1,8144,8147,1,8150,8155,1,8160,8172,1,8178,8180,1,8182,8188,1,8305,8319,14,8336,8348,1,8450,8455,5,8458,8467,1,8469,8473,4,8474,8477,1,8484,8490,2,8491,8493,1,8495,8505,1,8508,8511,1,8517,8521,1,8526,8579,53,8580,11264,2684,11265,11492,1,11499,11502,1,11506,11507,1,11520,11557,1,11559,11565,6,11568,11623,1,11631,11648,17,11649,11670,1,11680,11686,1,11688,11694,1,11696,11702,1,11704,11710,1,11712,11718,1,11720,11726,1,11728,11734,1,11736,11742,1,11823,12293,470,12294,12337,43,12338,12341,1,12347,12348,1,12353,12438,1,12445,12447,1,12449,12538,1,12540,12543,1,12549,12591,1,12593,12686,1,12704,12735,1,12784,12799,1,13312,19903,1,19968,42124,1,42192,42237,1,42240,42508,1,42512,42527,1,42538,42539,1,42560,42606,1,42623,42653,1,42656,42725,1,42775,42783,1,42786,42888,1,42891,42957,1,42960,42961,1,42963,42965,2,42966,42972,1,42994,43009,1,43011,43013,1,43015,43018,1,43020,43042,1,43072,43123,1,43138,43187,1,43250,43255,1,43259,43261,2,43262,43274,12,43275,43301,1,43312,43334,1,43360,43388,1,43396,43442,1,43471,43488,17,43489,43492,1,43494,43503,1,43514,43518,1,43520,43560,1,43584,43586,1,43588,43595,1,43616,43638,1,43642,43646,4,43647,43695,1,43697,43701,4,43702,43705,3,43706,43709,1,43712,43714,2,43739,43741,1,43744,43754,1,43762,43764,1,43777,43782,1,43785,43790,1,43793,43798,1,43808,43814,1,43816,43822,1,43824,43866,1,43868,43881,1,43888,44002,1,44032,55203,1,55216,55238,1,55243,55291,1,63744,64109,1,64112,64217,1,64256,64262,1,64275,64279,1,64285,64287,2,64288,64296,1,64298,64310,1,64312,64316,1,64318,64320,2,64321,64323,2,64324,64326,2,64327,64433,1,64467,64829,1,64848,64911,1,64914,64967,1,65008,65019,1,65136,65140,1,65142,65276,1,65313,65338,1,65345,65370,1,65382,65470,1,65474,65479,1,65482,65487,1,65490,65495,1,65498,65500,1,65536,65547,1,65549,65574,1,65576,65594,1,65596,65597,1,65599,65613,1,65616,65629,1,65664,65786,1,66176,66204,1,66208,66256,1,66304,66335,1,66349,66368,1,66370,66377,1,66384,66421,1,66432,66461,1,66464,66499,1,66504,66511,1,66560,66717,1,66736,66771,1,66776,66811,1,66816,66855,1,66864,66915,1,66928,66938,1,66940,66954,1,66956,66962,1,66964,66965,1,66967,66977,1,66979,66993,1,66995,67001,1,67003,67004,1,67008,67059,1,67072,67382,1,67392,67413,1,67424,67431,1,67456,67461,1,67463,67504,1,67506,67514,1,67584,67589,1,67592,67594,2,67595,67637,1,67639,67640,1,67644,67647,3,67648,67669,1,67680,67702,1,67712,67742,1,67808,67826,1,67828,67829,1,67840,67861,1,67872,67897,1,67968,68023,1,68030,68031,1,68096,68112,16,68113,68115,1,68117,68119,1,68121,68149,1,68192,68220,1,68224,68252,1,68288,68295,1,68297,68324,1,68352,68405,1,68416,68437,1,68448,68466,1,68480,68497,1,68608,68680,1,68736,68786,1,68800,68850,1,68864,68899,1,68938,68965,1,68975,68997,1,69248,69289,1,69296,69297,1,69314,69316,1,69376,69404,1,69415,69424,9,69425,69445,1,69488,69505,1,69552,69572,1,69600,69622,1,69635,69687,1,69745,69746,1,69749,69763,14,69764,69807,1,69840,69864,1,69891,69926,1,69956,69959,3,69968,70002,1,70006,70019,13,70020,70066,1,70081,70084,1,70106,70108,2,70144,70161,1,70163,70187,1,70207,70208,1,70272,70278,1,70280,70282,2,70283,70285,1,70287,70301,1,70303,70312,1,70320,70366,1,70405,70412,1,70415,70416,1,70419,70440,1,70442,70448,1,70450,70451,1,70453,70457,1,70461,70480,19,70493,70497,1,70528,70537,1,70539,70542,3,70544,70581,1,70583,70609,26,70611,70656,45,70657,70708,1,70727,70730,1,70751,70753,1,70784,70831,1,70852,70853,1,70855,71040,185,71041,71086,1,71128,71131,1,71168,71215,1,71236,71296,60,71297,71338,1,71352,71424,72,71425,71450,1,71488,71494,1,71680,71723,1,71840,71903,1,71935,71942,1,71945,71948,3,71949,71955,1,71957,71958,1,71960,71983,1,71999,72001,2,72096,72103,1,72106,72144,1,72161,72163,2,72192,72203,11,72204,72242,1,72250,72272,22,72284,72329,1,72349,72368,19,72369,72440,1,72640,72672,1,72704,72712,1,72714,72750,1,72768,72818,50,72819,72847,1,72960,72966,1,72968,72969,1,72971,73008,1,73030,73056,26,73057,73061,1,73063,73064,1,73066,73097,1,73112,73440,328,73441,73458,1,73474,73476,2,73477,73488,1,73490,73523,1,73648,73728,80,73729,74649,1,74880,75075,1,77712,77808,1,77824,78895,1,78913,78918,1,78944,82938,1,82944,83526,1,90368,90397,1,92160,92728,1,92736,92766,1,92784,92862,1,92880,92909,1,92928,92975,1,92992,92995,1,93027,93047,1,93053,93071,1,93504,93548,1,93760,93823,1,93952,94026,1,94032,94099,67,94100,94111,1,94176,94177,1,94179,94208,29,94209,100343,1,100352,101589,1,101631,101640,1,110576,110579,1,110581,110587,1,110589,110590,1,110592,110882,1,110898,110928,30,110929,110930,1,110933,110948,15,110949,110951,1,110960,111355,1,113664,113770,1,113776,113788,1,113792,113800,1,113808,113817,1,119808,119892,1,119894,119964,1,119966,119967,1,119970,119973,3,119974,119977,3,119978,119980,1,119982,119993,1,119995,119997,2,119998,120003,1,120005,120069,1,120071,120074,1,120077,120084,1,120086,120092,1,120094,120121,1,120123,120126,1,120128,120132,1,120134,120138,4,120139,120144,1,120146,120485,1,120488,120512,1,120514,120538,1,120540,120570,1,120572,120596,1,120598,120628,1,120630,120654,1,120656,120686,1,120688,120712,1,120714,120744,1,120746,120770,1,120772,120779,1,122624,122654,1,122661,122666,1,122928,122989,1,123136,123180,1,123191,123197,1,123214,123536,322,123537,123565,1,123584,123627,1,124112,124139,1,124368,124397,1,124400,124896,496,124897,124902,1,124904,124907,1,124909,124910,1,124912,124926,1,124928,125124,1,125184,125251,1,125259,126464,1205,126465,126467,1,126469,126495,1,126497,126498,1,126500,126503,3,126505,126514,1,126516,126519,1,126521,126523,2,126530,126535,5,126537,126541,2,126542,126543,1,126545,126546,1,126548,126551,3,126553,126561,2,126562,126564,2,126567,126570,1,126572,126578,1,126580,126583,1,126585,126588,1,126590,126592,2,126593,126601,1,126603,126619,1,126625,126627,1,126629,126633,1,126635,126651,1,131072,173791,1,173824,177977,1,177984,178205,1,178208,183969,1,183984,191456,1,191472,192093,1,194560,195101,1,196608,201546,1,201552,205743,1]));static foldL=new K(new Uint32Array([837,837,1]));static Ll=new K(new Uint32Array([97,122,1,181,223,42,224,246,1,248,255,1,257,311,2,312,328,2,329,375,2,378,382,2,383,384,1,387,389,2,392,396,4,397,402,5,405,409,4,410,411,1,414,417,3,419,421,2,424,426,2,427,429,2,432,436,4,438,441,3,442,445,3,446,447,1,454,460,3,462,476,2,477,495,2,496,499,3,501,505,4,507,563,2,564,569,1,572,575,3,576,578,2,583,591,2,592,659,1,661,687,1,881,883,2,887,891,4,892,893,1,912,940,28,941,974,1,976,977,1,981,983,1,985,1007,2,1008,1011,1,1013,1019,3,1020,1072,52,1073,1119,1,1121,1153,2,1163,1215,2,1218,1230,2,1231,1327,2,1376,1416,1,4304,4346,1,4349,4351,1,5112,5117,1,7296,7304,1,7306,7424,118,7425,7467,1,7531,7543,1,7545,7578,1,7681,7829,2,7830,7837,1,7839,7935,2,7936,7943,1,7952,7957,1,7968,7975,1,7984,7991,1,8e3,8005,1,8016,8023,1,8032,8039,1,8048,8061,1,8064,8071,1,8080,8087,1,8096,8103,1,8112,8116,1,8118,8119,1,8126,8130,4,8131,8132,1,8134,8135,1,8144,8147,1,8150,8151,1,8160,8167,1,8178,8180,1,8182,8183,1,8458,8462,4,8463,8467,4,8495,8505,5,8508,8509,1,8518,8521,1,8526,8580,54,11312,11359,1,11361,11365,4,11366,11372,2,11377,11379,2,11380,11382,2,11383,11387,1,11393,11491,2,11492,11500,8,11502,11507,5,11520,11557,1,11559,11565,6,42561,42605,2,42625,42651,2,42787,42799,2,42800,42801,1,42803,42865,2,42866,42872,1,42874,42876,2,42879,42887,2,42892,42894,2,42897,42899,2,42900,42901,1,42903,42921,2,42927,42933,6,42935,42947,2,42952,42954,2,42957,42961,4,42963,42971,2,42998,43002,4,43824,43866,1,43872,43880,1,43888,43967,1,64256,64262,1,64275,64279,1,65345,65370,1,66600,66639,1,66776,66811,1,66967,66977,1,66979,66993,1,66995,67001,1,67003,67004,1,68800,68850,1,68976,68997,1,71872,71903,1,93792,93823,1,119834,119859,1,119886,119892,1,119894,119911,1,119938,119963,1,119990,119993,1,119995,119997,2,119998,120003,1,120005,120015,1,120042,120067,1,120094,120119,1,120146,120171,1,120198,120223,1,120250,120275,1,120302,120327,1,120354,120379,1,120406,120431,1,120458,120485,1,120514,120538,1,120540,120545,1,120572,120596,1,120598,120603,1,120630,120654,1,120656,120661,1,120688,120712,1,120714,120719,1,120746,120770,1,120772,120777,1,120779,122624,1845,122625,122633,1,122635,122654,1,122661,122666,1,125218,125251,1]));static foldLl=new K(new Uint32Array([65,90,1,192,214,1,216,222,1,256,302,2,306,310,2,313,327,2,330,376,2,377,381,2,385,386,1,388,390,2,391,393,2,394,395,1,398,401,1,403,404,1,406,408,1,412,413,1,415,416,1,418,422,2,423,425,2,428,430,2,431,433,2,434,435,1,437,439,2,440,444,4,452,453,1,455,456,1,458,459,1,461,475,2,478,494,2,497,498,1,500,502,2,503,504,1,506,562,2,570,571,1,573,574,1,577,579,2,580,582,1,584,590,2,837,880,43,882,886,4,895,902,7,904,906,1,908,910,2,911,913,2,914,929,1,931,939,1,975,984,9,986,1006,2,1012,1015,3,1017,1018,1,1021,1071,1,1120,1152,2,1162,1216,2,1217,1229,2,1232,1326,2,1329,1366,1,4256,4293,1,4295,4301,6,5024,5109,1,7305,7312,7,7313,7354,1,7357,7359,1,7680,7828,2,7838,7934,2,7944,7951,1,7960,7965,1,7976,7983,1,7992,7999,1,8008,8013,1,8025,8031,2,8040,8047,1,8072,8079,1,8088,8095,1,8104,8111,1,8120,8124,1,8136,8140,1,8152,8155,1,8168,8172,1,8184,8188,1,8486,8490,4,8491,8498,7,8579,11264,2685,11265,11311,1,11360,11362,2,11363,11364,1,11367,11373,2,11374,11376,1,11378,11381,3,11390,11392,1,11394,11490,2,11499,11501,2,11506,42560,31054,42562,42604,2,42624,42650,2,42786,42798,2,42802,42862,2,42873,42877,2,42878,42886,2,42891,42893,2,42896,42898,2,42902,42922,2,42923,42926,1,42928,42932,1,42934,42948,2,42949,42951,1,42953,42955,2,42956,42960,4,42966,42972,2,42997,65313,22316,65314,65338,1,66560,66599,1,66736,66771,1,66928,66938,1,66940,66954,1,66956,66962,1,66964,66965,1,68736,68786,1,68944,68965,1,71840,71871,1,93760,93791,1,125184,125217,1]));static Lm=new K(new Uint32Array([688,705,1,710,721,1,736,740,1,748,750,2,884,890,6,1369,1600,231,1765,1766,1,2036,2037,1,2042,2074,32,2084,2088,4,2249,2417,168,3654,3782,128,4348,6103,1755,6211,6823,612,7288,7293,1,7468,7530,1,7544,7579,35,7580,7615,1,8305,8319,14,8336,8348,1,11388,11389,1,11631,11823,192,12293,12337,44,12338,12341,1,12347,12445,98,12446,12540,94,12541,12542,1,40981,42232,1251,42233,42237,1,42508,42623,115,42652,42653,1,42775,42783,1,42864,42888,24,42994,42996,1,43e3,43001,1,43471,43494,23,43632,43741,109,43763,43764,1,43868,43871,1,43881,65392,21511,65438,65439,1,67456,67461,1,67463,67504,1,67506,67514,1,68942,68975,33,92992,92995,1,93504,93506,1,93547,93548,1,94099,94111,1,94176,94177,1,94179,110576,16397,110577,110579,1,110581,110587,1,110589,110590,1,122928,122989,1,123191,123197,1,124139,125259,1120]));static Lo=new K(new Uint32Array([170,186,16,443,448,5,449,451,1,660,1488,828,1489,1514,1,1519,1522,1,1568,1599,1,1601,1610,1,1646,1647,1,1649,1747,1,1749,1774,25,1775,1786,11,1787,1788,1,1791,1808,17,1810,1839,1,1869,1957,1,1969,1994,25,1995,2026,1,2048,2069,1,2112,2136,1,2144,2154,1,2160,2183,1,2185,2190,1,2208,2248,1,2308,2361,1,2365,2384,19,2392,2401,1,2418,2432,1,2437,2444,1,2447,2448,1,2451,2472,1,2474,2480,1,2482,2486,4,2487,2489,1,2493,2510,17,2524,2525,1,2527,2529,1,2544,2545,1,2556,2565,9,2566,2570,1,2575,2576,1,2579,2600,1,2602,2608,1,2610,2611,1,2613,2614,1,2616,2617,1,2649,2652,1,2654,2674,20,2675,2676,1,2693,2701,1,2703,2705,1,2707,2728,1,2730,2736,1,2738,2739,1,2741,2745,1,2749,2768,19,2784,2785,1,2809,2821,12,2822,2828,1,2831,2832,1,2835,2856,1,2858,2864,1,2866,2867,1,2869,2873,1,2877,2908,31,2909,2911,2,2912,2913,1,2929,2947,18,2949,2954,1,2958,2960,1,2962,2965,1,2969,2970,1,2972,2974,2,2975,2979,4,2980,2984,4,2985,2986,1,2990,3001,1,3024,3077,53,3078,3084,1,3086,3088,1,3090,3112,1,3114,3129,1,3133,3160,27,3161,3162,1,3165,3168,3,3169,3200,31,3205,3212,1,3214,3216,1,3218,3240,1,3242,3251,1,3253,3257,1,3261,3293,32,3294,3296,2,3297,3313,16,3314,3332,18,3333,3340,1,3342,3344,1,3346,3386,1,3389,3406,17,3412,3414,1,3423,3425,1,3450,3455,1,3461,3478,1,3482,3505,1,3507,3515,1,3517,3520,3,3521,3526,1,3585,3632,1,3634,3635,1,3648,3653,1,3713,3714,1,3716,3718,2,3719,3722,1,3724,3747,1,3749,3751,2,3752,3760,1,3762,3763,1,3773,3776,3,3777,3780,1,3804,3807,1,3840,3904,64,3905,3911,1,3913,3948,1,3976,3980,1,4096,4138,1,4159,4176,17,4177,4181,1,4186,4189,1,4193,4197,4,4198,4206,8,4207,4208,1,4213,4225,1,4238,4352,114,4353,4680,1,4682,4685,1,4688,4694,1,4696,4698,2,4699,4701,1,4704,4744,1,4746,4749,1,4752,4784,1,4786,4789,1,4792,4798,1,4800,4802,2,4803,4805,1,4808,4822,1,4824,4880,1,4882,4885,1,4888,4954,1,4992,5007,1,5121,5740,1,5743,5759,1,5761,5786,1,5792,5866,1,5873,5880,1,5888,5905,1,5919,5937,1,5952,5969,1,5984,5996,1,5998,6e3,1,6016,6067,1,6108,6176,68,6177,6210,1,6212,6264,1,6272,6276,1,6279,6312,1,6314,6320,6,6321,6389,1,6400,6430,1,6480,6509,1,6512,6516,1,6528,6571,1,6576,6601,1,6656,6678,1,6688,6740,1,6917,6963,1,6981,6988,1,7043,7072,1,7086,7087,1,7098,7141,1,7168,7203,1,7245,7247,1,7258,7287,1,7401,7404,1,7406,7411,1,7413,7414,1,7418,8501,1083,8502,8504,1,11568,11623,1,11648,11670,1,11680,11686,1,11688,11694,1,11696,11702,1,11704,11710,1,11712,11718,1,11720,11726,1,11728,11734,1,11736,11742,1,12294,12348,54,12353,12438,1,12447,12449,2,12450,12538,1,12543,12549,6,12550,12591,1,12593,12686,1,12704,12735,1,12784,12799,1,13312,19903,1,19968,40980,1,40982,42124,1,42192,42231,1,42240,42507,1,42512,42527,1,42538,42539,1,42606,42656,50,42657,42725,1,42895,42999,104,43003,43009,1,43011,43013,1,43015,43018,1,43020,43042,1,43072,43123,1,43138,43187,1,43250,43255,1,43259,43261,2,43262,43274,12,43275,43301,1,43312,43334,1,43360,43388,1,43396,43442,1,43488,43492,1,43495,43503,1,43514,43518,1,43520,43560,1,43584,43586,1,43588,43595,1,43616,43631,1,43633,43638,1,43642,43646,4,43647,43695,1,43697,43701,4,43702,43705,3,43706,43709,1,43712,43714,2,43739,43740,1,43744,43754,1,43762,43777,15,43778,43782,1,43785,43790,1,43793,43798,1,43808,43814,1,43816,43822,1,43968,44002,1,44032,55203,1,55216,55238,1,55243,55291,1,63744,64109,1,64112,64217,1,64285,64287,2,64288,64296,1,64298,64310,1,64312,64316,1,64318,64320,2,64321,64323,2,64324,64326,2,64327,64433,1,64467,64829,1,64848,64911,1,64914,64967,1,65008,65019,1,65136,65140,1,65142,65276,1,65382,65391,1,65393,65437,1,65440,65470,1,65474,65479,1,65482,65487,1,65490,65495,1,65498,65500,1,65536,65547,1,65549,65574,1,65576,65594,1,65596,65597,1,65599,65613,1,65616,65629,1,65664,65786,1,66176,66204,1,66208,66256,1,66304,66335,1,66349,66368,1,66370,66377,1,66384,66421,1,66432,66461,1,66464,66499,1,66504,66511,1,66640,66717,1,66816,66855,1,66864,66915,1,67008,67059,1,67072,67382,1,67392,67413,1,67424,67431,1,67584,67589,1,67592,67594,2,67595,67637,1,67639,67640,1,67644,67647,3,67648,67669,1,67680,67702,1,67712,67742,1,67808,67826,1,67828,67829,1,67840,67861,1,67872,67897,1,67968,68023,1,68030,68031,1,68096,68112,16,68113,68115,1,68117,68119,1,68121,68149,1,68192,68220,1,68224,68252,1,68288,68295,1,68297,68324,1,68352,68405,1,68416,68437,1,68448,68466,1,68480,68497,1,68608,68680,1,68864,68899,1,68938,68941,1,68943,69248,305,69249,69289,1,69296,69297,1,69314,69316,1,69376,69404,1,69415,69424,9,69425,69445,1,69488,69505,1,69552,69572,1,69600,69622,1,69635,69687,1,69745,69746,1,69749,69763,14,69764,69807,1,69840,69864,1,69891,69926,1,69956,69959,3,69968,70002,1,70006,70019,13,70020,70066,1,70081,70084,1,70106,70108,2,70144,70161,1,70163,70187,1,70207,70208,1,70272,70278,1,70280,70282,2,70283,70285,1,70287,70301,1,70303,70312,1,70320,70366,1,70405,70412,1,70415,70416,1,70419,70440,1,70442,70448,1,70450,70451,1,70453,70457,1,70461,70480,19,70493,70497,1,70528,70537,1,70539,70542,3,70544,70581,1,70583,70609,26,70611,70656,45,70657,70708,1,70727,70730,1,70751,70753,1,70784,70831,1,70852,70853,1,70855,71040,185,71041,71086,1,71128,71131,1,71168,71215,1,71236,71296,60,71297,71338,1,71352,71424,72,71425,71450,1,71488,71494,1,71680,71723,1,71935,71942,1,71945,71948,3,71949,71955,1,71957,71958,1,71960,71983,1,71999,72001,2,72096,72103,1,72106,72144,1,72161,72163,2,72192,72203,11,72204,72242,1,72250,72272,22,72284,72329,1,72349,72368,19,72369,72440,1,72640,72672,1,72704,72712,1,72714,72750,1,72768,72818,50,72819,72847,1,72960,72966,1,72968,72969,1,72971,73008,1,73030,73056,26,73057,73061,1,73063,73064,1,73066,73097,1,73112,73440,328,73441,73458,1,73474,73476,2,73477,73488,1,73490,73523,1,73648,73728,80,73729,74649,1,74880,75075,1,77712,77808,1,77824,78895,1,78913,78918,1,78944,82938,1,82944,83526,1,90368,90397,1,92160,92728,1,92736,92766,1,92784,92862,1,92880,92909,1,92928,92975,1,93027,93047,1,93053,93071,1,93507,93546,1,93952,94026,1,94032,94208,176,94209,100343,1,100352,101589,1,101631,101640,1,110592,110882,1,110898,110928,30,110929,110930,1,110933,110948,15,110949,110951,1,110960,111355,1,113664,113770,1,113776,113788,1,113792,113800,1,113808,113817,1,122634,123136,502,123137,123180,1,123214,123536,322,123537,123565,1,123584,123627,1,124112,124138,1,124368,124397,1,124400,124896,496,124897,124902,1,124904,124907,1,124909,124910,1,124912,124926,1,124928,125124,1,126464,126467,1,126469,126495,1,126497,126498,1,126500,126503,3,126505,126514,1,126516,126519,1,126521,126523,2,126530,126535,5,126537,126541,2,126542,126543,1,126545,126546,1,126548,126551,3,126553,126561,2,126562,126564,2,126567,126570,1,126572,126578,1,126580,126583,1,126585,126588,1,126590,126592,2,126593,126601,1,126603,126619,1,126625,126627,1,126629,126633,1,126635,126651,1,131072,173791,1,173824,177977,1,177984,178205,1,178208,183969,1,183984,191456,1,191472,192093,1,194560,195101,1,196608,201546,1,201552,205743,1]));static Lt=new K(new Uint32Array([453,459,3,498,8072,7574,8073,8079,1,8088,8095,1,8104,8111,1,8124,8140,16,8188,8188,1]));static foldLt=new K(new Uint32Array([452,454,2,455,457,2,458,460,2,497,499,2,8064,8071,1,8080,8087,1,8096,8103,1,8115,8131,16,8179,8179,1]));static Lu=new K(new Uint32Array([65,90,1,192,214,1,216,222,1,256,310,2,313,327,2,330,376,2,377,381,2,385,386,1,388,390,2,391,393,2,394,395,1,398,401,1,403,404,1,406,408,1,412,413,1,415,416,1,418,422,2,423,425,2,428,430,2,431,433,2,434,435,1,437,439,2,440,444,4,452,461,3,463,475,2,478,494,2,497,500,3,502,504,1,506,562,2,570,571,1,573,574,1,577,579,2,580,582,1,584,590,2,880,882,2,886,895,9,902,904,2,905,906,1,908,910,2,911,913,2,914,929,1,931,939,1,975,978,3,979,980,1,984,1006,2,1012,1015,3,1017,1018,1,1021,1071,1,1120,1152,2,1162,1216,2,1217,1229,2,1232,1326,2,1329,1366,1,4256,4293,1,4295,4301,6,5024,5109,1,7305,7312,7,7313,7354,1,7357,7359,1,7680,7828,2,7838,7934,2,7944,7951,1,7960,7965,1,7976,7983,1,7992,7999,1,8008,8013,1,8025,8031,2,8040,8047,1,8120,8123,1,8136,8139,1,8152,8155,1,8168,8172,1,8184,8187,1,8450,8455,5,8459,8461,1,8464,8466,1,8469,8473,4,8474,8477,1,8484,8490,2,8491,8493,1,8496,8499,1,8510,8511,1,8517,8579,62,11264,11311,1,11360,11362,2,11363,11364,1,11367,11373,2,11374,11376,1,11378,11381,3,11390,11392,1,11394,11490,2,11499,11501,2,11506,42560,31054,42562,42604,2,42624,42650,2,42786,42798,2,42802,42862,2,42873,42877,2,42878,42886,2,42891,42893,2,42896,42898,2,42902,42922,2,42923,42926,1,42928,42932,1,42934,42948,2,42949,42951,1,42953,42955,2,42956,42960,4,42966,42972,2,42997,65313,22316,65314,65338,1,66560,66599,1,66736,66771,1,66928,66938,1,66940,66954,1,66956,66962,1,66964,66965,1,68736,68786,1,68944,68965,1,71840,71871,1,93760,93791,1,119808,119833,1,119860,119885,1,119912,119937,1,119964,119966,2,119967,119973,3,119974,119977,3,119978,119980,1,119982,119989,1,120016,120041,1,120068,120069,1,120071,120074,1,120077,120084,1,120086,120092,1,120120,120121,1,120123,120126,1,120128,120132,1,120134,120138,4,120139,120144,1,120172,120197,1,120224,120249,1,120276,120301,1,120328,120353,1,120380,120405,1,120432,120457,1,120488,120512,1,120546,120570,1,120604,120628,1,120662,120686,1,120720,120744,1,120778,125184,4406,125185,125217,1]));static Upper=this.Lu;static foldLu=new K(new Uint32Array([97,122,1,181,223,42,224,246,1,248,255,1,257,303,2,307,311,2,314,328,2,331,375,2,378,382,2,383,384,1,387,389,2,392,396,4,402,405,3,409,411,1,414,417,3,419,421,2,424,429,5,432,436,4,438,441,3,445,447,2,453,454,1,456,457,1,459,460,1,462,476,2,477,495,2,498,499,1,501,505,4,507,543,2,547,563,2,572,575,3,576,578,2,583,591,2,592,596,1,598,599,1,601,603,2,604,608,4,609,611,2,612,614,1,616,620,1,623,625,2,626,629,3,637,640,3,642,643,1,647,652,1,658,669,11,670,837,167,881,883,2,887,891,4,892,893,1,940,943,1,945,974,1,976,977,1,981,983,1,985,1007,2,1008,1011,1,1013,1019,3,1072,1119,1,1121,1153,2,1163,1215,2,1218,1230,2,1231,1327,2,1377,1414,1,4304,4346,1,4349,4351,1,5112,5117,1,7296,7304,1,7306,7545,239,7549,7566,17,7681,7829,2,7835,7841,6,7843,7935,2,7936,7943,1,7952,7957,1,7968,7975,1,7984,7991,1,8e3,8005,1,8017,8023,2,8032,8039,1,8048,8061,1,8112,8113,1,8126,8144,18,8145,8160,15,8161,8165,4,8526,8580,54,11312,11359,1,11361,11365,4,11366,11372,2,11379,11382,3,11393,11491,2,11500,11502,2,11507,11520,13,11521,11557,1,11559,11565,6,42561,42605,2,42625,42651,2,42787,42799,2,42803,42863,2,42874,42876,2,42879,42887,2,42892,42897,5,42899,42900,1,42903,42921,2,42933,42947,2,42952,42954,2,42957,42961,4,42967,42971,2,42998,43859,861,43888,43967,1,65345,65370,1,66600,66639,1,66776,66811,1,66967,66977,1,66979,66993,1,66995,67001,1,67003,67004,1,68800,68850,1,68976,68997,1,71872,71903,1,93792,93823,1,125218,125251,1]));static M=new K(new Uint32Array([768,879,1,1155,1161,1,1425,1469,1,1471,1473,2,1474,1476,2,1477,1479,2,1552,1562,1,1611,1631,1,1648,1750,102,1751,1756,1,1759,1764,1,1767,1768,1,1770,1773,1,1809,1840,31,1841,1866,1,1958,1968,1,2027,2035,1,2045,2070,25,2071,2073,1,2075,2083,1,2085,2087,1,2089,2093,1,2137,2139,1,2199,2207,1,2250,2273,1,2275,2307,1,2362,2364,1,2366,2383,1,2385,2391,1,2402,2403,1,2433,2435,1,2492,2494,2,2495,2500,1,2503,2504,1,2507,2509,1,2519,2530,11,2531,2558,27,2561,2563,1,2620,2622,2,2623,2626,1,2631,2632,1,2635,2637,1,2641,2672,31,2673,2677,4,2689,2691,1,2748,2750,2,2751,2757,1,2759,2761,1,2763,2765,1,2786,2787,1,2810,2815,1,2817,2819,1,2876,2878,2,2879,2884,1,2887,2888,1,2891,2893,1,2901,2903,1,2914,2915,1,2946,3006,60,3007,3010,1,3014,3016,1,3018,3021,1,3031,3072,41,3073,3076,1,3132,3134,2,3135,3140,1,3142,3144,1,3146,3149,1,3157,3158,1,3170,3171,1,3201,3203,1,3260,3262,2,3263,3268,1,3270,3272,1,3274,3277,1,3285,3286,1,3298,3299,1,3315,3328,13,3329,3331,1,3387,3388,1,3390,3396,1,3398,3400,1,3402,3405,1,3415,3426,11,3427,3457,30,3458,3459,1,3530,3535,5,3536,3540,1,3542,3544,2,3545,3551,1,3570,3571,1,3633,3636,3,3637,3642,1,3655,3662,1,3761,3764,3,3765,3772,1,3784,3790,1,3864,3865,1,3893,3897,2,3902,3903,1,3953,3972,1,3974,3975,1,3981,3991,1,3993,4028,1,4038,4139,101,4140,4158,1,4182,4185,1,4190,4192,1,4194,4196,1,4199,4205,1,4209,4212,1,4226,4237,1,4239,4250,11,4251,4253,1,4957,4959,1,5906,5909,1,5938,5940,1,5970,5971,1,6002,6003,1,6068,6099,1,6109,6155,46,6156,6157,1,6159,6277,118,6278,6313,35,6432,6443,1,6448,6459,1,6679,6683,1,6741,6750,1,6752,6780,1,6783,6832,49,6833,6862,1,6912,6916,1,6964,6980,1,7019,7027,1,7040,7042,1,7073,7085,1,7142,7155,1,7204,7223,1,7376,7378,1,7380,7400,1,7405,7412,7,7415,7417,1,7616,7679,1,8400,8432,1,11503,11505,1,11647,11744,97,11745,11775,1,12330,12335,1,12441,12442,1,42607,42610,1,42612,42621,1,42654,42655,1,42736,42737,1,43010,43014,4,43019,43043,24,43044,43047,1,43052,43136,84,43137,43188,51,43189,43205,1,43232,43249,1,43263,43302,39,43303,43309,1,43335,43347,1,43392,43395,1,43443,43456,1,43493,43561,68,43562,43574,1,43587,43596,9,43597,43643,46,43644,43645,1,43696,43698,2,43699,43700,1,43703,43704,1,43710,43711,1,43713,43755,42,43756,43759,1,43765,43766,1,44003,44010,1,44012,44013,1,64286,65024,738,65025,65039,1,65056,65071,1,66045,66272,227,66422,66426,1,68097,68099,1,68101,68102,1,68108,68111,1,68152,68154,1,68159,68325,166,68326,68900,574,68901,68903,1,68969,68973,1,69291,69292,1,69372,69375,1,69446,69456,1,69506,69509,1,69632,69634,1,69688,69702,1,69744,69747,3,69748,69759,11,69760,69762,1,69808,69818,1,69826,69888,62,69889,69890,1,69927,69940,1,69957,69958,1,70003,70016,13,70017,70018,1,70067,70080,1,70089,70092,1,70094,70095,1,70188,70199,1,70206,70209,3,70367,70378,1,70400,70403,1,70459,70460,1,70462,70468,1,70471,70472,1,70475,70477,1,70487,70498,11,70499,70502,3,70503,70508,1,70512,70516,1,70584,70592,1,70594,70597,3,70599,70602,1,70604,70608,1,70610,70625,15,70626,70709,83,70710,70726,1,70750,70832,82,70833,70851,1,71087,71093,1,71096,71104,1,71132,71133,1,71216,71232,1,71339,71351,1,71453,71467,1,71724,71738,1,71984,71989,1,71991,71992,1,71995,71998,1,72e3,72002,2,72003,72145,142,72146,72151,1,72154,72160,1,72164,72193,29,72194,72202,1,72243,72249,1,72251,72254,1,72263,72273,10,72274,72283,1,72330,72345,1,72751,72758,1,72760,72767,1,72850,72871,1,72873,72886,1,73009,73014,1,73018,73020,2,73021,73023,2,73024,73029,1,73031,73098,67,73099,73102,1,73104,73105,1,73107,73111,1,73459,73462,1,73472,73473,1,73475,73524,49,73525,73530,1,73534,73538,1,73562,78912,5350,78919,78933,1,90398,90415,1,92912,92916,1,92976,92982,1,94031,94033,2,94034,94087,1,94095,94098,1,94180,94192,12,94193,113821,19628,113822,118528,4706,118529,118573,1,118576,118598,1,119141,119145,1,119149,119154,1,119163,119170,1,119173,119179,1,119210,119213,1,119362,119364,1,121344,121398,1,121403,121452,1,121461,121476,15,121499,121503,1,121505,121519,1,122880,122886,1,122888,122904,1,122907,122913,1,122915,122916,1,122918,122922,1,123023,123184,161,123185,123190,1,123566,123628,62,123629,123631,1,124140,124143,1,124398,124399,1,125136,125142,1,125252,125258,1,917760,917999,1]));static foldM=new K(new Uint32Array([921,953,32,8126,8126,1]));static Mc=new K(new Uint32Array([2307,2363,56,2366,2368,1,2377,2380,1,2382,2383,1,2434,2435,1,2494,2496,1,2503,2504,1,2507,2508,1,2519,2563,44,2622,2624,1,2691,2750,59,2751,2752,1,2761,2763,2,2764,2818,54,2819,2878,59,2880,2887,7,2888,2891,3,2892,2903,11,3006,3007,1,3009,3010,1,3014,3016,1,3018,3020,1,3031,3073,42,3074,3075,1,3137,3140,1,3202,3203,1,3262,3264,2,3265,3268,1,3271,3272,1,3274,3275,1,3285,3286,1,3315,3330,15,3331,3390,59,3391,3392,1,3398,3400,1,3402,3404,1,3415,3458,43,3459,3535,76,3536,3537,1,3544,3551,1,3570,3571,1,3902,3903,1,3967,4139,172,4140,4145,5,4152,4155,3,4156,4182,26,4183,4194,11,4195,4196,1,4199,4205,1,4227,4228,1,4231,4236,1,4239,4250,11,4251,4252,1,5909,5940,31,6070,6078,8,6079,6085,1,6087,6088,1,6435,6438,1,6441,6443,1,6448,6449,1,6451,6456,1,6681,6682,1,6741,6743,2,6753,6755,2,6756,6765,9,6766,6770,1,6916,6965,49,6971,6973,2,6974,6977,1,6979,6980,1,7042,7073,31,7078,7079,1,7082,7143,61,7146,7148,1,7150,7154,4,7155,7204,49,7205,7211,1,7220,7221,1,7393,7415,22,12334,12335,1,43043,43044,1,43047,43136,89,43137,43188,51,43189,43203,1,43346,43347,1,43395,43444,49,43445,43450,5,43451,43454,3,43455,43456,1,43567,43568,1,43571,43572,1,43597,43643,46,43645,43755,110,43758,43759,1,43765,44003,238,44004,44006,2,44007,44009,2,44010,44012,2,69632,69634,2,69762,69808,46,69809,69810,1,69815,69816,1,69932,69957,25,69958,70018,60,70067,70069,1,70079,70080,1,70094,70188,94,70189,70190,1,70194,70195,1,70197,70368,171,70369,70370,1,70402,70403,1,70462,70463,1,70465,70468,1,70471,70472,1,70475,70477,1,70487,70498,11,70499,70584,85,70585,70586,1,70594,70597,3,70599,70602,1,70604,70605,1,70607,70709,102,70710,70711,1,70720,70721,1,70725,70832,107,70833,70834,1,70841,70843,2,70844,70846,1,70849,71087,238,71088,71089,1,71096,71099,1,71102,71216,114,71217,71218,1,71227,71228,1,71230,71340,110,71342,71343,1,71350,71454,104,71456,71457,1,71462,71724,262,71725,71726,1,71736,71984,248,71985,71989,1,71991,71992,1,71997,72e3,3,72002,72145,143,72146,72147,1,72156,72159,1,72164,72249,85,72279,72280,1,72343,72751,408,72766,72873,107,72881,72884,3,73098,73102,1,73107,73108,1,73110,73461,351,73462,73475,13,73524,73525,1,73534,73535,1,73537,90410,16873,90411,90412,1,94033,94087,1,94192,94193,1,119141,119142,1,119149,119154,1]));static Me=new K(new Uint32Array([1160,1161,1,6846,8413,1567,8414,8416,1,8418,8420,1,42608,42610,1]));static Mn=new K(new Uint32Array([768,879,1,1155,1159,1,1425,1469,1,1471,1473,2,1474,1476,2,1477,1479,2,1552,1562,1,1611,1631,1,1648,1750,102,1751,1756,1,1759,1764,1,1767,1768,1,1770,1773,1,1809,1840,31,1841,1866,1,1958,1968,1,2027,2035,1,2045,2070,25,2071,2073,1,2075,2083,1,2085,2087,1,2089,2093,1,2137,2139,1,2199,2207,1,2250,2273,1,2275,2306,1,2362,2364,2,2369,2376,1,2381,2385,4,2386,2391,1,2402,2403,1,2433,2492,59,2497,2500,1,2509,2530,21,2531,2558,27,2561,2562,1,2620,2625,5,2626,2631,5,2632,2635,3,2636,2637,1,2641,2672,31,2673,2677,4,2689,2690,1,2748,2753,5,2754,2757,1,2759,2760,1,2765,2786,21,2787,2810,23,2811,2815,1,2817,2876,59,2879,2881,2,2882,2884,1,2893,2901,8,2902,2914,12,2915,2946,31,3008,3021,13,3072,3076,4,3132,3134,2,3135,3136,1,3142,3144,1,3146,3149,1,3157,3158,1,3170,3171,1,3201,3260,59,3263,3270,7,3276,3277,1,3298,3299,1,3328,3329,1,3387,3388,1,3393,3396,1,3405,3426,21,3427,3457,30,3530,3538,8,3539,3540,1,3542,3633,91,3636,3642,1,3655,3662,1,3761,3764,3,3765,3772,1,3784,3790,1,3864,3865,1,3893,3897,2,3953,3966,1,3968,3972,1,3974,3975,1,3981,3991,1,3993,4028,1,4038,4141,103,4142,4144,1,4146,4151,1,4153,4154,1,4157,4158,1,4184,4185,1,4190,4192,1,4209,4212,1,4226,4229,3,4230,4237,7,4253,4957,704,4958,4959,1,5906,5908,1,5938,5939,1,5970,5971,1,6002,6003,1,6068,6069,1,6071,6077,1,6086,6089,3,6090,6099,1,6109,6155,46,6156,6157,1,6159,6277,118,6278,6313,35,6432,6434,1,6439,6440,1,6450,6457,7,6458,6459,1,6679,6680,1,6683,6742,59,6744,6750,1,6752,6754,2,6757,6764,1,6771,6780,1,6783,6832,49,6833,6845,1,6847,6862,1,6912,6915,1,6964,6966,2,6967,6970,1,6972,6978,6,7019,7027,1,7040,7041,1,7074,7077,1,7080,7081,1,7083,7085,1,7142,7144,2,7145,7149,4,7151,7153,1,7212,7219,1,7222,7223,1,7376,7378,1,7380,7392,1,7394,7400,1,7405,7412,7,7416,7417,1,7616,7679,1,8400,8412,1,8417,8421,4,8422,8432,1,11503,11505,1,11647,11744,97,11745,11775,1,12330,12333,1,12441,12442,1,42607,42612,5,42613,42621,1,42654,42655,1,42736,42737,1,43010,43014,4,43019,43045,26,43046,43052,6,43204,43205,1,43232,43249,1,43263,43302,39,43303,43309,1,43335,43345,1,43392,43394,1,43443,43446,3,43447,43449,1,43452,43453,1,43493,43561,68,43562,43566,1,43569,43570,1,43573,43574,1,43587,43596,9,43644,43696,52,43698,43700,1,43703,43704,1,43710,43711,1,43713,43756,43,43757,43766,9,44005,44008,3,44013,64286,20273,65024,65039,1,65056,65071,1,66045,66272,227,66422,66426,1,68097,68099,1,68101,68102,1,68108,68111,1,68152,68154,1,68159,68325,166,68326,68900,574,68901,68903,1,68969,68973,1,69291,69292,1,69372,69375,1,69446,69456,1,69506,69509,1,69633,69688,55,69689,69702,1,69744,69747,3,69748,69759,11,69760,69761,1,69811,69814,1,69817,69818,1,69826,69888,62,69889,69890,1,69927,69931,1,69933,69940,1,70003,70016,13,70017,70070,53,70071,70078,1,70089,70092,1,70095,70191,96,70192,70193,1,70196,70198,2,70199,70206,7,70209,70367,158,70371,70378,1,70400,70401,1,70459,70460,1,70464,70502,38,70503,70508,1,70512,70516,1,70587,70592,1,70606,70610,2,70625,70626,1,70712,70719,1,70722,70724,1,70726,70750,24,70835,70840,1,70842,70847,5,70848,70850,2,70851,71090,239,71091,71093,1,71100,71101,1,71103,71104,1,71132,71133,1,71219,71226,1,71229,71231,2,71232,71339,107,71341,71344,3,71345,71349,1,71351,71453,102,71455,71458,3,71459,71461,1,71463,71467,1,71727,71735,1,71737,71738,1,71995,71996,1,71998,72003,5,72148,72151,1,72154,72155,1,72160,72193,33,72194,72202,1,72243,72248,1,72251,72254,1,72263,72273,10,72274,72278,1,72281,72283,1,72330,72342,1,72344,72345,1,72752,72758,1,72760,72765,1,72767,72850,83,72851,72871,1,72874,72880,1,72882,72883,1,72885,72886,1,73009,73014,1,73018,73020,2,73021,73023,2,73024,73029,1,73031,73104,73,73105,73109,4,73111,73459,348,73460,73472,12,73473,73526,53,73527,73530,1,73536,73538,2,73562,78912,5350,78919,78933,1,90398,90409,1,90413,90415,1,92912,92916,1,92976,92982,1,94031,94095,64,94096,94098,1,94180,113821,19641,113822,118528,4706,118529,118573,1,118576,118598,1,119143,119145,1,119163,119170,1,119173,119179,1,119210,119213,1,119362,119364,1,121344,121398,1,121403,121452,1,121461,121476,15,121499,121503,1,121505,121519,1,122880,122886,1,122888,122904,1,122907,122913,1,122915,122916,1,122918,122922,1,123023,123184,161,123185,123190,1,123566,123628,62,123629,123631,1,124140,124143,1,124398,124399,1,125136,125142,1,125252,125258,1,917760,917999,1]));static foldMn=new K(new Uint32Array([921,953,32,8126,8126,1]));static N=new K(new Uint32Array([48,57,1,178,179,1,185,188,3,189,190,1,1632,1641,1,1776,1785,1,1984,1993,1,2406,2415,1,2534,2543,1,2548,2553,1,2662,2671,1,2790,2799,1,2918,2927,1,2930,2935,1,3046,3058,1,3174,3183,1,3192,3198,1,3302,3311,1,3416,3422,1,3430,3448,1,3558,3567,1,3664,3673,1,3792,3801,1,3872,3891,1,4160,4169,1,4240,4249,1,4969,4988,1,5870,5872,1,6112,6121,1,6128,6137,1,6160,6169,1,6470,6479,1,6608,6618,1,6784,6793,1,6800,6809,1,6992,7001,1,7088,7097,1,7232,7241,1,7248,7257,1,8304,8308,4,8309,8313,1,8320,8329,1,8528,8578,1,8581,8585,1,9312,9371,1,9450,9471,1,10102,10131,1,11517,12295,778,12321,12329,1,12344,12346,1,12690,12693,1,12832,12841,1,12872,12879,1,12881,12895,1,12928,12937,1,12977,12991,1,42528,42537,1,42726,42735,1,43056,43061,1,43216,43225,1,43264,43273,1,43472,43481,1,43504,43513,1,43600,43609,1,44016,44025,1,65296,65305,1,65799,65843,1,65856,65912,1,65930,65931,1,66273,66299,1,66336,66339,1,66369,66378,9,66513,66517,1,66720,66729,1,67672,67679,1,67705,67711,1,67751,67759,1,67835,67839,1,67862,67867,1,68028,68029,1,68032,68047,1,68050,68095,1,68160,68168,1,68221,68222,1,68253,68255,1,68331,68335,1,68440,68447,1,68472,68479,1,68521,68527,1,68858,68863,1,68912,68921,1,68928,68937,1,69216,69246,1,69405,69414,1,69457,69460,1,69573,69579,1,69714,69743,1,69872,69881,1,69942,69951,1,70096,70105,1,70113,70132,1,70384,70393,1,70736,70745,1,70864,70873,1,71248,71257,1,71360,71369,1,71376,71395,1,71472,71483,1,71904,71922,1,72016,72025,1,72688,72697,1,72784,72812,1,73040,73049,1,73120,73129,1,73552,73561,1,73664,73684,1,74752,74862,1,90416,90425,1,92768,92777,1,92864,92873,1,93008,93017,1,93019,93025,1,93552,93561,1,93824,93846,1,118e3,118009,1,119488,119507,1,119520,119539,1,119648,119672,1,120782,120831,1,123200,123209,1,123632,123641,1,124144,124153,1,124401,124410,1,125127,125135,1,125264,125273,1,126065,126123,1,126125,126127,1,126129,126132,1,126209,126253,1,126255,126269,1,127232,127244,1,130032,130041,1]));static Nd=new K(new Uint32Array([48,57,1,1632,1641,1,1776,1785,1,1984,1993,1,2406,2415,1,2534,2543,1,2662,2671,1,2790,2799,1,2918,2927,1,3046,3055,1,3174,3183,1,3302,3311,1,3430,3439,1,3558,3567,1,3664,3673,1,3792,3801,1,3872,3881,1,4160,4169,1,4240,4249,1,6112,6121,1,6160,6169,1,6470,6479,1,6608,6617,1,6784,6793,1,6800,6809,1,6992,7001,1,7088,7097,1,7232,7241,1,7248,7257,1,42528,42537,1,43216,43225,1,43264,43273,1,43472,43481,1,43504,43513,1,43600,43609,1,44016,44025,1,65296,65305,1,66720,66729,1,68912,68921,1,68928,68937,1,69734,69743,1,69872,69881,1,69942,69951,1,70096,70105,1,70384,70393,1,70736,70745,1,70864,70873,1,71248,71257,1,71360,71369,1,71376,71395,1,71472,71481,1,71904,71913,1,72016,72025,1,72688,72697,1,72784,72793,1,73040,73049,1,73120,73129,1,73552,73561,1,90416,90425,1,92768,92777,1,92864,92873,1,93008,93017,1,93552,93561,1,118e3,118009,1,120782,120831,1,123200,123209,1,123632,123641,1,124144,124153,1,124401,124410,1,125264,125273,1,130032,130041,1]));static Nl=new K(new Uint32Array([5870,5872,1,8544,8578,1,8581,8584,1,12295,12321,26,12322,12329,1,12344,12346,1,42726,42735,1,65856,65908,1,66369,66378,9,66513,66517,1,74752,74862,1]));static No=new K(new Uint32Array([178,179,1,185,188,3,189,190,1,2548,2553,1,2930,2935,1,3056,3058,1,3192,3198,1,3416,3422,1,3440,3448,1,3882,3891,1,4969,4988,1,6128,6137,1,6618,8304,1686,8308,8313,1,8320,8329,1,8528,8543,1,8585,9312,727,9313,9371,1,9450,9471,1,10102,10131,1,11517,12690,1173,12691,12693,1,12832,12841,1,12872,12879,1,12881,12895,1,12928,12937,1,12977,12991,1,43056,43061,1,65799,65843,1,65909,65912,1,65930,65931,1,66273,66299,1,66336,66339,1,67672,67679,1,67705,67711,1,67751,67759,1,67835,67839,1,67862,67867,1,68028,68029,1,68032,68047,1,68050,68095,1,68160,68168,1,68221,68222,1,68253,68255,1,68331,68335,1,68440,68447,1,68472,68479,1,68521,68527,1,68858,68863,1,69216,69246,1,69405,69414,1,69457,69460,1,69573,69579,1,69714,69733,1,70113,70132,1,71482,71483,1,71914,71922,1,72794,72812,1,73664,73684,1,93019,93025,1,93824,93846,1,119488,119507,1,119520,119539,1,119648,119672,1,125127,125135,1,126065,126123,1,126125,126127,1,126129,126132,1,126209,126253,1,126255,126269,1,127232,127244,1]));static P=new K(new Uint32Array([33,35,1,37,42,1,44,47,1,58,59,1,63,64,1,91,93,1,95,123,28,125,161,36,167,171,4,182,183,1,187,191,4,894,903,9,1370,1375,1,1417,1418,1,1470,1472,2,1475,1478,3,1523,1524,1,1545,1546,1,1548,1549,1,1563,1565,2,1566,1567,1,1642,1645,1,1748,1792,44,1793,1805,1,2039,2041,1,2096,2110,1,2142,2404,262,2405,2416,11,2557,2678,121,2800,3191,391,3204,3572,368,3663,3674,11,3675,3844,169,3845,3858,1,3860,3898,38,3899,3901,1,3973,4048,75,4049,4052,1,4057,4058,1,4170,4175,1,4347,4960,613,4961,4968,1,5120,5742,622,5787,5788,1,5867,5869,1,5941,5942,1,6100,6102,1,6104,6106,1,6144,6154,1,6468,6469,1,6686,6687,1,6816,6822,1,6824,6829,1,6990,6991,1,7002,7008,1,7037,7039,1,7164,7167,1,7227,7231,1,7294,7295,1,7360,7367,1,7379,8208,829,8209,8231,1,8240,8259,1,8261,8273,1,8275,8286,1,8317,8318,1,8333,8334,1,8968,8971,1,9001,9002,1,10088,10101,1,10181,10182,1,10214,10223,1,10627,10648,1,10712,10715,1,10748,10749,1,11513,11516,1,11518,11519,1,11632,11776,144,11777,11822,1,11824,11855,1,11858,11869,1,12289,12291,1,12296,12305,1,12308,12319,1,12336,12349,13,12448,12539,91,42238,42239,1,42509,42511,1,42611,42622,11,42738,42743,1,43124,43127,1,43214,43215,1,43256,43258,1,43260,43310,50,43311,43359,48,43457,43469,1,43486,43487,1,43612,43615,1,43742,43743,1,43760,43761,1,44011,64830,20819,64831,65040,209,65041,65049,1,65072,65106,1,65108,65121,1,65123,65128,5,65130,65131,1,65281,65283,1,65285,65290,1,65292,65295,1,65306,65307,1,65311,65312,1,65339,65341,1,65343,65371,28,65373,65375,2,65376,65381,1,65792,65794,1,66463,66512,49,66927,67671,744,67871,67903,32,68176,68184,1,68223,68336,113,68337,68342,1,68409,68415,1,68505,68508,1,68974,69293,319,69461,69465,1,69510,69513,1,69703,69709,1,69819,69820,1,69822,69825,1,69952,69955,1,70004,70005,1,70085,70088,1,70093,70107,14,70109,70111,1,70200,70205,1,70313,70612,299,70613,70615,2,70616,70731,115,70732,70735,1,70746,70747,1,70749,70854,105,71105,71127,1,71233,71235,1,71264,71276,1,71353,71484,131,71485,71486,1,71739,72004,265,72005,72006,1,72162,72255,93,72256,72262,1,72346,72348,1,72350,72354,1,72448,72457,1,72673,72769,96,72770,72773,1,72816,72817,1,73463,73464,1,73539,73551,1,73727,74864,1137,74865,74868,1,77809,77810,1,92782,92783,1,92917,92983,66,92984,92987,1,92996,93549,553,93550,93551,1,93847,93850,1,94178,113823,19645,121479,121483,1,124415,125278,863,125279,125279,1]));static Pc=new K(new Uint32Array([95,8255,8160,8256,8276,20,65075,65076,1,65101,65103,1,65343,65343,1]));static Pd=new K(new Uint32Array([45,1418,1373,1470,5120,3650,6150,8208,2058,8209,8213,1,11799,11802,3,11834,11835,1,11840,11869,29,12316,12336,20,12448,65073,52625,65074,65112,38,65123,65293,170,68974,69293,319]));static Pe=new K(new Uint32Array([41,93,52,125,3899,3774,3901,5788,1887,8262,8318,56,8334,8969,635,8971,9002,31,10089,10101,2,10182,10215,33,10217,10223,2,10628,10648,2,10713,10715,2,10749,11811,1062,11813,11817,2,11862,11868,2,12297,12305,2,12309,12315,2,12318,12319,1,64830,65048,218,65078,65092,2,65096,65114,18,65116,65118,2,65289,65341,52,65373,65379,3]));static Pf=new K(new Uint32Array([187,8217,8030,8221,8250,29,11779,11781,2,11786,11789,3,11805,11809,4]));static Pi=new K(new Uint32Array([171,8216,8045,8219,8220,1,8223,8249,26,11778,11780,2,11785,11788,3,11804,11808,4]));static Po=new K(new Uint32Array([33,35,1,37,39,1,42,46,2,47,58,11,59,63,4,64,92,28,161,167,6,182,183,1,191,894,703,903,1370,467,1371,1375,1,1417,1472,55,1475,1478,3,1523,1524,1,1545,1546,1,1548,1549,1,1563,1565,2,1566,1567,1,1642,1645,1,1748,1792,44,1793,1805,1,2039,2041,1,2096,2110,1,2142,2404,262,2405,2416,11,2557,2678,121,2800,3191,391,3204,3572,368,3663,3674,11,3675,3844,169,3845,3858,1,3860,3973,113,4048,4052,1,4057,4058,1,4170,4175,1,4347,4960,613,4961,4968,1,5742,5867,125,5868,5869,1,5941,5942,1,6100,6102,1,6104,6106,1,6144,6149,1,6151,6154,1,6468,6469,1,6686,6687,1,6816,6822,1,6824,6829,1,6990,6991,1,7002,7008,1,7037,7039,1,7164,7167,1,7227,7231,1,7294,7295,1,7360,7367,1,7379,8214,835,8215,8224,9,8225,8231,1,8240,8248,1,8251,8254,1,8257,8259,1,8263,8273,1,8275,8277,2,8278,8286,1,11513,11516,1,11518,11519,1,11632,11776,144,11777,11782,5,11783,11784,1,11787,11790,3,11791,11798,1,11800,11801,1,11803,11806,3,11807,11818,11,11819,11822,1,11824,11833,1,11836,11839,1,11841,11843,2,11844,11855,1,11858,11860,1,12289,12291,1,12349,12539,190,42238,42239,1,42509,42511,1,42611,42622,11,42738,42743,1,43124,43127,1,43214,43215,1,43256,43258,1,43260,43310,50,43311,43359,48,43457,43469,1,43486,43487,1,43612,43615,1,43742,43743,1,43760,43761,1,44011,65040,21029,65041,65046,1,65049,65072,23,65093,65094,1,65097,65100,1,65104,65106,1,65108,65111,1,65119,65121,1,65128,65130,2,65131,65281,150,65282,65283,1,65285,65287,1,65290,65294,2,65295,65306,11,65307,65311,4,65312,65340,28,65377,65380,3,65381,65792,411,65793,65794,1,66463,66512,49,66927,67671,744,67871,67903,32,68176,68184,1,68223,68336,113,68337,68342,1,68409,68415,1,68505,68508,1,69461,69465,1,69510,69513,1,69703,69709,1,69819,69820,1,69822,69825,1,69952,69955,1,70004,70005,1,70085,70088,1,70093,70107,14,70109,70111,1,70200,70205,1,70313,70612,299,70613,70615,2,70616,70731,115,70732,70735,1,70746,70747,1,70749,70854,105,71105,71127,1,71233,71235,1,71264,71276,1,71353,71484,131,71485,71486,1,71739,72004,265,72005,72006,1,72162,72255,93,72256,72262,1,72346,72348,1,72350,72354,1,72448,72457,1,72673,72769,96,72770,72773,1,72816,72817,1,73463,73464,1,73539,73551,1,73727,74864,1137,74865,74868,1,77809,77810,1,92782,92783,1,92917,92983,66,92984,92987,1,92996,93549,553,93550,93551,1,93847,93850,1,94178,113823,19645,121479,121483,1,124415,125278,863,125279,125279,1]));static Ps=new K(new Uint32Array([40,91,51,123,3898,3775,3900,5787,1887,8218,8222,4,8261,8317,56,8333,8968,635,8970,9001,31,10088,10100,2,10181,10214,33,10216,10222,2,10627,10647,2,10712,10714,2,10748,11810,1062,11812,11816,2,11842,11861,19,11863,11867,2,12296,12304,2,12308,12314,2,12317,64831,52514,65047,65077,30,65079,65091,2,65095,65113,18,65115,65117,2,65288,65339,51,65371,65375,4,65378,65378,1]));static S=new K(new Uint32Array([36,43,7,60,62,1,94,96,2,124,126,2,162,166,1,168,169,1,172,174,2,175,177,1,180,184,4,215,247,32,706,709,1,722,735,1,741,747,1,749,751,2,752,767,1,885,900,15,901,1014,113,1154,1421,267,1422,1423,1,1542,1544,1,1547,1550,3,1551,1758,207,1769,1789,20,1790,2038,248,2046,2047,1,2184,2546,362,2547,2554,7,2555,2801,246,2928,3059,131,3060,3066,1,3199,3407,208,3449,3647,198,3841,3843,1,3859,3861,2,3862,3863,1,3866,3871,1,3892,3896,2,4030,4037,1,4039,4044,1,4046,4047,1,4053,4056,1,4254,4255,1,5008,5017,1,5741,6107,366,6464,6622,158,6623,6655,1,7009,7018,1,7028,7036,1,8125,8127,2,8128,8129,1,8141,8143,1,8157,8159,1,8173,8175,1,8189,8190,1,8260,8274,14,8314,8316,1,8330,8332,1,8352,8384,1,8448,8449,1,8451,8454,1,8456,8457,1,8468,8470,2,8471,8472,1,8478,8483,1,8485,8489,2,8494,8506,12,8507,8512,5,8513,8516,1,8522,8525,1,8527,8586,59,8587,8592,5,8593,8967,1,8972,9e3,1,9003,9257,1,9280,9290,1,9372,9449,1,9472,10087,1,10132,10180,1,10183,10213,1,10224,10626,1,10649,10711,1,10716,10747,1,10750,11123,1,11126,11157,1,11159,11263,1,11493,11498,1,11856,11857,1,11904,11929,1,11931,12019,1,12032,12245,1,12272,12287,1,12292,12306,14,12307,12320,13,12342,12343,1,12350,12351,1,12443,12444,1,12688,12689,1,12694,12703,1,12736,12773,1,12783,12800,17,12801,12830,1,12842,12871,1,12880,12896,16,12897,12927,1,12938,12976,1,12992,13311,1,19904,19967,1,42128,42182,1,42752,42774,1,42784,42785,1,42889,42890,1,43048,43051,1,43062,43065,1,43639,43641,1,43867,43882,15,43883,64297,20414,64434,64450,1,64832,64847,1,64975,65020,45,65021,65023,1,65122,65124,2,65125,65126,1,65129,65284,155,65291,65308,17,65309,65310,1,65342,65344,2,65372,65374,2,65504,65510,1,65512,65518,1,65532,65533,1,65847,65855,1,65913,65929,1,65932,65934,1,65936,65948,1,65952,66e3,48,66001,66044,1,67703,67704,1,68296,69006,710,69007,71487,2480,73685,73713,1,92988,92991,1,92997,113820,20823,117760,117999,1,118016,118451,1,118608,118723,1,118784,119029,1,119040,119078,1,119081,119140,1,119146,119148,1,119171,119172,1,119180,119209,1,119214,119274,1,119296,119361,1,119365,119552,187,119553,119638,1,120513,120539,26,120571,120597,26,120629,120655,26,120687,120713,26,120745,120771,26,120832,121343,1,121399,121402,1,121453,121460,1,121462,121475,1,121477,121478,1,123215,123647,432,126124,126128,4,126254,126704,450,126705,126976,271,126977,127019,1,127024,127123,1,127136,127150,1,127153,127167,1,127169,127183,1,127185,127221,1,127245,127405,1,127462,127490,1,127504,127547,1,127552,127560,1,127568,127569,1,127584,127589,1,127744,128727,1,128732,128748,1,128752,128764,1,128768,128886,1,128891,128985,1,128992,129003,1,129008,129024,16,129025,129035,1,129040,129095,1,129104,129113,1,129120,129159,1,129168,129197,1,129200,129211,1,129216,129217,1,129280,129619,1,129632,129645,1,129648,129660,1,129664,129673,1,129679,129734,1,129742,129756,1,129759,129769,1,129776,129784,1,129792,129938,1,129940,130031,1]));static Sc=new K(new Uint32Array([36,162,126,163,165,1,1423,1547,124,2046,2047,1,2546,2547,1,2555,2801,246,3065,3647,582,6107,8352,2245,8353,8384,1,43064,65020,21956,65129,65284,155,65504,65505,1,65509,65510,1,73693,73696,1,123647,126128,2481]));static Sk=new K(new Uint32Array([94,96,2,168,175,7,180,184,4,706,709,1,722,735,1,741,747,1,749,751,2,752,767,1,885,900,15,901,2184,1283,8125,8127,2,8128,8129,1,8141,8143,1,8157,8159,1,8173,8175,1,8189,8190,1,12443,12444,1,42752,42774,1,42784,42785,1,42889,42890,1,43867,43882,15,43883,64434,20551,64435,64450,1,65342,65344,2,65507,127995,62488,127996,127999,1]));static Sm=new K(new Uint32Array([43,60,17,61,62,1,124,126,2,172,177,5,215,247,32,1014,1542,528,1543,1544,1,8260,8274,14,8314,8316,1,8330,8332,1,8472,8512,40,8513,8516,1,8523,8592,69,8593,8596,1,8602,8603,1,8608,8614,3,8622,8654,32,8655,8658,3,8660,8692,32,8693,8959,1,8992,8993,1,9084,9115,31,9116,9139,1,9180,9185,1,9655,9665,10,9720,9727,1,9839,10176,337,10177,10180,1,10183,10213,1,10224,10239,1,10496,10626,1,10649,10711,1,10716,10747,1,10750,11007,1,11056,11076,1,11079,11084,1,64297,65122,825,65124,65126,1,65291,65308,17,65309,65310,1,65372,65374,2,65506,65513,7,65514,65516,1,69006,69007,1,120513,120539,26,120571,120597,26,120629,120655,26,120687,120713,26,120745,120771,26,126704,126705,1]));static So=new K(new Uint32Array([166,169,3,174,176,2,1154,1421,267,1422,1550,128,1551,1758,207,1769,1789,20,1790,2038,248,2554,2928,374,3059,3064,1,3066,3199,133,3407,3449,42,3841,3843,1,3859,3861,2,3862,3863,1,3866,3871,1,3892,3896,2,4030,4037,1,4039,4044,1,4046,4047,1,4053,4056,1,4254,4255,1,5008,5017,1,5741,6464,723,6622,6655,1,7009,7018,1,7028,7036,1,8448,8449,1,8451,8454,1,8456,8457,1,8468,8470,2,8471,8478,7,8479,8483,1,8485,8489,2,8494,8506,12,8507,8522,15,8524,8525,1,8527,8586,59,8587,8597,10,8598,8601,1,8604,8607,1,8609,8610,1,8612,8613,1,8615,8621,1,8623,8653,1,8656,8657,1,8659,8661,2,8662,8691,1,8960,8967,1,8972,8991,1,8994,9e3,1,9003,9083,1,9085,9114,1,9140,9179,1,9186,9257,1,9280,9290,1,9372,9449,1,9472,9654,1,9656,9664,1,9666,9719,1,9728,9838,1,9840,10087,1,10132,10175,1,10240,10495,1,11008,11055,1,11077,11078,1,11085,11123,1,11126,11157,1,11159,11263,1,11493,11498,1,11856,11857,1,11904,11929,1,11931,12019,1,12032,12245,1,12272,12287,1,12292,12306,14,12307,12320,13,12342,12343,1,12350,12351,1,12688,12689,1,12694,12703,1,12736,12773,1,12783,12800,17,12801,12830,1,12842,12871,1,12880,12896,16,12897,12927,1,12938,12976,1,12992,13311,1,19904,19967,1,42128,42182,1,43048,43051,1,43062,43063,1,43065,43639,574,43640,43641,1,64832,64847,1,64975,65021,46,65022,65023,1,65508,65512,4,65517,65518,1,65532,65533,1,65847,65855,1,65913,65929,1,65932,65934,1,65936,65948,1,65952,66e3,48,66001,66044,1,67703,67704,1,68296,71487,3191,73685,73692,1,73697,73713,1,92988,92991,1,92997,113820,20823,117760,117999,1,118016,118451,1,118608,118723,1,118784,119029,1,119040,119078,1,119081,119140,1,119146,119148,1,119171,119172,1,119180,119209,1,119214,119274,1,119296,119361,1,119365,119552,187,119553,119638,1,120832,121343,1,121399,121402,1,121453,121460,1,121462,121475,1,121477,121478,1,123215,126124,2909,126254,126976,722,126977,127019,1,127024,127123,1,127136,127150,1,127153,127167,1,127169,127183,1,127185,127221,1,127245,127405,1,127462,127490,1,127504,127547,1,127552,127560,1,127568,127569,1,127584,127589,1,127744,127994,1,128e3,128727,1,128732,128748,1,128752,128764,1,128768,128886,1,128891,128985,1,128992,129003,1,129008,129024,16,129025,129035,1,129040,129095,1,129104,129113,1,129120,129159,1,129168,129197,1,129200,129211,1,129216,129217,1,129280,129619,1,129632,129645,1,129648,129660,1,129664,129673,1,129679,129734,1,129742,129756,1,129759,129769,1,129776,129784,1,129792,129938,1,129940,130031,1]));static Z=new K(new Uint32Array([32,160,128,5760,8192,2432,8193,8202,1,8232,8233,1,8239,8287,48,12288,12288,1]));static Zl=new K(new Uint32Array([8232,8232,1]));static Zp=new K(new Uint32Array([8233,8233,1]));static Zs=new K(new Uint32Array([32,160,128,5760,8192,2432,8193,8202,1,8239,8287,48,12288,12288,1]));static Adlam=new K(new Uint32Array([125184,125259,1,125264,125273,1,125278,125279,1]));static Ahom=new K(new Uint32Array([71424,71450,1,71453,71467,1,71472,71494,1]));static Anatolian_Hieroglyphs=new K(new Uint32Array([82944,83526,1]));static Arabic=new K(new Uint32Array([1536,1540,1,1542,1547,1,1549,1562,1,1564,1566,1,1568,1599,1,1601,1610,1,1622,1647,1,1649,1756,1,1758,1791,1,1872,1919,1,2160,2190,1,2192,2193,1,2199,2273,1,2275,2303,1,64336,64450,1,64467,64829,1,64832,64911,1,64914,64967,1,64975,65008,33,65009,65023,1,65136,65140,1,65142,65276,1,69216,69246,1,69314,69316,1,69372,69375,1,126464,126467,1,126469,126495,1,126497,126498,1,126500,126503,3,126505,126514,1,126516,126519,1,126521,126523,2,126530,126535,5,126537,126541,2,126542,126543,1,126545,126546,1,126548,126551,3,126553,126561,2,126562,126564,2,126567,126570,1,126572,126578,1,126580,126583,1,126585,126588,1,126590,126592,2,126593,126601,1,126603,126619,1,126625,126627,1,126629,126633,1,126635,126651,1,126704,126705,1]));static Armenian=new K(new Uint32Array([1329,1366,1,1369,1418,1,1421,1423,1,64275,64279,1]));static Avestan=new K(new Uint32Array([68352,68405,1,68409,68415,1]));static Balinese=new K(new Uint32Array([6912,6988,1,6990,7039,1]));static Bamum=new K(new Uint32Array([42656,42743,1,92160,92728,1]));static Bassa_Vah=new K(new Uint32Array([92880,92909,1,92912,92917,1]));static Batak=new K(new Uint32Array([7104,7155,1,7164,7167,1]));static Bengali=new K(new Uint32Array([2432,2435,1,2437,2444,1,2447,2448,1,2451,2472,1,2474,2480,1,2482,2486,4,2487,2489,1,2492,2500,1,2503,2504,1,2507,2510,1,2519,2524,5,2525,2527,2,2528,2531,1,2534,2558,1]));static Bhaiksuki=new K(new Uint32Array([72704,72712,1,72714,72758,1,72760,72773,1,72784,72812,1]));static Bopomofo=new K(new Uint32Array([746,747,1,12549,12591,1,12704,12735,1]));static Brahmi=new K(new Uint32Array([69632,69709,1,69714,69749,1,69759,69759,1]));static Braille=new K(new Uint32Array([10240,10495,1]));static Buginese=new K(new Uint32Array([6656,6683,1,6686,6687,1]));static Buhid=new K(new Uint32Array([5952,5971,1]));static Canadian_Aboriginal=new K(new Uint32Array([5120,5759,1,6320,6389,1,72368,72383,1]));static Carian=new K(new Uint32Array([66208,66256,1]));static Caucasian_Albanian=new K(new Uint32Array([66864,66915,1,66927,66927,1]));static Chakma=new K(new Uint32Array([69888,69940,1,69942,69959,1]));static Cham=new K(new Uint32Array([43520,43574,1,43584,43597,1,43600,43609,1,43612,43615,1]));static Cherokee=new K(new Uint32Array([5024,5109,1,5112,5117,1,43888,43967,1]));static Chorasmian=new K(new Uint32Array([69552,69579,1]));static Common=new K(new Uint32Array([0,64,1,91,96,1,123,169,1,171,185,1,187,191,1,215,247,32,697,735,1,741,745,1,748,767,1,884,894,10,901,903,2,1541,1548,7,1563,1567,4,1600,1757,157,2274,2404,130,2405,3647,1242,4053,4056,1,4347,5867,1520,5868,5869,1,5941,5942,1,6146,6147,1,6149,7379,1230,7393,7401,8,7402,7404,1,7406,7411,1,7413,7415,1,7418,8192,774,8193,8203,1,8206,8292,1,8294,8304,1,8308,8318,1,8320,8334,1,8352,8384,1,8448,8485,1,8487,8489,1,8492,8497,1,8499,8525,1,8527,8543,1,8585,8587,1,8592,9257,1,9280,9290,1,9312,10239,1,10496,11123,1,11126,11157,1,11159,11263,1,11776,11869,1,12272,12292,1,12294,12296,2,12297,12320,1,12336,12343,1,12348,12351,1,12443,12444,1,12448,12539,91,12540,12688,148,12689,12703,1,12736,12773,1,12783,12832,49,12833,12895,1,12927,13007,1,13055,13144,89,13145,13311,1,19904,19967,1,42752,42785,1,42888,42890,1,43056,43065,1,43310,43471,161,43867,43882,15,43883,64830,20947,64831,65040,209,65041,65049,1,65072,65106,1,65108,65126,1,65128,65131,1,65279,65281,2,65282,65312,1,65339,65344,1,65371,65381,1,65392,65438,46,65439,65504,65,65505,65510,1,65512,65518,1,65529,65533,1,65792,65794,1,65799,65843,1,65847,65855,1,65936,65948,1,66e3,66044,1,66273,66299,1,113824,113827,1,117760,118009,1,118016,118451,1,118608,118723,1,118784,119029,1,119040,119078,1,119081,119142,1,119146,119162,1,119171,119172,1,119180,119209,1,119214,119274,1,119488,119507,1,119520,119539,1,119552,119638,1,119648,119672,1,119808,119892,1,119894,119964,1,119966,119967,1,119970,119973,3,119974,119977,3,119978,119980,1,119982,119993,1,119995,119997,2,119998,120003,1,120005,120069,1,120071,120074,1,120077,120084,1,120086,120092,1,120094,120121,1,120123,120126,1,120128,120132,1,120134,120138,4,120139,120144,1,120146,120485,1,120488,120779,1,120782,120831,1,126065,126132,1,126209,126269,1,126976,127019,1,127024,127123,1,127136,127150,1,127153,127167,1,127169,127183,1,127185,127221,1,127232,127405,1,127462,127487,1,127489,127490,1,127504,127547,1,127552,127560,1,127568,127569,1,127584,127589,1,127744,128727,1,128732,128748,1,128752,128764,1,128768,128886,1,128891,128985,1,128992,129003,1,129008,129024,16,129025,129035,1,129040,129095,1,129104,129113,1,129120,129159,1,129168,129197,1,129200,129211,1,129216,129217,1,129280,129619,1,129632,129645,1,129648,129660,1,129664,129673,1,129679,129734,1,129742,129756,1,129759,129769,1,129776,129784,1,129792,129938,1,129940,130041,1,917505,917536,31,917537,917631,1]));static foldCommon=new K(new Uint32Array([924,956,32]));static Coptic=new K(new Uint32Array([994,1007,1,11392,11507,1,11513,11519,1]));static Cuneiform=new K(new Uint32Array([73728,74649,1,74752,74862,1,74864,74868,1,74880,75075,1]));static Cypriot=new K(new Uint32Array([67584,67589,1,67592,67594,2,67595,67637,1,67639,67640,1,67644,67647,3]));static Cypro_Minoan=new K(new Uint32Array([77712,77810,1]));static Cyrillic=new K(new Uint32Array([1024,1156,1,1159,1327,1,7296,7306,1,7467,7544,77,11744,11775,1,42560,42655,1,65070,65071,1,122928,122989,1,123023,123023,1]));static Deseret=new K(new Uint32Array([66560,66639,1]));static Devanagari=new K(new Uint32Array([2304,2384,1,2389,2403,1,2406,2431,1,43232,43263,1,72448,72457,1]));static Dives_Akuru=new K(new Uint32Array([71936,71942,1,71945,71948,3,71949,71955,1,71957,71958,1,71960,71989,1,71991,71992,1,71995,72006,1,72016,72025,1]));static Dogra=new K(new Uint32Array([71680,71739,1]));static Duployan=new K(new Uint32Array([113664,113770,1,113776,113788,1,113792,113800,1,113808,113817,1,113820,113823,1]));static Egyptian_Hieroglyphs=new K(new Uint32Array([77824,78933,1,78944,82938,1]));static Elbasan=new K(new Uint32Array([66816,66855,1]));static Elymaic=new K(new Uint32Array([69600,69622,1]));static Ethiopic=new K(new Uint32Array([4608,4680,1,4682,4685,1,4688,4694,1,4696,4698,2,4699,4701,1,4704,4744,1,4746,4749,1,4752,4784,1,4786,4789,1,4792,4798,1,4800,4802,2,4803,4805,1,4808,4822,1,4824,4880,1,4882,4885,1,4888,4954,1,4957,4988,1,4992,5017,1,11648,11670,1,11680,11686,1,11688,11694,1,11696,11702,1,11704,11710,1,11712,11718,1,11720,11726,1,11728,11734,1,11736,11742,1,43777,43782,1,43785,43790,1,43793,43798,1,43808,43814,1,43816,43822,1,124896,124902,1,124904,124907,1,124909,124910,1,124912,124926,1]));static Garay=new K(new Uint32Array([68928,68965,1,68969,68997,1,69006,69007,1]));static Georgian=new K(new Uint32Array([4256,4293,1,4295,4301,6,4304,4346,1,4348,4351,1,7312,7354,1,7357,7359,1,11520,11557,1,11559,11565,6]));static Glagolitic=new K(new Uint32Array([11264,11359,1,122880,122886,1,122888,122904,1,122907,122913,1,122915,122916,1,122918,122922,1]));static Gothic=new K(new Uint32Array([66352,66378,1]));static Grantha=new K(new Uint32Array([70400,70403,1,70405,70412,1,70415,70416,1,70419,70440,1,70442,70448,1,70450,70451,1,70453,70457,1,70460,70468,1,70471,70472,1,70475,70477,1,70480,70487,7,70493,70499,1,70502,70508,1,70512,70516,1]));static Greek=new K(new Uint32Array([880,883,1,885,887,1,890,893,1,895,900,5,902,904,2,905,906,1,908,910,2,911,929,1,931,993,1,1008,1023,1,7462,7466,1,7517,7521,1,7526,7530,1,7615,7936,321,7937,7957,1,7960,7965,1,7968,8005,1,8008,8013,1,8016,8023,1,8025,8031,2,8032,8061,1,8064,8116,1,8118,8132,1,8134,8147,1,8150,8155,1,8157,8175,1,8178,8180,1,8182,8190,1,8486,43877,35391,65856,65934,1,65952,119296,53344,119297,119365,1]));static foldGreek=new K(new Uint32Array([181,837,656]));static Gujarati=new K(new Uint32Array([2689,2691,1,2693,2701,1,2703,2705,1,2707,2728,1,2730,2736,1,2738,2739,1,2741,2745,1,2748,2757,1,2759,2761,1,2763,2765,1,2768,2784,16,2785,2787,1,2790,2801,1,2809,2815,1]));static Gunjala_Gondi=new K(new Uint32Array([73056,73061,1,73063,73064,1,73066,73102,1,73104,73105,1,73107,73112,1,73120,73129,1]));static Gurmukhi=new K(new Uint32Array([2561,2563,1,2565,2570,1,2575,2576,1,2579,2600,1,2602,2608,1,2610,2611,1,2613,2614,1,2616,2617,1,2620,2622,2,2623,2626,1,2631,2632,1,2635,2637,1,2641,2649,8,2650,2652,1,2654,2662,8,2663,2678,1]));static Gurung_Khema=new K(new Uint32Array([90368,90425,1]));static Han=new K(new Uint32Array([11904,11929,1,11931,12019,1,12032,12245,1,12293,12295,2,12321,12329,1,12344,12347,1,13312,19903,1,19968,40959,1,63744,64109,1,64112,64217,1,94178,94179,1,94192,94193,1,131072,173791,1,173824,177977,1,177984,178205,1,178208,183969,1,183984,191456,1,191472,192093,1,194560,195101,1,196608,201546,1,201552,205743,1]));static Hangul=new K(new Uint32Array([4352,4607,1,12334,12335,1,12593,12686,1,12800,12830,1,12896,12926,1,43360,43388,1,44032,55203,1,55216,55238,1,55243,55291,1,65440,65470,1,65474,65479,1,65482,65487,1,65490,65495,1,65498,65500,1]));static Hanifi_Rohingya=new K(new Uint32Array([68864,68903,1,68912,68921,1]));static Hanunoo=new K(new Uint32Array([5920,5940,1]));static Hatran=new K(new Uint32Array([67808,67826,1,67828,67829,1,67835,67839,1]));static Hebrew=new K(new Uint32Array([1425,1479,1,1488,1514,1,1519,1524,1,64285,64310,1,64312,64316,1,64318,64320,2,64321,64323,2,64324,64326,2,64327,64335,1]));static Hiragana=new K(new Uint32Array([12353,12438,1,12445,12447,1,110593,110879,1,110898,110928,30,110929,110930,1,127488,127488,1]));static Imperial_Aramaic=new K(new Uint32Array([67648,67669,1,67671,67679,1]));static Inherited=new K(new Uint32Array([768,879,1,1157,1158,1,1611,1621,1,1648,2385,737,2386,2388,1,6832,6862,1,7376,7378,1,7380,7392,1,7394,7400,1,7405,7412,7,7416,7417,1,7616,7679,1,8204,8205,1,8400,8432,1,12330,12333,1,12441,12442,1,65024,65039,1,65056,65069,1,66045,66272,227,70459,118528,48069,118529,118573,1,118576,118598,1,119143,119145,1,119163,119170,1,119173,119179,1,119210,119213,1,917760,917999,1]));static foldInherited=new K(new Uint32Array([921,953,32,8126,8126,1]));static Inscriptional_Pahlavi=new K(new Uint32Array([68448,68466,1,68472,68479,1]));static Inscriptional_Parthian=new K(new Uint32Array([68416,68437,1,68440,68447,1]));static Javanese=new K(new Uint32Array([43392,43469,1,43472,43481,1,43486,43487,1]));static Kaithi=new K(new Uint32Array([69760,69826,1,69837,69837,1]));static Kannada=new K(new Uint32Array([3200,3212,1,3214,3216,1,3218,3240,1,3242,3251,1,3253,3257,1,3260,3268,1,3270,3272,1,3274,3277,1,3285,3286,1,3293,3294,1,3296,3299,1,3302,3311,1,3313,3315,1]));static Katakana=new K(new Uint32Array([12449,12538,1,12541,12543,1,12784,12799,1,13008,13054,1,13056,13143,1,65382,65391,1,65393,65437,1,110576,110579,1,110581,110587,1,110589,110590,1,110592,110880,288,110881,110882,1,110933,110948,15,110949,110951,1]));static Kawi=new K(new Uint32Array([73472,73488,1,73490,73530,1,73534,73562,1]));static Kayah_Li=new K(new Uint32Array([43264,43309,1,43311,43311,1]));static Kharoshthi=new K(new Uint32Array([68096,68099,1,68101,68102,1,68108,68115,1,68117,68119,1,68121,68149,1,68152,68154,1,68159,68168,1,68176,68184,1]));static Khitan_Small_Script=new K(new Uint32Array([94180,101120,6940,101121,101589,1,101631,101631,1]));static Khmer=new K(new Uint32Array([6016,6109,1,6112,6121,1,6128,6137,1,6624,6655,1]));static Khojki=new K(new Uint32Array([70144,70161,1,70163,70209,1]));static Khudawadi=new K(new Uint32Array([70320,70378,1,70384,70393,1]));static Kirat_Rai=new K(new Uint32Array([93504,93561,1]));static Lao=new K(new Uint32Array([3713,3714,1,3716,3718,2,3719,3722,1,3724,3747,1,3749,3751,2,3752,3773,1,3776,3780,1,3782,3784,2,3785,3790,1,3792,3801,1,3804,3807,1]));static Latin=new K(new Uint32Array([65,90,1,97,122,1,170,186,16,192,214,1,216,246,1,248,696,1,736,740,1,7424,7461,1,7468,7516,1,7522,7525,1,7531,7543,1,7545,7614,1,7680,7935,1,8305,8319,14,8336,8348,1,8490,8491,1,8498,8526,28,8544,8584,1,11360,11391,1,42786,42887,1,42891,42957,1,42960,42961,1,42963,42965,2,42966,42972,1,42994,43007,1,43824,43866,1,43868,43876,1,43878,43881,1,64256,64262,1,65313,65338,1,65345,65370,1,67456,67461,1,67463,67504,1,67506,67514,1,122624,122654,1,122661,122666,1]));static Lepcha=new K(new Uint32Array([7168,7223,1,7227,7241,1,7245,7247,1]));static Limbu=new K(new Uint32Array([6400,6430,1,6432,6443,1,6448,6459,1,6464,6468,4,6469,6479,1]));static Linear_A=new K(new Uint32Array([67072,67382,1,67392,67413,1,67424,67431,1]));static Linear_B=new K(new Uint32Array([65536,65547,1,65549,65574,1,65576,65594,1,65596,65597,1,65599,65613,1,65616,65629,1,65664,65786,1]));static Lisu=new K(new Uint32Array([42192,42239,1,73648,73648,1]));static Lycian=new K(new Uint32Array([66176,66204,1]));static Lydian=new K(new Uint32Array([67872,67897,1,67903,67903,1]));static Mahajani=new K(new Uint32Array([69968,70006,1]));static Makasar=new K(new Uint32Array([73440,73464,1]));static Malayalam=new K(new Uint32Array([3328,3340,1,3342,3344,1,3346,3396,1,3398,3400,1,3402,3407,1,3412,3427,1,3430,3455,1]));static Mandaic=new K(new Uint32Array([2112,2139,1,2142,2142,1]));static Manichaean=new K(new Uint32Array([68288,68326,1,68331,68342,1]));static Marchen=new K(new Uint32Array([72816,72847,1,72850,72871,1,72873,72886,1]));static Masaram_Gondi=new K(new Uint32Array([72960,72966,1,72968,72969,1,72971,73014,1,73018,73020,2,73021,73023,2,73024,73031,1,73040,73049,1]));static Medefaidrin=new K(new Uint32Array([93760,93850,1]));static Meetei_Mayek=new K(new Uint32Array([43744,43766,1,43968,44013,1,44016,44025,1]));static Mende_Kikakui=new K(new Uint32Array([124928,125124,1,125127,125142,1]));static Meroitic_Cursive=new K(new Uint32Array([68e3,68023,1,68028,68047,1,68050,68095,1]));static Meroitic_Hieroglyphs=new K(new Uint32Array([67968,67999,1]));static Miao=new K(new Uint32Array([93952,94026,1,94031,94087,1,94095,94111,1]));static Modi=new K(new Uint32Array([71168,71236,1,71248,71257,1]));static Mongolian=new K(new Uint32Array([6144,6145,1,6148,6150,2,6151,6169,1,6176,6264,1,6272,6314,1,71264,71276,1]));static Mro=new K(new Uint32Array([92736,92766,1,92768,92777,1,92782,92783,1]));static Multani=new K(new Uint32Array([70272,70278,1,70280,70282,2,70283,70285,1,70287,70301,1,70303,70313,1]));static Myanmar=new K(new Uint32Array([4096,4255,1,43488,43518,1,43616,43647,1,71376,71395,1]));static Nabataean=new K(new Uint32Array([67712,67742,1,67751,67759,1]));static Nag_Mundari=new K(new Uint32Array([124112,124153,1]));static Nandinagari=new K(new Uint32Array([72096,72103,1,72106,72151,1,72154,72164,1]));static New_Tai_Lue=new K(new Uint32Array([6528,6571,1,6576,6601,1,6608,6618,1,6622,6623,1]));static Newa=new K(new Uint32Array([70656,70747,1,70749,70753,1]));static Nko=new K(new Uint32Array([1984,2042,1,2045,2047,1]));static Nushu=new K(new Uint32Array([94177,110960,16783,110961,111355,1]));static Nyiakeng_Puachue_Hmong=new K(new Uint32Array([123136,123180,1,123184,123197,1,123200,123209,1,123214,123215,1]));static Ogham=new K(new Uint32Array([5760,5788,1]));static Ol_Chiki=new K(new Uint32Array([7248,7295,1]));static Ol_Onal=new K(new Uint32Array([124368,124410,1,124415,124415,1]));static Old_Hungarian=new K(new Uint32Array([68736,68786,1,68800,68850,1,68858,68863,1]));static Old_Italic=new K(new Uint32Array([66304,66339,1,66349,66351,1]));static Old_North_Arabian=new K(new Uint32Array([68224,68255,1]));static Old_Permic=new K(new Uint32Array([66384,66426,1]));static Old_Persian=new K(new Uint32Array([66464,66499,1,66504,66517,1]));static Old_Sogdian=new K(new Uint32Array([69376,69415,1]));static Old_South_Arabian=new K(new Uint32Array([68192,68223,1]));static Old_Turkic=new K(new Uint32Array([68608,68680,1]));static Old_Uyghur=new K(new Uint32Array([69488,69513,1]));static Oriya=new K(new Uint32Array([2817,2819,1,2821,2828,1,2831,2832,1,2835,2856,1,2858,2864,1,2866,2867,1,2869,2873,1,2876,2884,1,2887,2888,1,2891,2893,1,2901,2903,1,2908,2909,1,2911,2915,1,2918,2935,1]));static Osage=new K(new Uint32Array([66736,66771,1,66776,66811,1]));static Osmanya=new K(new Uint32Array([66688,66717,1,66720,66729,1]));static Pahawh_Hmong=new K(new Uint32Array([92928,92997,1,93008,93017,1,93019,93025,1,93027,93047,1,93053,93071,1]));static Palmyrene=new K(new Uint32Array([67680,67711,1]));static Pau_Cin_Hau=new K(new Uint32Array([72384,72440,1]));static Phags_Pa=new K(new Uint32Array([43072,43127,1]));static Phoenician=new K(new Uint32Array([67840,67867,1,67871,67871,1]));static Psalter_Pahlavi=new K(new Uint32Array([68480,68497,1,68505,68508,1,68521,68527,1]));static Rejang=new K(new Uint32Array([43312,43347,1,43359,43359,1]));static Runic=new K(new Uint32Array([5792,5866,1,5870,5880,1]));static Samaritan=new K(new Uint32Array([2048,2093,1,2096,2110,1]));static Saurashtra=new K(new Uint32Array([43136,43205,1,43214,43225,1]));static Sharada=new K(new Uint32Array([70016,70111,1]));static Shavian=new K(new Uint32Array([66640,66687,1]));static Siddham=new K(new Uint32Array([71040,71093,1,71096,71133,1]));static SignWriting=new K(new Uint32Array([120832,121483,1,121499,121503,1,121505,121519,1]));static Sinhala=new K(new Uint32Array([3457,3459,1,3461,3478,1,3482,3505,1,3507,3515,1,3517,3520,3,3521,3526,1,3530,3535,5,3536,3540,1,3542,3544,2,3545,3551,1,3558,3567,1,3570,3572,1,70113,70132,1]));static Sogdian=new K(new Uint32Array([69424,69465,1]));static Sora_Sompeng=new K(new Uint32Array([69840,69864,1,69872,69881,1]));static Soyombo=new K(new Uint32Array([72272,72354,1]));static Sundanese=new K(new Uint32Array([7040,7103,1,7360,7367,1]));static Sunuwar=new K(new Uint32Array([72640,72673,1,72688,72697,1]));static Syloti_Nagri=new K(new Uint32Array([43008,43052,1]));static Syriac=new K(new Uint32Array([1792,1805,1,1807,1866,1,1869,1871,1,2144,2154,1]));static Tagalog=new K(new Uint32Array([5888,5909,1,5919,5919,1]));static Tagbanwa=new K(new Uint32Array([5984,5996,1,5998,6e3,1,6002,6003,1]));static Tai_Le=new K(new Uint32Array([6480,6509,1,6512,6516,1]));static Tai_Tham=new K(new Uint32Array([6688,6750,1,6752,6780,1,6783,6793,1,6800,6809,1,6816,6829,1]));static Tai_Viet=new K(new Uint32Array([43648,43714,1,43739,43743,1]));static Takri=new K(new Uint32Array([71296,71353,1,71360,71369,1]));static Tamil=new K(new Uint32Array([2946,2947,1,2949,2954,1,2958,2960,1,2962,2965,1,2969,2970,1,2972,2974,2,2975,2979,4,2980,2984,4,2985,2986,1,2990,3001,1,3006,3010,1,3014,3016,1,3018,3021,1,3024,3031,7,3046,3066,1,73664,73713,1,73727,73727,1]));static Tangsa=new K(new Uint32Array([92784,92862,1,92864,92873,1]));static Tangut=new K(new Uint32Array([94176,94208,32,94209,100343,1,100352,101119,1,101632,101640,1]));static Telugu=new K(new Uint32Array([3072,3084,1,3086,3088,1,3090,3112,1,3114,3129,1,3132,3140,1,3142,3144,1,3146,3149,1,3157,3158,1,3160,3162,1,3165,3168,3,3169,3171,1,3174,3183,1,3191,3199,1]));static Thaana=new K(new Uint32Array([1920,1969,1]));static Thai=new K(new Uint32Array([3585,3642,1,3648,3675,1]));static Tibetan=new K(new Uint32Array([3840,3911,1,3913,3948,1,3953,3991,1,3993,4028,1,4030,4044,1,4046,4052,1,4057,4058,1]));static Tifinagh=new K(new Uint32Array([11568,11623,1,11631,11632,1,11647,11647,1]));static Tirhuta=new K(new Uint32Array([70784,70855,1,70864,70873,1]));static Todhri=new K(new Uint32Array([67008,67059,1]));static Toto=new K(new Uint32Array([123536,123566,1]));static Tulu_Tigalari=new K(new Uint32Array([70528,70537,1,70539,70542,3,70544,70581,1,70583,70592,1,70594,70597,3,70599,70602,1,70604,70613,1,70615,70616,1,70625,70626,1]));static Ugaritic=new K(new Uint32Array([66432,66461,1,66463,66463,1]));static Vai=new K(new Uint32Array([42240,42539,1]));static Vithkuqi=new K(new Uint32Array([66928,66938,1,66940,66954,1,66956,66962,1,66964,66965,1,66967,66977,1,66979,66993,1,66995,67001,1,67003,67004,1]));static Wancho=new K(new Uint32Array([123584,123641,1,123647,123647,1]));static Warang_Citi=new K(new Uint32Array([71840,71922,1,71935,71935,1]));static Yezidi=new K(new Uint32Array([69248,69289,1,69291,69293,1,69296,69297,1]));static Yi=new K(new Uint32Array([40960,42124,1,42128,42182,1]));static Zanabazar_Square=new K(new Uint32Array([72192,72263,1]));static CATEGORIES=new Map([[`C`,e.C],[`Cc`,e.Cc],[`Cf`,e.Cf],[`Co`,e.Co],[`Cs`,e.Cs],[`L`,e.L],[`Ll`,e.Ll],[`Lm`,e.Lm],[`Lo`,e.Lo],[`Lt`,e.Lt],[`Lu`,e.Lu],[`M`,e.M],[`Mc`,e.Mc],[`Me`,e.Me],[`Mn`,e.Mn],[`N`,e.N],[`Nd`,e.Nd],[`Nl`,e.Nl],[`No`,e.No],[`P`,e.P],[`Pc`,e.Pc],[`Pd`,e.Pd],[`Pe`,e.Pe],[`Pf`,e.Pf],[`Pi`,e.Pi],[`Po`,e.Po],[`Ps`,e.Ps],[`S`,e.S],[`Sc`,e.Sc],[`Sk`,e.Sk],[`Sm`,e.Sm],[`So`,e.So],[`Z`,e.Z],[`Zl`,e.Zl],[`Zp`,e.Zp],[`Zs`,e.Zs]]);static SCRIPTS=new Map([[`Adlam`,e.Adlam],[`Ahom`,e.Ahom],[`Anatolian_Hieroglyphs`,e.Anatolian_Hieroglyphs],[`Arabic`,e.Arabic],[`Armenian`,e.Armenian],[`Avestan`,e.Avestan],[`Balinese`,e.Balinese],[`Bamum`,e.Bamum],[`Bassa_Vah`,e.Bassa_Vah],[`Batak`,e.Batak],[`Bengali`,e.Bengali],[`Bhaiksuki`,e.Bhaiksuki],[`Bopomofo`,e.Bopomofo],[`Brahmi`,e.Brahmi],[`Braille`,e.Braille],[`Buginese`,e.Buginese],[`Buhid`,e.Buhid],[`Canadian_Aboriginal`,e.Canadian_Aboriginal],[`Carian`,e.Carian],[`Caucasian_Albanian`,e.Caucasian_Albanian],[`Chakma`,e.Chakma],[`Cham`,e.Cham],[`Cherokee`,e.Cherokee],[`Chorasmian`,e.Chorasmian],[`Common`,e.Common],[`Coptic`,e.Coptic],[`Cuneiform`,e.Cuneiform],[`Cypriot`,e.Cypriot],[`Cypro_Minoan`,e.Cypro_Minoan],[`Cyrillic`,e.Cyrillic],[`Deseret`,e.Deseret],[`Devanagari`,e.Devanagari],[`Dives_Akuru`,e.Dives_Akuru],[`Dogra`,e.Dogra],[`Duployan`,e.Duployan],[`Egyptian_Hieroglyphs`,e.Egyptian_Hieroglyphs],[`Elbasan`,e.Elbasan],[`Elymaic`,e.Elymaic],[`Ethiopic`,e.Ethiopic],[`Garay`,e.Garay],[`Georgian`,e.Georgian],[`Glagolitic`,e.Glagolitic],[`Gothic`,e.Gothic],[`Grantha`,e.Grantha],[`Greek`,e.Greek],[`Gujarati`,e.Gujarati],[`Gunjala_Gondi`,e.Gunjala_Gondi],[`Gurmukhi`,e.Gurmukhi],[`Gurung_Khema`,e.Gurung_Khema],[`Han`,e.Han],[`Hangul`,e.Hangul],[`Hanifi_Rohingya`,e.Hanifi_Rohingya],[`Hanunoo`,e.Hanunoo],[`Hatran`,e.Hatran],[`Hebrew`,e.Hebrew],[`Hiragana`,e.Hiragana],[`Imperial_Aramaic`,e.Imperial_Aramaic],[`Inherited`,e.Inherited],[`Inscriptional_Pahlavi`,e.Inscriptional_Pahlavi],[`Inscriptional_Parthian`,e.Inscriptional_Parthian],[`Javanese`,e.Javanese],[`Kaithi`,e.Kaithi],[`Kannada`,e.Kannada],[`Katakana`,e.Katakana],[`Kawi`,e.Kawi],[`Kayah_Li`,e.Kayah_Li],[`Kharoshthi`,e.Kharoshthi],[`Khitan_Small_Script`,e.Khitan_Small_Script],[`Khmer`,e.Khmer],[`Khojki`,e.Khojki],[`Khudawadi`,e.Khudawadi],[`Kirat_Rai`,e.Kirat_Rai],[`Lao`,e.Lao],[`Latin`,e.Latin],[`Lepcha`,e.Lepcha],[`Limbu`,e.Limbu],[`Linear_A`,e.Linear_A],[`Linear_B`,e.Linear_B],[`Lisu`,e.Lisu],[`Lycian`,e.Lycian],[`Lydian`,e.Lydian],[`Mahajani`,e.Mahajani],[`Makasar`,e.Makasar],[`Malayalam`,e.Malayalam],[`Mandaic`,e.Mandaic],[`Manichaean`,e.Manichaean],[`Marchen`,e.Marchen],[`Masaram_Gondi`,e.Masaram_Gondi],[`Medefaidrin`,e.Medefaidrin],[`Meetei_Mayek`,e.Meetei_Mayek],[`Mende_Kikakui`,e.Mende_Kikakui],[`Meroitic_Cursive`,e.Meroitic_Cursive],[`Meroitic_Hieroglyphs`,e.Meroitic_Hieroglyphs],[`Miao`,e.Miao],[`Modi`,e.Modi],[`Mongolian`,e.Mongolian],[`Mro`,e.Mro],[`Multani`,e.Multani],[`Myanmar`,e.Myanmar],[`Nabataean`,e.Nabataean],[`Nag_Mundari`,e.Nag_Mundari],[`Nandinagari`,e.Nandinagari],[`New_Tai_Lue`,e.New_Tai_Lue],[`Newa`,e.Newa],[`Nko`,e.Nko],[`Nushu`,e.Nushu],[`Nyiakeng_Puachue_Hmong`,e.Nyiakeng_Puachue_Hmong],[`Ogham`,e.Ogham],[`Ol_Chiki`,e.Ol_Chiki],[`Ol_Onal`,e.Ol_Onal],[`Old_Hungarian`,e.Old_Hungarian],[`Old_Italic`,e.Old_Italic],[`Old_North_Arabian`,e.Old_North_Arabian],[`Old_Permic`,e.Old_Permic],[`Old_Persian`,e.Old_Persian],[`Old_Sogdian`,e.Old_Sogdian],[`Old_South_Arabian`,e.Old_South_Arabian],[`Old_Turkic`,e.Old_Turkic],[`Old_Uyghur`,e.Old_Uyghur],[`Oriya`,e.Oriya],[`Osage`,e.Osage],[`Osmanya`,e.Osmanya],[`Pahawh_Hmong`,e.Pahawh_Hmong],[`Palmyrene`,e.Palmyrene],[`Pau_Cin_Hau`,e.Pau_Cin_Hau],[`Phags_Pa`,e.Phags_Pa],[`Phoenician`,e.Phoenician],[`Psalter_Pahlavi`,e.Psalter_Pahlavi],[`Rejang`,e.Rejang],[`Runic`,e.Runic],[`Samaritan`,e.Samaritan],[`Saurashtra`,e.Saurashtra],[`Sharada`,e.Sharada],[`Shavian`,e.Shavian],[`Siddham`,e.Siddham],[`SignWriting`,e.SignWriting],[`Sinhala`,e.Sinhala],[`Sogdian`,e.Sogdian],[`Sora_Sompeng`,e.Sora_Sompeng],[`Soyombo`,e.Soyombo],[`Sundanese`,e.Sundanese],[`Sunuwar`,e.Sunuwar],[`Syloti_Nagri`,e.Syloti_Nagri],[`Syriac`,e.Syriac],[`Tagalog`,e.Tagalog],[`Tagbanwa`,e.Tagbanwa],[`Tai_Le`,e.Tai_Le],[`Tai_Tham`,e.Tai_Tham],[`Tai_Viet`,e.Tai_Viet],[`Takri`,e.Takri],[`Tamil`,e.Tamil],[`Tangsa`,e.Tangsa],[`Tangut`,e.Tangut],[`Telugu`,e.Telugu],[`Thaana`,e.Thaana],[`Thai`,e.Thai],[`Tibetan`,e.Tibetan],[`Tifinagh`,e.Tifinagh],[`Tirhuta`,e.Tirhuta],[`Todhri`,e.Todhri],[`Toto`,e.Toto],[`Tulu_Tigalari`,e.Tulu_Tigalari],[`Ugaritic`,e.Ugaritic],[`Vai`,e.Vai],[`Vithkuqi`,e.Vithkuqi],[`Wancho`,e.Wancho],[`Warang_Citi`,e.Warang_Citi],[`Yezidi`,e.Yezidi],[`Yi`,e.Yi],[`Zanabazar_Square`,e.Zanabazar_Square]]);static FOLD_CATEGORIES=new Map([[`L`,e.foldL],[`Ll`,e.foldLl],[`Lt`,e.foldLt],[`Lu`,e.foldLu],[`M`,e.foldM],[`Mn`,e.foldMn]]);static FOLD_SCRIPT=new Map([[`Common`,e.foldCommon],[`Greek`,e.foldGreek],[`Inherited`,e.foldInherited]]);static Print=new K(new Uint32Array([33,126,1,161,172,1,174,887,1,890,895,1,900,906,1,908,910,2,911,929,1,931,1327,1,1329,1366,1,1369,1418,1,1421,1423,1,1425,1479,1,1488,1514,1,1519,1524,1,1542,1563,1,1565,1756,1,1758,1805,1,1808,1866,1,1869,1969,1,1984,2042,1,2045,2093,1,2096,2110,1,2112,2139,1,2142,2144,2,2145,2154,1,2160,2190,1,2199,2273,1,2275,2435,1,2437,2444,1,2447,2448,1,2451,2472,1,2474,2480,1,2482,2486,4,2487,2489,1,2492,2500,1,2503,2504,1,2507,2510,1,2519,2524,5,2525,2527,2,2528,2531,1,2534,2558,1,2561,2563,1,2565,2570,1,2575,2576,1,2579,2600,1,2602,2608,1,2610,2611,1,2613,2614,1,2616,2617,1,2620,2622,2,2623,2626,1,2631,2632,1,2635,2637,1,2641,2649,8,2650,2652,1,2654,2662,8,2663,2678,1,2689,2691,1,2693,2701,1,2703,2705,1,2707,2728,1,2730,2736,1,2738,2739,1,2741,2745,1,2748,2757,1,2759,2761,1,2763,2765,1,2768,2784,16,2785,2787,1,2790,2801,1,2809,2815,1,2817,2819,1,2821,2828,1,2831,2832,1,2835,2856,1,2858,2864,1,2866,2867,1,2869,2873,1,2876,2884,1,2887,2888,1,2891,2893,1,2901,2903,1,2908,2909,1,2911,2915,1,2918,2935,1,2946,2947,1,2949,2954,1,2958,2960,1,2962,2965,1,2969,2970,1,2972,2974,2,2975,2979,4,2980,2984,4,2985,2986,1,2990,3001,1,3006,3010,1,3014,3016,1,3018,3021,1,3024,3031,7,3046,3066,1,3072,3084,1,3086,3088,1,3090,3112,1,3114,3129,1,3132,3140,1,3142,3144,1,3146,3149,1,3157,3158,1,3160,3162,1,3165,3168,3,3169,3171,1,3174,3183,1,3191,3212,1,3214,3216,1,3218,3240,1,3242,3251,1,3253,3257,1,3260,3268,1,3270,3272,1,3274,3277,1,3285,3286,1,3293,3294,1,3296,3299,1,3302,3311,1,3313,3315,1,3328,3340,1,3342,3344,1,3346,3396,1,3398,3400,1,3402,3407,1,3412,3427,1,3430,3455,1,3457,3459,1,3461,3478,1,3482,3505,1,3507,3515,1,3517,3520,3,3521,3526,1,3530,3535,5,3536,3540,1,3542,3544,2,3545,3551,1,3558,3567,1,3570,3572,1,3585,3642,1,3647,3675,1,3713,3714,1,3716,3718,2,3719,3722,1,3724,3747,1,3749,3751,2,3752,3773,1,3776,3780,1,3782,3784,2,3785,3790,1,3792,3801,1,3804,3807,1,3840,3911,1,3913,3948,1,3953,3991,1,3993,4028,1,4030,4044,1,4046,4058,1,4096,4293,1,4295,4301,6,4304,4680,1,4682,4685,1,4688,4694,1,4696,4698,2,4699,4701,1,4704,4744,1,4746,4749,1,4752,4784,1,4786,4789,1,4792,4798,1,4800,4802,2,4803,4805,1,4808,4822,1,4824,4880,1,4882,4885,1,4888,4954,1,4957,4988,1,4992,5017,1,5024,5109,1,5112,5117,1,5120,5759,1,5761,5788,1,5792,5880,1,5888,5909,1,5919,5942,1,5952,5971,1,5984,5996,1,5998,6e3,1,6002,6003,1,6016,6109,1,6112,6121,1,6128,6137,1,6144,6157,1,6159,6169,1,6176,6264,1,6272,6314,1,6320,6389,1,6400,6430,1,6432,6443,1,6448,6459,1,6464,6468,4,6469,6509,1,6512,6516,1,6528,6571,1,6576,6601,1,6608,6618,1,6622,6683,1,6686,6750,1,6752,6780,1,6783,6793,1,6800,6809,1,6816,6829,1,6832,6862,1,6912,6988,1,6990,7155,1,7164,7223,1,7227,7241,1,7245,7306,1,7312,7354,1,7357,7367,1,7376,7418,1,7424,7957,1,7960,7965,1,7968,8005,1,8008,8013,1,8016,8023,1,8025,8031,2,8032,8061,1,8064,8116,1,8118,8132,1,8134,8147,1,8150,8155,1,8157,8175,1,8178,8180,1,8182,8190,1,8208,8231,1,8240,8286,1,8304,8305,1,8308,8334,1,8336,8348,1,8352,8384,1,8400,8432,1,8448,8587,1,8592,9257,1,9280,9290,1,9312,11123,1,11126,11157,1,11159,11507,1,11513,11557,1,11559,11565,6,11568,11623,1,11631,11632,1,11647,11670,1,11680,11686,1,11688,11694,1,11696,11702,1,11704,11710,1,11712,11718,1,11720,11726,1,11728,11734,1,11736,11742,1,11744,11869,1,11904,11929,1,11931,12019,1,12032,12245,1,12272,12287,1,12289,12351,1,12353,12438,1,12441,12543,1,12549,12591,1,12593,12686,1,12688,12773,1,12783,12830,1,12832,42124,1,42128,42182,1,42192,42539,1,42560,42743,1,42752,42957,1,42960,42961,1,42963,42965,2,42966,42972,1,42994,43052,1,43056,43065,1,43072,43127,1,43136,43205,1,43214,43225,1,43232,43347,1,43359,43388,1,43392,43469,1,43471,43481,1,43486,43518,1,43520,43574,1,43584,43597,1,43600,43609,1,43612,43714,1,43739,43766,1,43777,43782,1,43785,43790,1,43793,43798,1,43808,43814,1,43816,43822,1,43824,43883,1,43888,44013,1,44016,44025,1,44032,55203,1,55216,55238,1,55243,55291,1,63744,64109,1,64112,64217,1,64256,64262,1,64275,64279,1,64285,64310,1,64312,64316,1,64318,64320,2,64321,64323,2,64324,64326,2,64327,64450,1,64467,64911,1,64914,64967,1,64975,65008,33,65009,65049,1,65056,65106,1,65108,65126,1,65128,65131,1,65136,65140,1,65142,65276,1,65281,65470,1,65474,65479,1,65482,65487,1,65490,65495,1,65498,65500,1,65504,65510,1,65512,65518,1,65532,65533,1,65536,65547,1,65549,65574,1,65576,65594,1,65596,65597,1,65599,65613,1,65616,65629,1,65664,65786,1,65792,65794,1,65799,65843,1,65847,65934,1,65936,65948,1,65952,66e3,48,66001,66045,1,66176,66204,1,66208,66256,1,66272,66299,1,66304,66339,1,66349,66378,1,66384,66426,1,66432,66461,1,66463,66499,1,66504,66517,1,66560,66717,1,66720,66729,1,66736,66771,1,66776,66811,1,66816,66855,1,66864,66915,1,66927,66938,1,66940,66954,1,66956,66962,1,66964,66965,1,66967,66977,1,66979,66993,1,66995,67001,1,67003,67004,1,67008,67059,1,67072,67382,1,67392,67413,1,67424,67431,1,67456,67461,1,67463,67504,1,67506,67514,1,67584,67589,1,67592,67594,2,67595,67637,1,67639,67640,1,67644,67647,3,67648,67669,1,67671,67742,1,67751,67759,1,67808,67826,1,67828,67829,1,67835,67867,1,67871,67897,1,67903,67968,65,67969,68023,1,68028,68047,1,68050,68099,1,68101,68102,1,68108,68115,1,68117,68119,1,68121,68149,1,68152,68154,1,68159,68168,1,68176,68184,1,68192,68255,1,68288,68326,1,68331,68342,1,68352,68405,1,68409,68437,1,68440,68466,1,68472,68497,1,68505,68508,1,68521,68527,1,68608,68680,1,68736,68786,1,68800,68850,1,68858,68903,1,68912,68921,1,68928,68965,1,68969,68997,1,69006,69007,1,69216,69246,1,69248,69289,1,69291,69293,1,69296,69297,1,69314,69316,1,69372,69415,1,69424,69465,1,69488,69513,1,69552,69579,1,69600,69622,1,69632,69709,1,69714,69749,1,69759,69820,1,69822,69826,1,69840,69864,1,69872,69881,1,69888,69940,1,69942,69959,1,69968,70006,1,70016,70111,1,70113,70132,1,70144,70161,1,70163,70209,1,70272,70278,1,70280,70282,2,70283,70285,1,70287,70301,1,70303,70313,1,70320,70378,1,70384,70393,1,70400,70403,1,70405,70412,1,70415,70416,1,70419,70440,1,70442,70448,1,70450,70451,1,70453,70457,1,70459,70468,1,70471,70472,1,70475,70477,1,70480,70487,7,70493,70499,1,70502,70508,1,70512,70516,1,70528,70537,1,70539,70542,3,70544,70581,1,70583,70592,1,70594,70597,3,70599,70602,1,70604,70613,1,70615,70616,1,70625,70626,1,70656,70747,1,70749,70753,1,70784,70855,1,70864,70873,1,71040,71093,1,71096,71133,1,71168,71236,1,71248,71257,1,71264,71276,1,71296,71353,1,71360,71369,1,71376,71395,1,71424,71450,1,71453,71467,1,71472,71494,1,71680,71739,1,71840,71922,1,71935,71942,1,71945,71948,3,71949,71955,1,71957,71958,1,71960,71989,1,71991,71992,1,71995,72006,1,72016,72025,1,72096,72103,1,72106,72151,1,72154,72164,1,72192,72263,1,72272,72354,1,72368,72440,1,72448,72457,1,72640,72673,1,72688,72697,1,72704,72712,1,72714,72758,1,72760,72773,1,72784,72812,1,72816,72847,1,72850,72871,1,72873,72886,1,72960,72966,1,72968,72969,1,72971,73014,1,73018,73020,2,73021,73023,2,73024,73031,1,73040,73049,1,73056,73061,1,73063,73064,1,73066,73102,1,73104,73105,1,73107,73112,1,73120,73129,1,73440,73464,1,73472,73488,1,73490,73530,1,73534,73562,1,73648,73664,16,73665,73713,1,73727,74649,1,74752,74862,1,74864,74868,1,74880,75075,1,77712,77810,1,77824,78895,1,78912,78933,1,78944,82938,1,82944,83526,1,90368,90425,1,92160,92728,1,92736,92766,1,92768,92777,1,92782,92862,1,92864,92873,1,92880,92909,1,92912,92917,1,92928,92997,1,93008,93017,1,93019,93025,1,93027,93047,1,93053,93071,1,93504,93561,1,93760,93850,1,93952,94026,1,94031,94087,1,94095,94111,1,94176,94180,1,94192,94193,1,94208,100343,1,100352,101589,1,101631,101640,1,110576,110579,1,110581,110587,1,110589,110590,1,110592,110882,1,110898,110928,30,110929,110930,1,110933,110948,15,110949,110951,1,110960,111355,1,113664,113770,1,113776,113788,1,113792,113800,1,113808,113817,1,113820,113823,1,117760,118009,1,118016,118451,1,118528,118573,1,118576,118598,1,118608,118723,1,118784,119029,1,119040,119078,1,119081,119154,1,119163,119274,1,119296,119365,1,119488,119507,1,119520,119539,1,119552,119638,1,119648,119672,1,119808,119892,1,119894,119964,1,119966,119967,1,119970,119973,3,119974,119977,3,119978,119980,1,119982,119993,1,119995,119997,2,119998,120003,1,120005,120069,1,120071,120074,1,120077,120084,1,120086,120092,1,120094,120121,1,120123,120126,1,120128,120132,1,120134,120138,4,120139,120144,1,120146,120485,1,120488,120779,1,120782,121483,1,121499,121503,1,121505,121519,1,122624,122654,1,122661,122666,1,122880,122886,1,122888,122904,1,122907,122913,1,122915,122916,1,122918,122922,1,122928,122989,1,123023,123136,113,123137,123180,1,123184,123197,1,123200,123209,1,123214,123215,1,123536,123566,1,123584,123641,1,123647,124112,465,124113,124153,1,124368,124410,1,124415,124896,481,124897,124902,1,124904,124907,1,124909,124910,1,124912,124926,1,124928,125124,1,125127,125142,1,125184,125259,1,125264,125273,1,125278,125279,1,126065,126132,1,126209,126269,1,126464,126467,1,126469,126495,1,126497,126498,1,126500,126503,3,126505,126514,1,126516,126519,1,126521,126523,2,126530,126535,5,126537,126541,2,126542,126543,1,126545,126546,1,126548,126551,3,126553,126561,2,126562,126564,2,126567,126570,1,126572,126578,1,126580,126583,1,126585,126588,1,126590,126592,2,126593,126601,1,126603,126619,1,126625,126627,1,126629,126633,1,126635,126651,1,126704,126705,1,126976,127019,1,127024,127123,1,127136,127150,1,127153,127167,1,127169,127183,1,127185,127221,1,127232,127405,1,127462,127490,1,127504,127547,1,127552,127560,1,127568,127569,1,127584,127589,1,127744,128727,1,128732,128748,1,128752,128764,1,128768,128886,1,128891,128985,1,128992,129003,1,129008,129024,16,129025,129035,1,129040,129095,1,129104,129113,1,129120,129159,1,129168,129197,1,129200,129211,1,129216,129217,1,129280,129619,1,129632,129645,1,129648,129660,1,129664,129673,1,129679,129734,1,129742,129756,1,129759,129769,1,129776,129784,1,129792,129938,1,129940,130041,1,131072,173791,1,173824,177977,1,177984,178205,1,178208,183969,1,183984,191456,1,191472,192093,1,194560,195101,1,196608,201546,1,201552,205743,1,917760,917999,1]))},dW=class{static MAX_RUNE=1114111;static MAX_ASCII=127;static MAX_LATIN1=255;static MAX_BMP=65535;static MIN_FOLD=65;static MAX_FOLD=125251;static is32(e,t){let n=0,r=e.length;for(;ne.getHi(n))continue;let r=e.getLo(n);if(t0&&t>=e.getLo(0)&&this.is32(e,t)}static isUpper(e){if(e<=this.MAX_LATIN1){let t=String.fromCodePoint(e);return t.toUpperCase()===t&&t.toLowerCase()!==t}return this.is(uW.Upper,e)}static isPrint(e){return e<=this.MAX_LATIN1?e>=32&&e=161&&e!==173:this.is(uW.Print,e)}static simpleFold(e){if(uW.CASE_ORBIT.has(e))return uW.CASE_ORBIT.get(e);let t=G.toLowerCase(e);return t===e?G.toUpperCase(e):t}static equalsIgnoreCase(e,t){if(e<0||t<0||e===t)return!0;if(e<=this.MAX_ASCII&&t<=this.MAX_ASCII)return G.CODES.get(`A`)<=e&&e<=G.CODES.get(`Z`)&&(e|=32),G.CODES.get(`A`)<=t&&t<=G.CODES.get(`Z`)&&(t|=32),e===t;for(let n=this.simpleFold(e);n!==e;n=this.simpleFold(n))if(n===t)return!0;return!1}},fW=class{static METACHARACTERS=`\\.+*?()|[]{}^$`;static EMPTY_BEGIN_LINE=1;static EMPTY_END_LINE=2;static EMPTY_BEGIN_TEXT=4;static EMPTY_END_TEXT=8;static EMPTY_WORD_BOUNDARY=16;static EMPTY_NO_WORD_BOUNDARY=32;static EMPTY_ALL=-1;static emptyInts(){return[]}static isalnum(e){return G.CODES.get(`0`)<=e&&e<=G.CODES.get(`9`)||G.CODES.get(`a`)<=e&&e<=G.CODES.get(`z`)||G.CODES.get(`A`)<=e&&e<=G.CODES.get(`Z`)}static unhex(e){return G.CODES.get(`0`)<=e&&e<=G.CODES.get(`9`)?e-G.CODES.get(`0`):G.CODES.get(`a`)<=e&&e<=G.CODES.get(`f`)?e-G.CODES.get(`a`)+10:G.CODES.get(`A`)<=e&&e<=G.CODES.get(`F`)?e-G.CODES.get(`A`)+10:-1}static escapeRune(e){let t=``;if(dW.isPrint(e))this.METACHARACTERS.indexOf(String.fromCodePoint(e))>=0&&(t+=`\\`),t+=String.fromCodePoint(e);else switch(e){case G.CODES.get(`"`):t+=`\\"`;break;case G.CODES.get(`\\`):t+=`\\\\`;break;case G.CODES.get(` `):t+=`\\t`;break;case G.CODES.get(` +`):t+=`\\n`;break;case G.CODES.get(`\r`):t+=`\\r`;break;case G.CODES.get(`\b`):t+=`\\b`;break;case G.CODES.get(`\f`):t+=`\\f`;break;default:{let n=e.toString(16);e<256?(t+=`\\x`,n.length===1&&(t+=`0`),t+=n):t+=`\\x{${n}}`;break}}return t}static stringToRunes(e){return String(e).split(``).map(e=>e.codePointAt(0))}static runeToString(e){return String.fromCodePoint(e)}static isWordRune(e){return G.CODES.get(`a`)<=e&&e<=G.CODES.get(`z`)||G.CODES.get(`A`)<=e&&e<=G.CODES.get(`Z`)||G.CODES.get(`0`)<=e&&e<=G.CODES.get(`9`)||e===G.CODES.get(`_`)}static emptyOpContext(e,t){let n=0;return e<0&&(n|=this.EMPTY_BEGIN_TEXT|this.EMPTY_BEGIN_LINE),e===G.CODES.get(` +`)&&(n|=this.EMPTY_BEGIN_LINE),t<0&&(n|=this.EMPTY_END_TEXT|this.EMPTY_END_LINE),t===G.CODES.get(` +`)&&(n|=this.EMPTY_END_LINE),this.isWordRune(e)===this.isWordRune(t)?n|=this.EMPTY_NO_WORD_BOUNDARY:n|=this.EMPTY_WORD_BOUNDARY,n}static quoteMeta(e){return e.split(``).map(e=>this.METACHARACTERS.indexOf(e)>=0?`\\${e}`:e).join(``)}static charCount(e){return e>dW.MAX_BMP?2:1}static stringToUtf8ByteArray(e){if(globalThis.TextEncoder)return Array.from(new TextEncoder().encode(e));{let t=[],n=0;for(let r=0;r>6|192,t[n++]=i&63|128):(i&64512)==55296&&r+1>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}}static utf8ByteArrayToString(e){if(globalThis.TextDecoder)return new TextDecoder(`utf-8`).decode(new Uint8Array(e));{let t=[],n=0,r=0;for(;n191&&i<224){let a=e[n++];t[r++]=String.fromCharCode((i&31)<<6|a&63)}else if(i>239&&i<365){let a=e[n++],o=e[n++],s=e[n++],c=((i&7)<<18|(a&63)<<12|(o&63)<<6|s&63)-65536;t[r++]=String.fromCharCode(55296+(c>>10)),t[r++]=String.fromCharCode(56320+(c&1023))}else{let a=e[n++],o=e[n++];t[r++]=String.fromCharCode((i&15)<<12|(a&63)<<6|o&63)}}return t.join(``)}}},pW=(e=[],t=0)=>{let n={};for(let r=0;re.codePointAt(0))}length(){return this.charSequence.length}},_W=class{static utf16(e){return new gW(e)}static utf8(e){return Array.isArray(e)?new hW(e):new hW(fW.stringToUtf8ByteArray(e))}},vW=class{static EOF(){return-8}canCheckPrefix(){return!0}endPos(){return this.end}},yW=class extends vW{constructor(e,t=0,n=e.length){super(),this.bytes=e,this.start=t,this.end=n}step(e){if(e+=this.start,e>=this.end)return vW.EOF();let t=this.bytes[e++]&255;return t&128?(t&224)==192?(t&=31,e>=this.end?vW.EOF():(t=t<<6|this.bytes[e++]&63,t<<3|2)):(t&240)==224?(t&=15,e+1>=this.end?vW.EOF():(t=t<<6|this.bytes[e++]&63,t=t<<6|this.bytes[e++]&63,t<<3|3)):(t&=7,e+2>=this.end?vW.EOF():(t=t<<6|this.bytes[e++]&63,t=t<<6|this.bytes[e++]&63,t=t<<6|this.bytes[e++]&63,t<<3|4)):t<<3|1}index(e,t){t+=this.start;let n=this.indexOf(this.bytes,e.prefixUTF8,t);return n<0?n:n-t}context(e){e+=this.start;let t=-1;if(e>this.start&&e<=this.end){let n=e-1;if(t=this.bytes[n--],t>=128){let r=e-4;for(r=r&&(this.bytes[n]&192)==128;)n--;n>3}}let n=e>3:-1;return fW.emptyOpContext(t,n)}indexOf(e,t,n=0){let r=t.length;if(r===0)return-1;let i=e.length;for(let a=n;a<=i-r;a++)for(let n=0;n0&&e<=this.charSequence.length?this.charSequence.codePointAt(e-1):-1,n=e{let t=e.codePointAt(0);return t===G.CODES.get(`\\`)||t===G.CODES.get(`$`)?`\\${e}`:e}).join(``)}constructor(e,t){if(e===null)throw Error(`pattern is null`);this.patternInput=e;let n=this.patternInput.re2();this.patternGroupCount=n.numberOfCapturingGroups(),this.groups=[],this.namedGroups=n.namedGroups,this.numberOfInstructions=n.numberOfInstructions(),t instanceof mW?this.resetMatcherInput(t):Array.isArray(t)?this.resetMatcherInput(_W.utf8(t)):this.resetMatcherInput(_W.utf16(t))}pattern(){return this.patternInput}reset(){return this.matcherInputLength=this.matcherInput.length(),this.appendPos=0,this.hasMatch=!1,this.hasGroups=!1,this.anchorFlag=0,this}resetMatcherInput(e){if(e===null)throw Error(`input is null`);return this.matcherInput=e,this.reset(),this}start(e=0){if(typeof e==`string`){let t=this.namedGroups[e];if(!Number.isFinite(t))throw new TW(`group '${e}' not found`);e=t}return this.loadGroup(e),this.groups[2*e]}end(e=0){if(typeof e==`string`){let t=this.namedGroups[e];if(!Number.isFinite(t))throw new TW(`group '${e}' not found`);e=t}return this.loadGroup(e),this.groups[2*e+1]}programSize(){return this.numberOfInstructions}group(e=0){if(typeof e==`string`){let t=this.namedGroups[e];if(!Number.isFinite(t))throw new TW(`group '${e}' not found`);e=t}let t=this.start(e),n=this.end(e);return t<0&&n<0?null:this.substring(t,n)}groupCount(){return this.patternGroupCount}loadGroup(e){if(e<0||e>this.patternGroupCount)throw new TW(`Group index out of bounds: ${e}`);if(!this.hasMatch)throw new TW(`perhaps no match attempted`);if(e===0||this.hasGroups)return;let t=this.groups[1]+1;t>this.matcherInputLength&&(t=this.matcherInputLength);let n=this.patternInput.re2().matchMachineInput(this.matcherInput,this.groups[0],t,this.anchorFlag,1+this.patternGroupCount);if(!n[0])throw new TW(`inconsistency in matching group data`);this.groups=n[1],this.hasGroups=!0}matches(){return this.genMatch(0,W.ANCHOR_BOTH)}lookingAt(){return this.genMatch(0,W.ANCHOR_START)}find(e=null){if(e!==null){if(e<0||e>this.matcherInputLength)throw new TW(`start index out of bounds: ${e}`);return this.reset(),this.genMatch(e,0)}return e=0,this.hasMatch&&(e=this.groups[1],this.groups[0]===this.groups[1]&&e++),this.genMatch(e,W.UNANCHORED)}genMatch(e,t){let n=this.patternInput.re2().matchMachineInput(this.matcherInput,e,this.matcherInputLength,t,1);return n[0]?(this.groups=n[1],this.hasMatch=!0,this.hasGroups=!1,this.anchorFlag=t,!0):!1}substring(e,t){return this.matcherInput.isUTF8Encoding()?fW.utf8ByteArrayToString(this.matcherInput.asBytes().slice(e,t)):this.matcherInput.asCharSequence().substring(e,t).toString()}inputLength(){return this.matcherInputLength}appendReplacement(e,t=!1){let n=``,r=this.start(),i=this.end();return this.appendPosG.CODES.get(`9`)||o*10+a-G.CODES.get(`0`)>this.patternGroupCount));i++)o=o*10+a-G.CODES.get(`0`);if(o>this.patternGroupCount)throw new TW(`n > number of groups: ${o}`);let s=this.group(o);s!==null&&(t+=s),n=i,i--;continue}if(a===G.CODES.get(`{`)){nG.CODES.get(`9`)||o*10+a-G.CODES.get(`0`)>this.patternGroupCount));i++)o=o*10+a-G.CODES.get(`0`);if(o>this.patternGroupCount){t+=`$${o}`,n=i,i--;continue}let s=this.group(o);s!==null&&(t+=s),n=i,i--;continue}if(a===G.CODES.get(`<`)){n`)&&e.codePointAt(r)!==G.CODES.get(` `);)r++;if(r===e.length||e.codePointAt(r)!==G.CODES.get(`>`)){t+=e.substring(i-1,r+1),n=r+1;continue}let a=e.substring(i+1,r);Object.prototype.hasOwnProperty.call(this.namedGroups,a)?t+=this.group(a):t+=`$<${a}>`,n=r+1}}return n ${this.out}, ${this.arg}`;case e.ALT_MATCH:return`altmatch -> ${this.out}, ${this.arg}`;case e.CAPTURE:return`cap ${this.arg} -> ${this.out}`;case e.EMPTY_WIDTH:return`empty ${this.arg} -> ${this.out}`;case e.MATCH:return`match`;case e.FAIL:return`fail`;case e.NOP:return`nop -> ${this.out}`;case e.RUNE:return this.runes===null?`rune `:[`rune `,e.escapeRunes(this.runes),(this.arg&W.FOLD_CASE)===0?``:`/i`,` -> `,this.out].join(``);case e.RUNE1:return`rune1 ${e.escapeRunes(this.runes)} -> ${this.out}`;case e.RUNE_ANY:return`any -> ${this.out}`;case e.RUNE_ANY_NOT_NL:return`anynotnl -> ${this.out}`;default:throw Error(`unhandled case in Inst.toString`)}}},kW=class{constructor(){this.inst=null,this.cap=[]}},AW=class{constructor(){this.sparse=[],this.densePcs=[],this.denseThreads=[],this.size=0}contains(e){let t=this.sparse[e];return tthis.matchcap.length?this.initNewCap(e):this.resetCap(e)}resetCap(e){for(let t=0;t0?(this.poolSize--,t=this.pool[this.poolSize]):t=new kW,t.inst=e,t}freeQueue(e,t=0){let n=e.size-t,r=this.poolSize+n;this.pool.length>3,c=o&7,l=-1,u=0;o!==vW.EOF()&&(o=e.step(t+c),l=o>>3,u=o&7);let d;for(d=t===0?fW.emptyOpContext(-1,s):e.context(t);;){if(i.isEmpty()){if((r&fW.EMPTY_BEGIN_TEXT)!==0&&t!==0||this.matched)break;if(this.re2.prefix.length!==0&&l!==this.re2.prefixRune&&e.canCheckPrefix()){let n=e.index(this.re2,t);if(n<0)break;t+=n,o=e.step(t),s=o>>3,c=o&7,o=e.step(t+c),l=o>>3,u=o&7}}!this.matched&&(t===0||n===W.UNANCHORED)&&(this.ncap>0&&(this.matchcap[0]=t),this.add(i,this.prog.start,t,this.matchcap,d,null));let f=t+c;if(d=e.context(f),this.step(i,a,t,f,s,d,n,t===e.endPos()),c===0||this.ncap===0&&this.matched)break;t+=c,s=l,c=u,s!==-1&&(o=e.step(t+c),l=o>>3,u=o&7);let p=i;i=a,a=p}return this.freeQueue(a),this.matched}step(e,t,n,r,i,a,o,s){let c=this.re2.longest;for(let l=0;l0&&this.matchcap[0]0&&(!c||!this.matched||this.matchcap[1]0&&a.cap!==r&&(a.cap=r.slice(0,this.ncap)),e.denseThreads[o]=a,a=null;break;default:throw Error(`unhandled`)}return a}},MW=e=>{let t=-2128831035;for(let n=0;n{if(e.length!==t.length)return!1;for(let n=0;n0;){let e=n.pop();if(t.has(e))continue;t.add(e);let i=this.prog.getInst(e);switch(i.op){case OW.MATCH:r=!0;break;case OW.ALT:case OW.ALT_MATCH:n.push(i.out),n.push(i.arg);break;case OW.NOP:case OW.CAPTURE:n.push(i.out);break;case OW.EMPTY_WIDTH:return null}}return{pcs:Int32Array.from(t).sort(),isMatch:r}}getState(e){let t=this.computeClosure(e);if(!t)return null;let n=t.pcs,r=MW(n),i=this.stateCache.get(r);if(i)for(let e=0;e=this.stateLimit)return this.stateCache.clear(),this.stateCount=0,this.startState=null,null;let a=new PW(n,t.isMatch);return i.push(a),this.stateCount++,a}step(e,t,n){if(n===W.UNANCHORED&&t<=dW.MAX_ASCII){let n=e.nextAscii[t];if(n!==null)return n}else{let r=t+(n===W.UNANCHORED?0:dW.MAX_RUNE+1);if(e.nextMap.has(r))return e.nextMap.get(r)}let r=[];for(let n=0;n>3,s=t&7;if(s===0)break;if(i=this.step(i,o,n),i===null)return null;if(i.isMatch){if(n===W.ANCHOR_BOTH){if(a+s===r)return!0}else return!0}if(i.nfaStates.length===0&&n!==W.UNANCHORED)return!1;a+=s}return!1}},q=class e{static Op=pW([`NO_MATCH`,`EMPTY_MATCH`,`LITERAL`,`CHAR_CLASS`,`ANY_CHAR_NOT_NL`,`ANY_CHAR`,`BEGIN_LINE`,`END_LINE`,`BEGIN_TEXT`,`END_TEXT`,`WORD_BOUNDARY`,`NO_WORD_BOUNDARY`,`CAPTURE`,`STAR`,`PLUS`,`QUEST`,`REPEAT`,`CONCAT`,`ALTERNATE`,`LEFT_PAREN`,`VERTICAL_BAR`]);static isPseudoOp(t){return t>=e.Op.LEFT_PAREN}static emptySubs(){return[]}static quoteIfHyphen(e){return e===G.CODES.get(`-`)?`\\`:``}static fromRegexp(t){let n=new e(t.op);return n.flags=t.flags,n.subs=t.subs,n.runes=t.runes,n.cap=t.cap,n.min=t.min,n.max=t.max,n.name=t.name,n.namedGroups=t.namedGroups,n}constructor(t){this.op=t,this.flags=0,this.subs=e.emptySubs(),this.runes=[],this.min=0,this.max=0,this.cap=0,this.name=null,this.namedGroups={}}reinit(){this.flags=0,this.subs=e.emptySubs(),this.runes=[],this.cap=0,this.min=0,this.max=0,this.name=null,this.namedGroups={}}toString(){return this.appendTo()}appendTo(){let t=``;switch(this.op){case e.Op.NO_MATCH:t+=`[^\\x00-\\x{10FFFF}]`;break;case e.Op.EMPTY_MATCH:t+=`(?:)`;break;case e.Op.STAR:case e.Op.PLUS:case e.Op.QUEST:case e.Op.REPEAT:{let n=this.subs[0];switch(n.op>e.Op.CAPTURE||n.op===e.Op.LITERAL&&n.runes.length>1?t+=`(?:${n.appendTo()})`:t+=n.appendTo(),this.op){case e.Op.STAR:t+=`*`;break;case e.Op.PLUS:t+=`+`;break;case e.Op.QUEST:t+=`?`;break;case e.Op.REPEAT:t+=`{${this.min}`,this.min!==this.max&&(t+=`,`,this.max>=0&&(t+=this.max)),t+=`}`}(this.flags&W.NON_GREEDY)!==0&&(t+=`?`);break}case e.Op.CONCAT:for(let n of this.subs)n.op===e.Op.ALTERNATE?t+=`(?:${n.appendTo()})`:t+=n.appendTo();break;case e.Op.ALTERNATE:{let e=``;for(let n of this.subs)t+=e,e=`|`,t+=n.appendTo();break}case e.Op.LITERAL:(this.flags&W.FOLD_CASE)!==0&&(t+=`(?i:`);for(let e of this.runes)t+=fW.escapeRune(e);(this.flags&W.FOLD_CASE)!==0&&(t+=`)`);break;case e.Op.ANY_CHAR_NOT_NL:t+=`(?-s:.)`;break;case e.Op.ANY_CHAR:t+=`(?s:.)`;break;case e.Op.CAPTURE:this.name===null||this.name.length===0?t+=`(`:t+=`(?P<${this.name}>`,this.subs[0].op!==e.Op.EMPTY_MATCH&&(t+=this.subs[0].appendTo()),t+=`)`;break;case e.Op.BEGIN_TEXT:t+=`\\A`;break;case e.Op.END_TEXT:(this.flags&W.WAS_DOLLAR)===0?t+=`\\z`:t+=`(?-m:$)`;break;case e.Op.BEGIN_LINE:t+=`^`;break;case e.Op.END_LINE:t+=`$`;break;case e.Op.WORD_BOUNDARY:t+=`\\b`;break;case e.Op.NO_WORD_BOUNDARY:t+=`\\B`;break;case e.Op.CHAR_CLASS:if(this.runes.length%2!=0){t+=`[invalid char class]`;break}if(t+=`[`,this.runes.length===0)t+=`^\\x00-\\x{10FFFF}`;else if(this.runes[0]===0&&this.runes[this.runes.length-1]===dW.MAX_RUNE){t+=`^`;for(let n=1;n>1];return e&1?t.arg:t.out}patch(e,t){for(;e!==0;){let n=this.inst[e>>1];e&1?(e=n.arg,n.arg=t):(e=n.out,n.out=t)}}append(e,t){if(e===0)return t;if(t===0)return e;let n=e;for(;;){let e=this.next(n);if(e===0)break;n=e}let r=this.inst[n>>1];return n&1?r.arg=t:r.out=t,e}toString(){let e=``;for(let t=0;t0){r=[];for(let e=0;et.min){let i=e.simplify1(q.Op.QUEST,t.flags,n,null);for(let r=t.min+1;r0&&(n+=` `);let t=e[r],i=e[r+1];n+=t===i?`0x${t.toString(16)}`:`0x${t.toString(16)}-0x${i.toString(16)}`}return n+=`]`,n}static cmp(e,t,n,r){let i=e[t]-n;return i===0?r-e[t+1]:i}static qsortIntPair(t,n,r){let i=((n+r)/2|0)&-2,a=t[i],o=t[i+1],s=n,c=r;for(;s<=c;){for(;sn&&e.cmp(t,c,a,o)>0;)c-=2;if(s<=c){if(s!==c){let e=t[s];t[s]=t[c],t[c]=e,e=t[s+1],t[s+1]=t[c+1],t[c+1]=e}s+=2,c-=2}}nthis.r[t-1]&&(this.r[t-1]=r);continue}this.r[t]=n,this.r[t+1]=r,t+=2}return this.len=t,this}appendLiteral(e,t){return(t&W.FOLD_CASE)===0?this.appendRange(e,e):this.appendFoldedRange(e,e)}appendRange(e,t){if(this.len>0){for(let n=2;n<=4;n+=2)if(this.len>=n){let r=this.r[this.len-n],i=this.r[this.len-n+1];if(e<=i+1&&r<=t+1)return ei&&(this.r[this.len-n+1]=t),this}}return this.r[this.len++]=e,this.r[this.len++]=t,this}appendFoldedRange(e,t){if(e<=dW.MIN_FOLD&&t>=dW.MAX_FOLD||tdW.MAX_FOLD)return this.appendRange(e,t);edW.MAX_FOLD&&(this.appendRange(dW.MAX_FOLD+1,t),t=dW.MAX_FOLD);for(let n=e;n<=t;n++){this.appendRange(n,n);for(let e=dW.simpleFold(n);e!==n;e=dW.simpleFold(e))this.appendRange(e,e)}return this}appendClass(e){for(let t=0;tdW.MAX_FOLD)return e;let t=e,n=e;for(e=dW.simpleFold(e);e!==n;e=dW.simpleFold(e))t>e&&(t=e);return t}static leadingRegexp(e){if(e.op===q.Op.EMPTY_MATCH)return null;if(e.op===q.Op.CONCAT&&e.subs.length>0){let t=e.subs[0];return t.op===q.Op.EMPTY_MATCH?null:t}return e}static literalRegexp(e,t){let n=new q(q.Op.LITERAL);return n.flags=t,n.runes=fW.stringToRunes(e),n}static parse(t,n){return new e(t,n).parseInternal()}static parseRepeat(t){let n=t.pos();if(!t.more()||!t.lookingAt(`{`))return-1;t.skip(1);let r=e.parseInt(t);if(r===-1||!t.more())return-1;let i;if(!t.lookingAt(`,`))i=r;else{if(t.skip(1),!t.more())return-1;if(t.lookingAt(`}`))i=-1;else if((i=e.parseInt(t))===-1)return-1}if(!t.more()||!t.lookingAt(`}`))return-1;if(t.skip(1),r<0||r>1e3||i===-2||i>1e3||i>=0&&r>i)throw new CW(e.ERR_INVALID_REPEAT_SIZE,t.from(n));return r<<16|i&dW.MAX_BMP}static isValidCaptureName(e){if(e.length===0)return!1;for(let t=0;t=G.CODES.get(`0`)&&e.peek()<=G.CODES.get(`9`);)e.skip(1);let n=e.from(t);return n.length===0||n.length>1&&n.codePointAt(0)===G.CODES.get(`0`)?-1:n.length>8?-2:parseFloat(n,10)}static isCharClass(e){return e.op===q.Op.LITERAL&&e.runes.length===1||e.op===q.Op.CHAR_CLASS||e.op===q.Op.ANY_CHAR_NOT_NL||e.op===q.Op.ANY_CHAR}static matchRune(e,t){switch(e.op){case q.Op.LITERAL:return e.runes.length===1&&e.runes[0]===t;case q.Op.CHAR_CLASS:for(let n=0;nG.CODES.get(`7`))break;case G.CODES.get(`0`):{let e=r-G.CODES.get(`0`);for(let n=1;n<3&&!(!t.more()||t.peek()G.CODES.get(`7`));n++)e=e*8+t.peek()-G.CODES.get(`0`),t.skip(1);return e}case G.CODES.get(`x`):{if(!t.more())break;if(r=t.pop(),r===G.CODES.get(`{`)){let e=0,n=0;for(;;){if(!t.more())break e;if(r=t.pop(),r===G.CODES.get(`}`))break;let i=fW.unhex(r);if(i<0||(n=n*16+i,n>dW.MAX_RUNE))break e;e++}if(e===0)break e;return n}let e=fW.unhex(r);if(!t.more())break;r=t.pop();let n=fW.unhex(r);if(e<0||n<0)break;return e*16+n}case G.CODES.get(`a`):return G.CODES.get(`\x07`);case G.CODES.get(`f`):return G.CODES.get(`\f`);case G.CODES.get(`n`):return G.CODES.get(` +`);case G.CODES.get(`r`):return G.CODES.get(`\r`);case G.CODES.get(`t`):return G.CODES.get(` `);case G.CODES.get(`v`):return G.CODES.get(`\v`);default:if(r<=dW.MAX_ASCII&&!fW.isalnum(r))return r}throw new CW(e.ERR_INVALID_ESCAPE,t.from(n))}static parseClassChar(t,n){if(!t.more())throw new CW(e.ERR_MISSING_BRACKET,t.from(n));return t.lookingAt(`\\`)?e.parseEscape(t):t.pop()}static concatRunes(e,t){return[...e,...t]}constructor(e,t=0){this.wholeRegexp=e,this.flags=t,this.numCap=0,this.namedGroups={},this.stack=[],this.free=null,this.numRegexp=0,this.numRunes=0,this.repeats=0,this.height=null,this.size=null}newRegexp(e){let t=this.free;return t!==null&&t.subs!==null&&t.subs.length>0?(this.free=t.subs[0],t.reinit(),t.op=e):(t=new q(e),this.numRegexp+=1),t}reuse(e){this.height!==null&&Object.prototype.hasOwnProperty.call(this.height,e)&&delete this.height[e],e.subs!==null&&e.subs.length>0&&(e.subs[0]=this.free),this.free=e}checkLimits(t){if(this.numRunes>e.MAX_RUNES)throw new CW(e.ERR_LARGE);this.checkSize(t),this.checkHeight(t)}checkSize(t){if(this.size===null){if(this.repeats===0&&(this.repeats=1),t.op===q.Op.REPEAT){let n=t.max;n===-1&&(n=t.min),n<=0&&(n=1),n>e.MAX_SIZE/this.repeats?this.repeats=e.MAX_SIZE:this.repeats*=n}if(this.numRegexpe.MAX_SIZE)throw new CW(e.ERR_LARGE)}calcSize(e,t=!1){if(!t&&Object.prototype.hasOwnProperty.call(this.size,e))return this.size[e];let n=0;switch(e.op){case q.Op.LITERAL:n=e.runes.length;break;case q.Op.CAPTURE:case q.Op.STAR:n=2+this.calcSize(e.subs[0]);break;case q.Op.PLUS:case q.Op.QUEST:n=1+this.calcSize(e.subs[0]);break;case q.Op.CONCAT:for(let t of e.subs)n+=this.calcSize(t);break;case q.Op.ALTERNATE:for(let t of e.subs)n+=this.calcSize(t);e.subs.length>1&&(n=n+e.subs.length-1);break;case q.Op.REPEAT:{let t=this.calcSize(e.subs[0]);if(e.max===-1){n=e.min===0?2+t:1+e.min*t;break}n=e.max*t+(e.max-e.min);break}}return n=Math.max(1,n),this.size[e]=n,n}checkHeight(t){if(!(this.numRegexpe.MAX_HEIGHT)throw new CW(e.ERR_NESTING_DEPTH)}}calcHeight(e,t=!1){if(!t&&Object.prototype.hasOwnProperty.call(this.height,e))return this.height[e];let n=1;for(let t of e.subs){let e=this.calcHeight(t);n<1+e&&(n=1+e)}return this.height[e]=n,n}pop(){return this.stack.pop()}popToPseudo(){let e=this.stack.length,t=e;for(;t>0&&!q.isPseudoOp(this.stack[t-1].op);)t--;let n=this.stack.slice(t,e);return this.stack=this.stack.slice(0,t),n}push(e){if(this.numRunes+=e.runes.length,e.op===q.Op.CHAR_CLASS&&e.runes.length===2&&e.runes[0]===e.runes[1]){if(this.maybeConcat(e.runes[0],this.flags&-2))return null;e.op=q.Op.LITERAL,e.runes=[e.runes[0]],e.flags=this.flags&-2}else if(e.op===q.Op.CHAR_CLASS&&e.runes.length===4&&e.runes[0]===e.runes[1]&&e.runes[2]===e.runes[3]&&dW.simpleFold(e.runes[0])===e.runes[2]&&dW.simpleFold(e.runes[2])===e.runes[0]||e.op===q.Op.CHAR_CLASS&&e.runes.length===2&&e.runes[0]+1===e.runes[1]&&dW.simpleFold(e.runes[0])===e.runes[1]&&dW.simpleFold(e.runes[1])===e.runes[0]){if(this.maybeConcat(e.runes[0],this.flags|W.FOLD_CASE))return null;e.op=q.Op.LITERAL,e.runes=[e.runes[0]],e.flags=this.flags|W.FOLD_CASE}else this.maybeConcat(-1,0);return this.stack.push(e),this.checkLimits(e),e}maybeConcat(t,n){let r=this.stack.length;if(r<2)return!1;let i=this.stack[r-1],a=this.stack[r-2];return i.op!==q.Op.LITERAL||a.op!==q.Op.LITERAL||(i.flags&W.FOLD_CASE)!==(a.flags&W.FOLD_CASE)?!1:(a.runes=e.concatRunes(a.runes,i.runes),t>=0?(i.runes=[t],i.flags=n,!0):(this.pop(),this.reuse(i),!1))}newLiteral(t,n){let r=this.newRegexp(q.Op.LITERAL);return r.flags=n,(n&W.FOLD_CASE)!==0&&(t=e.minFoldRune(t)),r.runes=[t],r}literal(e){this.push(this.newLiteral(e,this.flags))}op(e){let t=this.newRegexp(e);return t.flags=this.flags,this.push(t)}repeat(t,n,r,i,a,o){let s=this.flags;if((s&W.PERL_X)!==0&&(a.more()&&a.lookingAt(`?`)&&(a.skip(1),s^=W.NON_GREEDY),o!==-1))throw new CW(e.ERR_INVALID_REPEAT_OP,a.from(o));let c=this.stack.length;if(c===0)throw new CW(e.ERR_MISSING_REPEAT_ARGUMENT,a.from(i));let l=this.stack[c-1];if(q.isPseudoOp(l.op))throw new CW(e.ERR_MISSING_REPEAT_ARGUMENT,a.from(i));let u=this.newRegexp(t);if(u.min=n,u.max=r,u.flags=s,u.subs=[l],this.stack[c-1]=u,this.checkLimits(u),t===q.Op.REPEAT&&(n>=2||r>=2)&&!this.repeatIsValid(u,1e3))throw new CW(e.ERR_INVALID_REPEAT_SIZE,a.from(i))}repeatIsValid(e,t){if(e.op===q.Op.REPEAT){let n=e.max;if(n===0)return!0;if(n<0&&(n=e.min),n>t)return!1;n>0&&(t=Math.trunc(t/n))}for(let n of e.subs)if(!this.repeatIsValid(n,t))return!1;return!0}concat(){this.maybeConcat(-1,0);let e=this.popToPseudo();return e.length===0?this.push(this.newRegexp(q.Op.EMPTY_MATCH)):this.push(this.collapse(e,q.Op.CONCAT))}alternate(){let e=this.popToPseudo();return e.length>0&&this.cleanAlt(e[e.length-1]),e.length===0?this.push(this.newRegexp(q.Op.NO_MATCH)):this.push(this.collapse(e,q.Op.ALTERNATE))}cleanAlt(e){e.op===q.Op.CHAR_CLASS&&(e.runes=new oG(e.runes).cleanClass().toArray(),e.runes.length===2&&e.runes[0]===0&&e.runes[1]===dW.MAX_RUNE?(e.runes=[],e.op=q.Op.ANY_CHAR):e.runes.length===4&&e.runes[0]===0&&e.runes[1]===G.CODES.get(` +`)-1&&e.runes[2]===G.CODES.get(` +`)+1&&e.runes[3]===dW.MAX_RUNE&&(e.runes=[],e.op=q.Op.ANY_CHAR_NOT_NL))}collapse(e,t){if(e.length===1)return e[0];let n=0;for(let r of e)n+=r.op===t?r.subs.length:1;let r=Array(n).fill(null),i=0;for(let n of e)n.op===t?(r.splice(i,n.subs.length,...n.subs),i+=n.subs.length,this.reuse(n)):r[i++]=n;let a=this.newRegexp(t);if(a.subs=r,t===q.Op.ALTERNATE&&(a.subs=this.factor(a.subs),a.subs.length===1)){let e=a;a=a.subs[0],this.reuse(e)}return a}factor(t){if(t.length<2)return t;let n=0,r=t.length,i=0,a=null,o=0,s=0,c=0;for(let e=0;e<=r;e++){let l=null,u=0,d=0;if(e0&&(r=r.subs[0]),r.op===q.Op.LITERAL&&(l=r.runes,u=r.runes.length,d=r.flags&W.FOLD_CASE),d===s){let e=0;for(;e0){o=e;continue}}}if(e!==c){if(e===c+1)t[i++]=t[n+c];else{let r=this.newRegexp(q.Op.LITERAL);r.flags=s,r.runes=a.slice(0,o);for(let r=c;r0){let n=this.removeLeadingString(e.subs[0],t);if(e.subs[0]=n,n.op===q.Op.EMPTY_MATCH)switch(this.reuse(n),e.subs.length){case 0:case 1:e.op=q.Op.EMPTY_MATCH,e.subs=null;break;case 2:{let t=e;e=e.subs[1],this.reuse(t);break}default:e.subs=e.subs.slice(1,e.subs.length)}return e}return e.op===q.Op.LITERAL&&(e.runes=e.runes.slice(t,e.runes.length),e.runes.length===0&&(e.op=q.Op.EMPTY_MATCH)),e}removeLeadingRegexp(e,t){if(e.op===q.Op.CONCAT&&e.subs.length>0){switch(t&&this.reuse(e.subs[0]),e.subs=e.subs.slice(1,e.subs.length),e.subs.length){case 0:e.op=q.Op.EMPTY_MATCH,e.subs=q.emptySubs();break;case 1:{let t=e;e=e.subs[0],this.reuse(t);break}}return e}return t&&this.reuse(e),this.newRegexp(q.Op.EMPTY_MATCH)}parseInternal(){if((this.flags&W.LITERAL)!==0)return e.literalRegexp(this.wholeRegexp,this.flags);let t=-1,n=-1,r=-1,i=new cG(this.wholeRegexp);for(;i.more();){let a=-1;e:switch(i.peek()){case G.CODES.get(`(`):if((this.flags&W.PERL_X)!==0&&i.lookingAt(`(?`)){this.parsePerlFlags(i);break}this.op(q.Op.LEFT_PAREN).cap=++this.numCap,i.skip(1);break;case G.CODES.get(`|`):this.parseVerticalBar(),i.skip(1);break;case G.CODES.get(`)`):this.parseRightParen(),i.skip(1);break;case G.CODES.get(`^`):(this.flags&W.ONE_LINE)===0?this.op(q.Op.BEGIN_LINE):this.op(q.Op.BEGIN_TEXT),i.skip(1);break;case G.CODES.get(`$`):(this.flags&W.ONE_LINE)===0?this.op(q.Op.END_LINE):this.op(q.Op.END_TEXT).flags|=W.WAS_DOLLAR,i.skip(1);break;case G.CODES.get(`.`):(this.flags&W.DOT_NL)===0?this.op(q.Op.ANY_CHAR_NOT_NL):this.op(q.Op.ANY_CHAR),i.skip(1);break;case G.CODES.get(`[`):this.parseClass(i);break;case G.CODES.get(`*`):case G.CODES.get(`+`):case G.CODES.get(`?`):{a=i.pos();let e=null;switch(i.pop()){case G.CODES.get(`*`):e=q.Op.STAR;break;case G.CODES.get(`+`):e=q.Op.PLUS;break;case G.CODES.get(`?`):e=q.Op.QUEST}this.repeat(e,n,r,a,i,t);break}case G.CODES.get(`{`):{a=i.pos();let o=e.parseRepeat(i);if(o<0){i.rewindTo(a),this.literal(i.pop());break}n=o>>16,r=(o&dW.MAX_BMP)<<16>>16,this.repeat(q.Op.REPEAT,n,r,a,i,t);break}case G.CODES.get(`\\`):{let t=i.pos();if(i.skip(1),(this.flags&W.PERL_X)!==0&&i.more())switch(i.pop()){case G.CODES.get(`A`):this.op(q.Op.BEGIN_TEXT);break e;case G.CODES.get(`b`):this.op(q.Op.WORD_BOUNDARY);break e;case G.CODES.get(`B`):this.op(q.Op.NO_WORD_BOUNDARY);break e;case G.CODES.get(`C`):throw new CW(e.ERR_INVALID_ESCAPE,`\\C`);case G.CODES.get(`Q`):{let e=i.rest(),t=e.indexOf(`\\E`);t>=0&&(e=e.substring(0,t)),i.skipString(e),i.skipString(`\\E`);let n=0;for(;n`);if(i<0)throw new CW(e.ERR_INVALID_NAMED_CAPTURE,r);let a=r.substring(n,i);if(t.skipString(a),t.skip(n+1),!e.isValidCaptureName(a))throw new CW(e.ERR_INVALID_NAMED_CAPTURE,r.substring(0,i+1));let o=this.op(q.Op.LEFT_PAREN);if(o.cap=++this.numCap,this.namedGroups[a])throw new CW(e.ERR_DUPLICATE_NAMED_CAPTURE,a);this.namedGroups[a]=this.numCap,o.name=a;return}t.skip(2);let i=this.flags,a=1,o=!1;e:for(;t.more();){let e=t.pop();switch(e){case G.CODES.get(`i`):i|=W.FOLD_CASE,o=!0;break;case G.CODES.get(`m`):i&=-17,o=!0;break;case G.CODES.get(`s`):i|=W.DOT_NL,o=!0;break;case G.CODES.get(`U`):i|=W.NON_GREEDY,o=!0;break;case G.CODES.get(`-`):if(a<0)break e;a=-1,i=~i,o=!1;break;case G.CODES.get(`:`):case G.CODES.get(`)`):if(a<0){if(!o)break e;i=~i}e===G.CODES.get(`:`)&&this.op(q.Op.LEFT_PAREN),this.flags=i;return;default:break e}}throw new CW(e.ERR_INVALID_PERL_OP,t.from(n))}parseVerticalBar(){this.concat(),this.swapVerticalBar()||this.op(q.Op.VERTICAL_BAR)}swapVerticalBar(){let t=this.stack.length;if(t>=3&&this.stack[t-2].op===q.Op.VERTICAL_BAR&&e.isCharClass(this.stack[t-1])&&e.isCharClass(this.stack[t-3])){let n=this.stack[t-1],r=this.stack[t-3];if(n.op>r.op){let e=r;r=n,n=e,this.stack[t-3]=r}return e.mergeCharClass(r,n),this.reuse(n),this.pop(),!0}if(t>=2){let e=this.stack[t-1],n=this.stack[t-2];if(n.op===q.Op.VERTICAL_BAR)return t>=3&&this.cleanAlt(this.stack[t-3]),this.stack[t-2]=e,this.stack[t-1]=n,!0}return!1}parseRightParen(){if(this.concat(),this.swapVerticalBar()&&this.pop(),this.alternate(),this.stack.length<2)throw new CW(e.ERR_UNEXPECTED_PAREN,this.wholeRegexp);let t=this.pop(),n=this.pop();if(n.op!==q.Op.LEFT_PAREN)throw new CW(e.ERR_UNEXPECTED_PAREN,this.wholeRegexp);this.flags=n.flags,n.cap===0?this.push(t):(n.op=q.Op.CAPTURE,n.subs=[t],this.push(n))}parsePerlClassEscape(e,t){let n=e.pos();if((this.flags&W.PERL_X)===0||!e.more()||e.pop()!==G.CODES.get(`\\`)||!e.more())return!1;e.pop();let r=e.from(n),i=WW.has(r)?WW.get(r):null;return i!==null&&(t.appendGroup(i,(this.flags&W.FOLD_CASE)!==0),!0)}parseNamedClass(t,n){let r=t.rest(),i=r.indexOf(`:]`);if(i<0)return!1;let a=r.substring(0,i+2);t.skipString(a);let o=aG.has(a)?aG.get(a):null;if(o===null)throw new CW(e.ERR_INVALID_CHAR_RANGE,a);return n.appendGroup(o,(this.flags&W.FOLD_CASE)!==0),!0}parseUnicodeClass(t,n){let r=t.pos();if((this.flags&W.UNICODE_GROUPS)===0||!t.lookingAt(`\\p`)&&!t.lookingAt(`\\P`))return!1;t.skip(1);let i=1,a=t.pop();if(a===G.CODES.get(`P`)&&(i=-1),!t.more())throw t.rewindTo(r),new CW(e.ERR_INVALID_CHAR_RANGE,t.rest());a=t.pop();let o;if(a!==G.CODES.get(`{`))o=fW.runeToString(a);else{let n=t.rest(),i=n.indexOf(`}`);if(i<0)throw t.rewindTo(r),new CW(e.ERR_INVALID_CHAR_RANGE,t.rest());o=n.substring(0,i),t.skipString(o),t.skip(1)}o.length!==0&&o.codePointAt(0)===G.CODES.get(`^`)&&(i=0-i,o=o.substring(1));let s=e.unicodeTable(o);if(s===null)throw new CW(e.ERR_INVALID_CHAR_RANGE,t.from(r));let c=s.first,l=s.second;if((this.flags&W.FOLD_CASE)===0||l===null)n.appendTableWithSign(c,i);else{let e=new oG().appendTable(c).appendTable(l).cleanClass().toArray();n.appendClassWithSign(e,i)}return!0}parseClass(t){let n=t.pos();t.skip(1);let r=this.newRegexp(q.Op.CHAR_CLASS);r.flags=this.flags;let i=new oG,a=1;t.more()&&t.lookingAt(`^`)&&(a=-1,t.skip(1),(this.flags&W.CLASS_NL)===0&&i.appendRange(G.CODES.get(` +`),G.CODES.get(` +`)));let o=!0;for(;!t.more()||t.peek()!==G.CODES.get(`]`)||o;){if(t.more()&&t.lookingAt(`-`)&&(this.flags&W.PERL_X)===0&&!o){let r=t.rest();if(r===`-`||!r.startsWith(`-]`))throw t.rewindTo(n),new CW(e.ERR_INVALID_CHAR_RANGE,t.rest())}o=!1;let r=t.pos();if(t.lookingAt(`[:`)){if(this.parseNamedClass(t,i))continue;t.rewindTo(r)}if(this.parseUnicodeClass(t,i)||this.parsePerlClassEscape(t,i))continue;t.rewindTo(r);let a=e.parseClassChar(t,n),s=a;if(t.more()&&t.lookingAt(`-`)){if(t.skip(1),t.more()&&t.lookingAt(`]`))t.skip(-1);else if(s=e.parseClassChar(t,n),s0&&(s.prefixRune=s.prefix.codePointAt(0)),s.namedGroups=i.namedGroups,s}static match(t,n){return e.compile(t).match(n)}constructor(e,t,n=0,r=0){this.expr=e,this.prog=t,this.numSubexp=n,this.longest=r,this.cond=t.startCond(),this.prefix=null,this.prefixUTF8=null,this.prefixComplete=!1,this.prefixRune=0,this.pooled=new uG,this.dfa=new FW(t)}executeEngine(e,t,n,r){if(r>0)return this.doExecuteNFA(e,t,n,r);let i=this.dfa.match(e,t,n);return i===null?this.doExecuteNFA(e,t,n,r):i?[]:null}numberOfCapturingGroups(){return this.numSubexp}numberOfInstructions(){return this.prog.numInst()}get(){let e;do e=this.pooled.get();while(e&&!this.pooled.compareAndSet(e,e.next));return e}reset(){this.pooled.set(null)}put(e,t){let n=this.pooled.get();do n=this.pooled.get(),!t&&n&&(e=jW.fromMachine(e),t=!0),e.next!==n&&(e.next=n);while(!this.pooled.compareAndSet(n,e))}toString(){return this.expr}doExecuteNFA(e,t,n,r){let i=this.get(),a=!1;i?i.next!==null&&(i=jW.fromMachine(i),a=!0):(i=jW.fromRE2(this),a=!0),i.init(r);let o=i.match(e,t,n)?i.submatches():null;return this.put(i,a),o}match(e){return this.executeEngine(xW.fromUTF16(e),0,W.UNANCHORED,0)!==null}matchWithGroup(e,t,n,r,i){return e instanceof mW||(e=_W.utf16(e)),this.matchMachineInput(e,t,n,r,i)}matchMachineInput(e,t,n,r,i){if(t>n)return[!1,null];let a=e.isUTF16Encoding()?xW.fromUTF16(e.asCharSequence(),0,n):xW.fromUTF8(e.asBytes(),0,n),o=this.executeEngine(a,t,r,2*i);return o===null?[!1,null]:[!0,o]}matchUTF8(e){return this.executeEngine(xW.fromUTF8(e),0,W.UNANCHORED,0)!==null}replaceAll(e,t){return this.replaceAllFunc(e,()=>t,2*e.length+1)}replaceFirst(e,t){return this.replaceAllFunc(e,()=>t,1)}replaceAllFunc(e,t,n){let r=0,i=0,a=``,o=xW.fromUTF16(e),s=0;for(;i<=e.length;){let c=this.executeEngine(o,i,W.UNANCHORED,2);if(c===null||c.length===0)break;a+=e.substring(r,c[0]),(c[1]>r||c[0]===0)&&(a+=t(e.substring(c[0],c[1])),s++),r=c[1];let l=o.step(i)&7;if(i+l>c[1]?i+=l:i+1>c[1]?i++:i=c[1],s>=n)break}return a+=e.substring(r),a}pad(e){if(e===null)return null;let t=(1+this.numSubexp)*2;if(e.lengthe){let r=[],i=e.endPos();t<0&&(t=i+1);let a=0,o=0,s=-1;for(;o=0&&(n[r]=e.slice(t[2*r],t[2*r+1]));return n}findUTF8SubmatchIndex(e){return this.pad(this.executeEngine(xW.fromUTF8(e),0,W.UNANCHORED,this.prog.numCap))}findSubmatch(e){let t=this.executeEngine(xW.fromUTF16(e),0,W.UNANCHORED,this.prog.numCap);if(t===null)return null;let n=Array(1+this.numSubexp).fill(null);for(let r=0;r=0&&(n[r]=e.substring(t[2*r],t[2*r+1]));return n}findSubmatchIndex(e){return this.pad(this.executeEngine(xW.fromUTF16(e),0,W.UNANCHORED,this.prog.numCap))}findAllUTF8(e,t){let n=this.allMatches(xW.fromUTF8(e),t,t=>e.slice(t[0],t[1]));return n.length===0?null:n}findAllUTF8Index(e,t){let n=this.allMatches(xW.fromUTF8(e),t,e=>e.slice(0,2));return n.length===0?null:n}findAll(e,t){let n=this.allMatches(xW.fromUTF16(e),t,t=>e.substring(t[0],t[1]));return n.length===0?null:n}findAllIndex(e,t){let n=this.allMatches(xW.fromUTF16(e),t,e=>e.slice(0,2));return n.length===0?null:n}findAllUTF8Submatch(e,t){let n=this.allMatches(xW.fromUTF8(e),t,t=>{let n=Array(t.length/2|0).fill(null);for(let r=0;r=0&&(n[r]=e.slice(t[2*r],t[2*r+1]));return n});return n.length===0?null:n}findAllUTF8SubmatchIndex(e,t){let n=this.allMatches(xW.fromUTF8(e),t);return n.length===0?null:n}findAllSubmatch(e,t){let n=this.allMatches(xW.fromUTF16(e),t,t=>{let n=Array(t.length/2|0).fill(null);for(let r=0;r=0&&(n[r]=e.substring(t[2*r],t[2*r+1]));return n});return n.length===0?null:n}findAllSubmatchIndex(e,t){let n=this.allMatches(xW.fromUTF16(e),t);return n.length===0?null:n}},fG=class e{static isUpperCaseAlpha(e){return`A`<=e&&e<=`Z`}static isHexadecimal(e){return`0`<=e&&e<=`9`||`A`<=e&&e<=`F`||`a`<=e&&e<=`f`}static getUtf8CharSize(e){let t=e.charCodeAt(0);return t<128?1:t<2048?2:t<65536?3:4}static translate(t){if(typeof t!=`string`)return t;let n=``,r=!1,i=t.length;i===0&&(n=`(?:)`,r=!0);let a=0;for(;a>4).toString(16).toUpperCase(),n+=(i.charCodeAt(0)-64&15).toString(16).toUpperCase(),a+=3,r=!0;continue}}n+=`\\c`,a+=2;continue;case`u`:if(a+2=i||t[a+3]!==`=`&&t[a+3]!==`!`)){n+=`(?P<`,a+=3,r=!0;continue}let s=e.getUtf8CharSize(o);n+=t.substring(a,a+s),a+=s}return r?n:t}},pG=class e{static CASE_INSENSITIVE=1;static DOTALL=2;static MULTILINE=4;static DISABLE_UNICODE_GROUPS=8;static LONGEST_MATCH=16;static quote(e){return fW.quoteMeta(e)}static translateRegExp(e){return fG.translate(e)}static compile(t,n=0){let r=t;if((n&e.CASE_INSENSITIVE)!==0&&(r=`(?i)${r}`),(n&e.DOTALL)!==0&&(r=`(?s)${r}`),(n&e.MULTILINE)!==0&&(r=`(?m)${r}`),(n&~(e.MULTILINE|e.DOTALL|e.CASE_INSENSITIVE|e.DISABLE_UNICODE_GROUPS|e.LONGEST_MATCH))!==0)throw new EW(`Flags should only be a combination of MULTILINE, DOTALL, CASE_INSENSITIVE, DISABLE_UNICODE_GROUPS, LONGEST_MATCH`);let i=W.PERL;(n&e.DISABLE_UNICODE_GROUPS)!==0&&(i&=-129);let a=new e(t,n);return a.re2Input=dG.compileImpl(r,i,(n&e.LONGEST_MATCH)!==0),a}static matches(t,n){return e.compile(t).testExact(n)}static initTest(t,n,r){if(t==null)throw Error(`pattern is null`);if(r==null)throw Error(`re2 is null`);let i=new e(t,n);return i.re2Input=r,i}constructor(e,t){this.patternInput=e,this.flagsInput=t}reset(){this.re2Input.reset()}flags(){return this.flagsInput}pattern(){return this.patternInput}re2(){return this.re2Input}matches(e){return this.testExact(e)}matcher(e){return Array.isArray(e)&&(e=_W.utf8(e)),new DW(this,e)}test(e){return Array.isArray(e)?this.re2Input.matchUTF8(e):this.re2Input.match(e)}testExact(e){let t=Array.isArray(e)?xW.fromUTF8(e):xW.fromUTF16(e);return this.re2Input.executeEngine(t,0,W.ANCHOR_BOTH,0)!==null}split(e,t=0){let n=this.matcher(e),r=[],i=0,a=0;for(;n.find();){if(a===0&&n.end()===0){a=n.end();continue}if(t>0&&r.length===t-1)break;if(a===n.start()){if(t===0){i+=1,a=n.end();continue}}else for(;i>0;)r.push(``),--i;r.push(n.substring(a,n.start())),a=n.end()}if(t===0&&a!==n.inputLength()){for(;i>0;)r.push(``),--i;r.push(n.substring(a,n.inputLength()))}return(t!==0||r.length===0)&&r.push(n.substring(a,n.inputLength())),r}toString(){return this.patternInput}programSize(){return this.re2Input.numberOfInstructions()}groupCount(){return this.re2Input.numberOfCapturingGroups()}namedGroups(){return this.re2Input.namedGroups}equals(e){return this===e?!0:e===null||this.constructor!==e.constructor?!1:this.flagsInput===e.flagsInput&&this.patternInput===e.patternInput}}});function Qbe(e){let t=0;return e.includes(`i`)&&(t|=pG.CASE_INSENSITIVE),e.includes(`m`)&&(t|=pG.MULTILINE),e.includes(`s`)&&(t|=pG.DOTALL),t}function $be(e){return pG.translateRegExp(e)}function mG(e,t=``,n={}){return new _G(e,t,n)}var hG,gG,_G,vG,exe=B(()=>{Zbe(),sH(),U(),hG=1e6,gG=67108864,_G=class{_re2;_pattern;_flags;_global;_ignoreCase;_multiline;_lastIndex=0;_nativeRegex=null;_matcher=null;_matcherInput=null;maxResults;maxOutputBytes;signal;assertResultCount(e){if(this.signal?.aborted)throw Error(`regular expression aborted`);if(e>this.maxResults)throw new H(`regular expression result limit exceeded (${this.maxResults})`,`array_elements`)}expandReplacement(e,t){let n=new oH(this.maxOutputBytes,`regular expression replacement`),r=this._re2.groupCount(),i=this._re2.namedGroups();for(let a=0;a=t.length){n.append(o);continue}if(t[a+1]===`{`){let r=t.indexOf(`}`,a+2);if(r!==-1){let o=t.slice(a+2,r),s=i?.[o];if(s!==void 0){n.append(e.group(s)??``),a=r;continue}}}if(/\d/.test(t[a+1])){let i=a+1,o=0;for(;ir)break;o=e,i++}n.append(e.group(o)??``),a=i-1;continue}n.append(o)}return n.build()}acquireMatcher(e){return this._matcher===null?(this._matcher=this._re2.matcher(e),this._matcherInput=e,this._matcher):(this._matcherInput!==e&&(this._matcher.matcherInput.charSequence=e,this._matcherInput=e),this._matcher.reset(),this._matcher)}constructor(e,t=``,n={}){if(this._pattern=e,this._flags=t,this._global=t.includes(`g`),this._ignoreCase=t.includes(`i`),this._multiline=t.includes(`m`),this.maxResults=n.maxResults??hG,this.maxOutputBytes=n.maxOutputBytes??gG,this.signal=n.signal,!Number.isSafeInteger(this.maxResults)||this.maxResults<0||!Number.isSafeInteger(this.maxOutputBytes)||this.maxOutputBytes<0)throw Error(`invalid regular expression limits`);try{let n=$be(e),r=Qbe(t);this._re2=pG.compile(n,r)}catch(t){if(t instanceof CW){let n=t.message||``,r=``;throw n.includes(`(?=`)||n.includes(`(?!`)||n.includes(`(?<`)||n.includes(`(?0){let e=Object.create(null);for(let[n,r]of Object.entries(o)){let i=t.group(r);i!==null&&(e[n]=i)}a.groups=e}return this._global&&(this._lastIndex=t.end(0),t.start(0)===t.end(0)&&this._lastIndex++),a}match(e){if(this._global&&(this._lastIndex=0),!this._global)return this.exec(e);let t=[],n=this.acquireMatcher(e),r=0;for(;n.find(r);){let i=n.group(0)??``;if(this.assertResultCount(t.length+1),t.push(i),r=n.end(0),n.start(0)===n.end(0)&&r++,r>e.length)break}return t.length>0?t:null}replace(e,t){if(this._global&&(this._lastIndex=0),typeof t==`string`){let n=this._re2.matcher(e),r=new oH(this.maxOutputBytes,`regular expression replacement`),i=0,a=0,o=0;for(;n.find(a);){this.assertResultCount(++o);let s=n.start(0),c=n.end(0);if(r.append(e.slice(i,s)),r.append(this.expandReplacement(n,t)),i=c,a=c>s?c:c+1,!this._global||a>e.length)break}return r.append(e.slice(i)),r.build()}let n=new oH(this.maxOutputBytes,`regular expression replacement`),r=this._re2.matcher(e),i=0,a=0,o=0,s=this._re2.groupCount(),c=this._re2.namedGroups();for(;r.find(a);){this.assertResultCount(++o),n.append(e.slice(i,r.start(0)));let l=[],u=r.group(0)??``;for(let e=1;e<=s;e++)l.push(r.group(e));if(l.push(r.start(0)),l.push(e),c&&Object.keys(c).length>0){let e=Object.create(null);for(let[t,n]of Object.entries(c))e[t]=r.group(n)??``;l.push(e)}let d=r.start(0),f=r.end(0);if(n.append(t(u,...l)),i=f,a=i,d===f&&a++,!this._global||a>e.length)break}return n.append(e.slice(i)),n.build()}split(e,t){if(t===0)return[];let n=t===void 0||t<0?this.maxResults:Math.min(t,this.maxResults),r=[],i=this._re2.matcher(e),a=0,o=0;for(;r.lengthi.start(0)?i.end(0):i.end(0)+1;return r.length0){let e=Object.create(null);for(let[n,i]of Object.entries(r)){let r=t.group(i);r!==null&&(e[n]=r)}s.groups=e}if(yield s,i=t.end(0),t.start(0)===t.end(0)&&i++,i>e.length)break}}get native(){if(!this._nativeRegex)try{this._nativeRegex=new RegExp(this._pattern,this._flags)}catch{this._nativeRegex=RegExp(``,this._flags),Object.defineProperty(this._nativeRegex,"source",{value:this._pattern,writable:!1})}return this._nativeRegex}get source(){return this._pattern}get flags(){return this._flags}get global(){return this._global}get ignoreCase(){return this._ignoreCase}get multiline(){return this._multiline}get lastIndex(){return this._lastIndex}set lastIndex(e){this._lastIndex=e}},vG=class{_regex;constructor(e){this._regex=e}test(e){return this._regex.global&&(this._regex.lastIndex=0),this._regex.test(e)}exec(e){return this._regex.exec(e)}match(e){return this._regex.global&&(this._regex.lastIndex=0),e.match(this._regex)}replace(e,t){return this._regex.global&&(this._regex.lastIndex=0),e.replace(this._regex,t)}split(e,t){return e.split(this._regex,t)}search(e){return e.search(this._regex)}*matchAll(e){if(!this._regex.global)throw Error(`matchAll requires global flag`);this._regex.lastIndex=0;let t=this._regex.exec(e);for(;t!==null;)yield t,t[0].length===0&&this._regex.lastIndex++,t=this._regex.exec(e)}get native(){return this._regex}get source(){return this._regex.source}get flags(){return this._regex.flags}get global(){return this._regex.global}get ignoreCase(){return this._regex.ignoreCase}get multiline(){return this._regex.multiline}get lastIndex(){return this._regex.lastIndex}set lastIndex(e){this._regex.lastIndex=e}}}),yG=B(()=>{exe()});function bG(e,t,n){let r=typeof n==`boolean`?{ignoreCase:n}:n??{},i=t;r.stripQuotes&&(i.startsWith(`"`)&&i.endsWith(`"`)||i.startsWith(`'`)&&i.endsWith(`'`))&&(i=i.slice(1,-1));let a=r.ignoreCase?`i:${i}`:i,o=SG.get(a);if(!o){if(o=txe(i,r.ignoreCase),SG.size>=xG){let e=SG.keys().next().value;e!==void 0&&SG.delete(e)}SG.set(a,o)}return o.test(e)}function txe(e,t){let n=`^`;for(let t=0;t{yG(),xG=2048,SG=new Map});function wG(e,t){let n=e.ignoreCase?t.toLowerCase():t,r=e.needles;for(let e=0;e]+)>)/g,(e,n,r)=>n===`&`?t[0]:r===void 0?t[parseInt(n,10)]??``:t.groups?.[r]??``)}function EG(e,t,n={}){let{invertMatch:r=!1,showLineNumbers:i=!1,countOnly:a=!1,countMatches:o=!1,filename:s=``,onlyMatching:c=!1,beforeContext:l=0,afterContext:u=0,maxCount:d=0,contextSeparator:f=`--`,showColumn:p=!1,vimgrep:m=!1,showByteOffset:h=!1,replace:g=null,passthru:_=!1,multiline:v=!1,kResetGroup:y,preFilter:b,maxWork:x,maxMatches:S,signal:C}=n;if(v)return nxe(e,t,{invertMatch:r,showLineNumbers:i,countOnly:a,countMatches:o,filename:s,onlyMatching:c,beforeContext:l,afterContext:u,maxCount:d,contextSeparator:f,showColumn:p,showByteOffset:h,replace:g,kResetGroup:y,preFilter:b,maxWork:x,maxMatches:S,signal:C});let w=0,T=(e=1)=>{if(C?.aborted)throw new HB;if(w+=e,x!==void 0&&w>x)throw new H(`search: matching work limit exceeded (${x})`,`iterations`)},E=(e,t)=>{if(S!==void 0&&e.length>=S)throw new H(`search: result limit exceeded (${S})`,`array_elements`);e.push(t)},D=1;for(let t=0;tS))throw new H(`search: line limit exceeded (${S})`,`array_elements`);let O=e.split(` +`),k=O.length,A=k>0&&O[k-1]===``?k-1:k;if(a||o){let e=0,n=(o||c)&&!r;for(let i=0;i0,matchCount:e}}if(l===0&&u===0&&!_){let e=[],n=!1,a=0,o=0;for(let l=0;l0&&a>=d));l++){let u=O[l],d=null;if(b&&!wG(b,u)||(t.lastIndex=0,d=t.exec(u)),d!==null!==r){if(n=!0,a++,c)for(let n=d;n!==null;n=t.exec(u)){T();let r=y===void 0?n[0]:n[y]??``,a=g===null?r:TG(g,n),c=s?`${s}:`:``;h&&(c+=`${o+n.index}:`),i&&(c+=`${l+1}:`),p&&(c+=`${n.index+1}:`),E(e,c+a),n[0].length===0&&t.lastIndex++}else if(m)for(let n=d;n!==null;n=t.exec(u)){T();let r=s?`${s}:`:``;h&&(r+=`${o+n.index}:`),i&&(r+=`${l+1}:`),p&&(r+=`${n.index+1}:`),E(e,r+u),n[0].length===0&&t.lastIndex++}else{let n=d?d.index+1:1,r=u;g!==null&&(t.lastIndex=0,r=t.replace(u,(...e)=>{if(e[0].length===0)return``;let t=e,n=e[e.length-1];return typeof n==`object`&&n?(t.groups=n,t.input=e[e.length-2],t.index=e[e.length-3]):(t.input=e[e.length-1],t.index=e[e.length-2]),TG(g,t)}));let a=s?`${s}:`:``;h&&(a+=`${o+(d?d.index:0)}:`),i&&(a+=`${l+1}:`),p&&(a+=`${n}:`),E(e,a+r)}}o+=u.length+1}return{output:e.length>0?`${e.join(` +`)} +`:``,matched:n,matchCount:a}}if(_){let e=[],n=!1,a=0;for(let o=0;o0?`${e.join(` +`)} +`:``,matched:n,matchCount:a}}let j=[],M=0,ee=new Set,te=-1,N=[];for(let e=0;e0&&M>=d));e++){let n=O[e],i;if(b&&!wG(b,n)?i=!1:(t.lastIndex=0,i=t.test(n)),i!==r){if(S!==void 0&&N.length>=S)throw new H(`search: match limit exceeded (${S})`,`array_elements`);N.push(e),M++}}for(let e of N){T();let n=Math.max(0,e-l);te>=0&&n>te+1&&E(j,f);for(let t=n;t0?`${j.join(` +`)} +`:``,matched:M>0,matchCount:M}}function nxe(e,t,n){let{invertMatch:r,showLineNumbers:i,countOnly:a,countMatches:o,filename:s,onlyMatching:c,beforeContext:l,afterContext:u,maxCount:d,contextSeparator:f,showColumn:p,showByteOffset:m,replace:h,kResetGroup:g,preFilter:_,maxWork:v,maxMatches:y,signal:b}=n,x=0,S=(e=1)=>{if(b?.aborted)throw new HB;if(x+=e,v!==void 0&&x>v)throw new H(`search: matching work limit exceeded (${v})`,`iterations`)};if(_&&!r&&!wG(_,e))return a||o?{output:`${s?`${s}:0`:`0`} +`,matched:!1,matchCount:0}:{output:``,matched:!1,matchCount:0};let C=[0];for(let t=0;t=y)throw new H(`search: line index limit exceeded (${y})`,`array_elements`);C.push(t+1)}let w=e.split(` +`),T=w.length,E=T>0&&w[T-1]===``?T-1:T,D=e=>{let t=0,n=C.length;for(;t{let t=D(e);return e-C[t]+1};if(a||o){let n=0,i=0,a=-1;t.lastIndex=0;for(let r=t.exec(e);r!==null&&(S(),!(d>0&&n>=d));r=t.exec(e)){if(n++,!o){let e=D(r.index),t=D(r.index+Math.max(0,r[0].length-1)),n=Math.max(e,a+1);n<=t&&(i+=t-n+1,a=t)}r[0].length===0&&t.lastIndex++}let c=o?r?0:n:r?E-i:i;return{output:`${s?`${s}:${c}`:String(c)} +`,matched:c>0,matchCount:c}}let k=[];t.lastIndex=0;for(let n=t.exec(e);n!==null&&(S(),!(d>0&&k.length>=d));n=t.exec(e)){if(y!==void 0&&k.length>=y)throw new H(`search: match limit exceeded (${y})`,`array_elements`);let e=D(n.index),r=D(n.index+Math.max(0,n[0].length-1)),i=g===void 0?n[0]:n[g]??``;k.push({startLine:e,endLine:r,byteOffset:n.index,column:O(n.index),matchText:i}),n[0].length===0&&t.lastIndex++}if(r){let e=new Set;for(let t of k)for(let n=t.startLine;n<=t.endLine;n++)S(),e.add(n);let t=[];for(let n=0;n0?`${t.join(` +`)} +`:``,matched:t.length>0,matchCount:t.length}}if(k.length===0)return{output:``,matched:!1,matchCount:0};let A=new Set,j=-1,M=[];for(let e of k){S();let n=Math.max(0,e.startLine-l),r=Math.min(E-1,e.endLine+u);j>=0&&n>j+1&&M.push(f);for(let t=n;t0?`${M.join(` +`)} +`:``,matched:!0,matchCount:k.length}}var rxe=B(()=>{U()});function DG(e){let t=``,n=0;for(;n:]]`){t+=`\\b`,n+=7;continue}if(e[n]===`[`){let r=`[`;for(n++,n]+)>/g,`(?<$1>`),t.mode===`perl`){n=sxe(n),n=cxe(n),n=lxe(n);let e=pxe(n);n=e.pattern,r=e.kResetGroup}break;default:n=DG(e),n=gxe(n)}t.wholeWord&&(n=`\\b(?:${n})\\b`),t.lineRegexp&&(n=`^(?:${n})$`);let i=/\\u\{[0-9A-Fa-f]+\}/.test(n),a=`g`+(t.ignoreCase?`i`:``)+(t.multiline?`m`:``)+(t.multilineDotall?`s`:``)+(i?`u`:``),o=ixe(n,t.ignoreCase??!1);return{regex:mG(n,a),kResetGroup:r,preFilter:o??void 0}}function ixe(e,t){let n=e;if(n.startsWith(`\\b(?:`)&&n.endsWith(`)\\b`)?n=n.slice(5,n.length-3):n.startsWith(`\\b`)&&n.endsWith(`\\b`)&&n.length>=4&&(n=n.slice(2,n.length-2)),n.length===0)return null;let r=axe(n);if(r===null)return null;let i=[];for(let e of r){let t=oxe(e);if(t===null||t.length===0)return null;i.push(t)}return i.length===0?null:{needles:t?i.map(e=>e.toLowerCase()):i,ignoreCase:t}}function axe(e){let t=[],n=0,r=!1,i=0;for(let a=0;a=0&&t[n]===`\\`;n--)e++;e%2==0&&(t=t.slice(0,-1))}if(t.length===0)return null;let n=``;for(let e=0;e0&&n+1=0&&e[r]===`\\`;)n++,r--;if(n%2==0)return t}t+=2}else t++;return-1}function hxe(e){let t=0,n=0;for(;n`),t=t.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)(?![>0-9])/g,`$$<$1>`),t}function gxe(e){let t=``,n=0,r=!0,i=0;for(;n{yG(),AG=new Map([[`alpha`,`a-zA-Z`],[`digit`,`0-9`],[`alnum`,`a-zA-Z0-9`],[`lower`,`a-z`],[`upper`,`A-Z`],[`xdigit`,`0-9A-Fa-f`],[`space`,` \\t\\n\\r\\f\\v`],[`blank`,` \\t`],[`punct`,"!-/:-@\\[-`{-~"],[`graph`,`!-~`],[`print`,` -~`],[`cntrl`,`\\x00-\\x1F\\x7F`],[`ascii`,`\\x00-\\x7F`],[`word`,`a-zA-Z0-9_`]])}),jG=B(()=>{rxe(),_xe()}),MG={};wz(MG,{egrepCommand:()=>WG,egrepFlagsForFuzzing:()=>qG,fgrepCommand:()=>UG,fgrepFlagsForFuzzing:()=>KG,flagsForFuzzing:()=>GG,grepCommand:()=>VG});function NG(e){let t=e.limits.maxLoopIterations,n=e.limits.maxArrayElements;return Math.max(t,Math.min(n,t*10))}function PG(e){if(++e.operations>e.maxOperations)throw new H(`grep: glob operation limit exceeded (${e.maxOperations})`,`glob_operations`)}function FG(e){if(e.results>=e.maxResults)throw new H(`grep: array element limit exceeded (${e.maxResults})`,`array_elements`);e.results++}function vxe(e){return e.split(` +`)}function yxe(e){if(e===``)return[];let t=e.split(` +`);return t[t.length-1]===``&&t.pop(),t}function bxe(e,t){return e.length===1?{pattern:e[0],mode:t}:t===`fixed`?{pattern:e.map(e=>`(?:${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)})`).join(`|`),mode:`extended`}:t===`basic`?{pattern:e.join(`\\|`),mode:t}:{pattern:e.map(e=>`(?:${e})`).join(`|`),mode:t}}async function IG(e,t,n,r,i,a=0){if(a>=HG)return;let o=n.fs.resolvePath(n.cwd,e);try{if(PG(i),!(await n.fs.stat(o)).isDirectory){let n=e.split(`/`).pop()||``;t&&bG(n,t.replace(/^\//,``),{stripQuotes:!0})&&(FG(i),r.push(e));return}PG(i);let s=await n.fs.readdir(o);for(let o of s){let s=e===`.`?o:`${e}/${o}`,c=n.fs.resolvePath(n.cwd,s);PG(i),(await n.fs.stat(c)).isDirectory?await IG(s,t,n,r,i,a+1):t&&bG(o,t.replace(/^\//,``),{stripQuotes:!0})&&(FG(i),r.push(s))}}catch(e){nV(e)}}async function xxe(e,t,n){let r=[],i=e.lastIndexOf(`/`),a,o;if(i===-1?(a=t.cwd,o=e):(a=e.slice(0,i)||`/`,o=e.slice(i+1)),e.includes(`**`)){let r=[],i=e.split(`**`);return await IG(i[0].replace(/\/$/,``)||`.`,i[1]||``,t,r,n),r.map(e=>({path:e}))}let s=t.fs.resolvePath(t.cwd,a);try{if(t.fs.readdirWithFileTypes){PG(n);let e=await t.fs.readdirWithFileTypes(s);for(let t of e)if(PG(n),bG(t.name,o,{stripQuotes:!0})){let e=i===-1?t.name:`${a}/${t.name}`;FG(n),r.push({path:e,isFile:t.isFile})}}else{PG(n);let e=await t.fs.readdir(s);for(let t of e)if(PG(n),bG(t,o,{stripQuotes:!0})){let e=i===-1?t:`${a}/${t}`;FG(n),r.push({path:e})}}}catch(e){nV(e)}return r.sort((e,t)=>e.path.localeCompare(t.path))}async function LG(e,t,n=[],r=[],i=[],a,o={operations:0,results:0,maxOperations:t.limits.maxGlobOperations,maxResults:t.limits.maxArrayElements},s=[],c=0){if(c>=HG)return s;let l=t.fs.resolvePath(t.cwd,e);try{let u,d;if(a!==void 0)u=a,d=!a;else{PG(o);let e=await t.fs.stat(l);u=e.isFile,d=e.isDirectory}if(u){let t=e.split(`/`).pop()||e;return r.length>0&&r.some(e=>bG(t,e,{stripQuotes:!0}))||n.length>0&&!n.some(e=>bG(t,e,{stripQuotes:!0}))||(FG(o),s.push({path:e,isFile:!0})),s}if(!d)return s;let f=e.split(`/`).pop()||e;if(i.length>0&&i.some(e=>bG(f,e,{stripQuotes:!0})))return s;if(t.fs.readdirWithFileTypes){PG(o);let a=await t.fs.readdirWithFileTypes(l);for(let l of a)PG(o),!l.name.startsWith(`.`)&&await LG(e===`.`?l.name:`${e}/${l.name}`,t,n,r,i,l.isFile,o,s,c+1)}else{PG(o);let a=await t.fs.readdir(l);for(let l of a)PG(o),!l.startsWith(`.`)&&await LG(e===`.`?l:`${e}/${l}`,t,n,r,i,void 0,o,s,c+1)}}catch(e){nV(e)}return s}var RG,zG,BG,VG,HG,UG,WG,GG,KG,qG,JG=B(()=>{kB(),rV(),U(),CG(),sV(),jG(),RG=`(standard input)`,zG=`[^\\s\\S]`,BG={name:`grep`,summary:`print lines that match patterns`,usage:`grep [OPTION]... PATTERN [FILE]...`,description:[`Search for PATTERN in each FILE.`,`With no FILE, or when FILE is -, read standard input.`],options:[`-E, --extended-regexp PATTERN is an extended regular expression`,`-P, --perl-regexp PATTERN is a Perl regular expression`,`-F, --fixed-strings PATTERN is a set of newline-separated strings`,`-i, --ignore-case ignore case distinctions`,`-v, --invert-match select non-matching lines`,`-w, --word-regexp match only whole words`,`-x, --line-regexp match only whole lines`,`-c, --count print only a count of matching lines`,`-l, --files-with-matches print only names of files with matches`,`-L, --files-without-match print names of files with no matches`,`-m NUM, --max-count=NUM stop after NUM matches`,`-n, --line-number print line number with output lines`,`-h, --no-filename suppress the file name prefix on output`,`-o, --only-matching show only nonempty parts of lines that match`,`-q, --quiet, --silent suppress all normal output`,`-r, -R, --recursive search directories recursively`,`-A NUM print NUM lines of trailing context`,`-B NUM print NUM lines of leading context`,`-C NUM print NUM lines of context`,`-e PATTERN use PATTERN for matching`,`-f FILE, --file=FILE obtain patterns from FILE, one per line`,` --include=GLOB search only files matching GLOB`,` --exclude=GLOB skip files matching GLOB`,` --exclude-dir=DIR skip directories matching DIR`,` --help display this help and exit`]},VG={name:`grep`,async execute(e,t){let n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=!1,f=!1,p=!1,m=!1,h=!1,g=!1,_=0,v=0,y=0,b=[],x=[],S=[],C=null,w=[],T=[],E=!0;for(let t=0;t0)w.push(n);else if(t+1t.limits.maxArrayElements)throw new H(`grep: array element limit exceeded (${t.limits.maxArrayElements})`,`array_elements`);O.push(...r)}if(O.length===0&&!i&&!s)return{stdout:``,stderr:``,exitCode:1};let A=p?`fixed`:d?`extended`:f?`perl`:`basic`;if(A===`perl`&&new Set(O).size>1)return{stdout:``,stderr:`grep: the -P option only supports a single pattern +`,exitCode:2};if(O.length>1&&A!==`fixed`)for(let e of O)try{OG(e,{mode:A})}catch{return{stdout:``,stderr:`grep: invalid regular expression: ${e} +`,exitCode:2}}let j=O.length===0?{pattern:zG,mode:`extended`}:bxe(O,A),M,ee,te;try{let e=OG(j.pattern,{mode:j.mode,ignoreCase:n,wholeWord:l,lineRegexp:u});M=e.regex,ee=e.kResetGroup,te=e.preFilter}catch{return{stdout:``,stderr:`grep: invalid regular expression: ${O.join(` +`)} +`,exitCode:2}}if(D.length===0&&t.stdin!==void 0){let e=EG(k?``:vB(t.stdin),M,{invertMatch:i,showLineNumbers:r,countOnly:a,filename:``,onlyMatching:m,beforeContext:v,afterContext:y,maxCount:_,kResetGroup:ee,preFilter:te,maxWork:NG(t),maxMatches:t.limits.maxArrayElements,signal:t.signal});return g?{stdout:``,stderr:``,exitCode:+!e.matched}:{stdout:e.output,stderr:``,exitCode:+!e.matched}}if(D.length===0)return{stdout:``,stderr:`grep: no input files +`,exitCode:2};let N=``,ne=``,re=!1,ie=!1,ae=[],oe={operations:0,results:0,maxOperations:t.limits.maxGlobOperations,maxResults:t.limits.maxArrayElements},se=e=>{if(e.length>oe.maxResults-ae.length)throw new H(`grep: array element limit exceeded (${oe.maxResults})`,`array_elements`);ae.push(...e)},ce=!1,le=!1;for(let e of D){if(e===`-`){if(ae.length>=oe.maxResults)throw new H(`grep: array element limit exceeded (${oe.maxResults})`,`array_elements`);ae.push({path:RG,isFile:!0,isStdin:!0,stdinAtEof:ce}),ce=!0;continue}if(le=!0,e.includes(`*`)||e.includes(`?`)||e.includes(`[`)){let n=await xxe(e,t,oe);if(c)for(let e of n)se(await LG(e.path,t,b,x,S,e.isFile,oe));else se(n)}else if(c)se(await LG(e,t,b,x,S,void 0,oe));else{if(ae.length>=oe.maxResults)throw new H(`grep: array element limit exceeded (${oe.maxResults})`,`array_elements`);ae.push({path:e})}}let ue=(ae.length>1||c&&le)&&!h;for(let e=0;e{let n=e.path,o=n.split(`/`).pop()||n;if(x.length>0&&!c&&!e.isStdin&&x.some(e=>bG(o,e,{stripQuotes:!0}))||b.length>0&&!c&&!e.isStdin&&!b.some(e=>bG(o,e,{stripQuotes:!0})))return null;try{let o;if(e.isStdin)o=e.stdinAtEof||t.stdin===void 0?``:vB(t.stdin);else{let r=t.fs.resolvePath(t.cwd,n),i=!1;if(i=e.isFile===void 0?(await t.fs.stat(r)).isDirectory:!e.isFile,i)return c?null:{error:`grep: ${n}: Is a directory +`};o=await t.fs.readFile(r)}if(te&&!i){let e=te.ignoreCase?o.toLowerCase():o;if(!te.needles.some(t=>e.includes(t)))return a?{file:n,result:{output:`${ue?`${n}:0`:`0`} +`,matched:!1,matchCount:0}}:{file:n,result:{output:``,matched:!1,matchCount:0}}}return{file:n,result:EG(o,M,{invertMatch:i,showLineNumbers:r,countOnly:a,filename:ue?n:``,onlyMatching:m,beforeContext:v,afterContext:y,maxCount:_,kResetGroup:ee,preFilter:te,maxWork:NG(t),maxMatches:t.limits.maxArrayElements,signal:t.signal})}}catch(e){return nV(e),{error:`grep: ${n}: No such file or directory +`}}}));for(let e of l){if(e===null)continue;if(`error`in e&&e.error){ne+=e.error,e.error.includes(`Is a directory`)||(ie=!0);continue}if(!(`file`in e)||!e.result)continue;let{file:t,result:n}=e;if(n.matched){if(re=!0,g)return{stdout:``,stderr:``,exitCode:0};o?N+=`${t} +`:s||(N+=n.output)}else s?N+=`${t} +`:a&&!o&&(N+=n.output)}}let de;return de=ie?2:+!re,g?{stdout:``,stderr:``,exitCode:de}:{stdout:N,stderr:ne,exitCode:de}}},HG=256,UG={name:`fgrep`,async execute(e,t){return VG.execute([`-F`,...e],t)}},WG={name:`egrep`,async execute(e,t){return VG.execute([`-E`,...e],t)}},GG={name:`grep`,flags:[{flag:`-E`,type:`boolean`},{flag:`-F`,type:`boolean`},{flag:`-P`,type:`boolean`},{flag:`-i`,type:`boolean`},{flag:`-v`,type:`boolean`},{flag:`-w`,type:`boolean`},{flag:`-x`,type:`boolean`},{flag:`-c`,type:`boolean`},{flag:`-l`,type:`boolean`},{flag:`-L`,type:`boolean`},{flag:`-n`,type:`boolean`},{flag:`-h`,type:`boolean`},{flag:`-o`,type:`boolean`},{flag:`-q`,type:`boolean`},{flag:`-r`,type:`boolean`},{flag:`-m`,type:`value`,valueHint:`number`},{flag:`-A`,type:`value`,valueHint:`number`},{flag:`-B`,type:`value`,valueHint:`number`},{flag:`-C`,type:`value`,valueHint:`number`},{flag:`-e`,type:`value`,valueHint:`pattern`},{flag:`-f`,type:`value`,valueHint:`path`}],stdinType:`text`,needsArgs:!0},KG={name:`fgrep`,flags:[],stdinType:`text`,needsArgs:!0},qG={name:`egrep`,flags:[],stdinType:`text`,needsArgs:!0}});function YG(e,t){if(Array.isArray(e))throw TypeError(`${t}: expected object, got array`);if(Object.getPrototypeOf(e)!==null)throw TypeError(`${t}: expected null-prototype object, got prototypal object`)}function XG(e){return!rK.has(e)}function ZG(e,t,n){YG(e,`safeSet`),XG(t)&&(e[t]=n)}function QG(e,t){return YG(e,`safeHasOwn`),Object.hasOwn(e,t)}function $G(e,t={}){let n=t.maxDepth??2e3,r=t.maxElements??1e6,i=new WeakMap,a=t.elementBudget??{used:0};if(!Number.isSafeInteger(a.used)||a.used<0||a.used>r)throw new H(`query input element limit exceeded (${r})`,`array_elements`);let o=()=>{if(++a.used>r)throw new H(`query input element limit exceeded (${r})`,`array_elements`)},s=(e,t,r)=>{if(typeof e!=`object`||!e||e instanceof Date)return e;let a=i.get(e);if(a!==void 0)return a;if(t>n)throw new H(`query depth limit exceeded (${n})`,`recursion`);let o=Array.isArray(e)?[]:Object.create(null);return i.set(e,o),r.push({source:e,target:o,depth:t}),o},c=[],l=s(e,0,c);for(;c.length>0;){let e=c.pop();if(!e)break;let{source:t,target:n,depth:i}=e;if(Array.isArray(t)&&Array.isArray(n)){if(t.length>r-a.used)throw new H(`query input element limit exceeded (${r})`,`array_elements`);n.length=t.length;for(let e=t.length-1;e>=0;e--)o(),n[e]=s(t[e],i+1,c);continue}let l=t,u=n,d=Object.keys(l);if(d.length>r-a.used)throw new H(`query input element limit exceeded (${r})`,`array_elements`);for(let e=0;e{U(),rK=new Set([`__proto__`,`constructor`,`prototype`]),[...rK]});function Cxe(){let e=[];for(let[t,n]of Object.entries(aK).sort()){let r=[];for(let e of n.extensions)r.push(`*${e}`);for(let e of n.globs)r.push(e);e.push(`${t}: ${r.join(`, `)}`)}return`${e.join(` +`)} +`}var aK,oK,sK=B(()=>{yG(),iK(),aK=Sxe({js:{extensions:[`.js`,`.mjs`,`.cjs`,`.jsx`],globs:[]},ts:{extensions:[`.ts`,`.tsx`,`.mts`,`.cts`],globs:[]},html:{extensions:[`.html`,`.htm`,`.xhtml`],globs:[]},css:{extensions:[`.css`,`.scss`,`.sass`,`.less`],globs:[]},json:{extensions:[`.json`,`.jsonc`,`.json5`],globs:[]},xml:{extensions:[`.xml`,`.xsl`,`.xslt`],globs:[]},c:{extensions:[`.c`,`.h`],globs:[]},cpp:{extensions:[`.cpp`,`.cc`,`.cxx`,`.hpp`,`.hh`,`.hxx`,`.h`],globs:[]},rust:{extensions:[`.rs`],globs:[]},go:{extensions:[`.go`],globs:[]},zig:{extensions:[`.zig`],globs:[]},java:{extensions:[`.java`],globs:[]},kotlin:{extensions:[`.kt`,`.kts`],globs:[]},scala:{extensions:[`.scala`,`.sc`],globs:[]},clojure:{extensions:[`.clj`,`.cljc`,`.cljs`,`.edn`],globs:[]},py:{extensions:[`.py`,`.pyi`,`.pyw`],globs:[]},rb:{extensions:[`.rb`,`.rake`,`.gemspec`],globs:[`Rakefile`,`Gemfile`]},php:{extensions:[`.php`,`.phtml`,`.php3`,`.php4`,`.php5`],globs:[]},perl:{extensions:[`.pl`,`.pm`,`.pod`,`.t`],globs:[]},lua:{extensions:[`.lua`],globs:[]},sh:{extensions:[`.sh`,`.bash`,`.zsh`,`.fish`],globs:[`.bashrc`,`.zshrc`,`.profile`]},bat:{extensions:[`.bat`,`.cmd`],globs:[]},ps:{extensions:[`.ps1`,`.psm1`,`.psd1`],globs:[]},yaml:{extensions:[`.yaml`,`.yml`],globs:[]},toml:{extensions:[`.toml`],globs:[`Cargo.toml`,`pyproject.toml`]},ini:{extensions:[`.ini`,`.cfg`,`.conf`],globs:[]},csv:{extensions:[`.csv`,`.tsv`],globs:[]},md:{extensions:[`.md`,`.mdx`,`.markdown`,`.mdown`,`.mkd`],globs:[]},markdown:{extensions:[`.md`,`.mdx`,`.markdown`,`.mdown`,`.mkd`],globs:[]},rst:{extensions:[`.rst`],globs:[]},txt:{extensions:[`.txt`,`.text`],globs:[]},tex:{extensions:[`.tex`,`.ltx`,`.sty`,`.cls`],globs:[]},sql:{extensions:[`.sql`],globs:[]},graphql:{extensions:[`.graphql`,`.gql`],globs:[]},proto:{extensions:[`.proto`],globs:[]},make:{extensions:[`.mk`,`.mak`],globs:[`Makefile`,`GNUmakefile`,`makefile`]},docker:{extensions:[],globs:[`Dockerfile`,`Dockerfile.*`,`*.dockerfile`]},tf:{extensions:[`.tf`,`.tfvars`],globs:[]}}),oK=class{types;constructor(){this.types=new Map(Object.entries(aK).map(([e,t])=>[e,{extensions:[...t.extensions],globs:[...t.globs]}]))}addType(e){let t=e.indexOf(`:`);if(t===-1)return;let n=e.slice(0,t),r=e.slice(t+1);if(r.startsWith(`include:`)){let e=r.slice(8),t=this.types.get(e);if(t){let e=this.types.get(n)||{extensions:[],globs:[]};e.extensions.push(...t.extensions),e.globs.push(...t.globs),this.types.set(n,e)}}else{let e=this.types.get(n)||{extensions:[],globs:[]};if(r.startsWith(`*.`)&&!r.slice(2).includes(`*`)){let t=r.slice(1);e.extensions.includes(t)||e.extensions.push(t)}else e.globs.includes(r)||e.globs.push(r);this.types.set(n,e)}}clearType(e){let t=this.types.get(e);t&&(t.extensions=[],t.globs=[])}getType(e){return this.types.get(e)}getAllTypes(){return this.types}matchesType(e,t){let n=e.toLowerCase();for(let r of t){if(r===`all`){if(this.matchesAnyType(e))return!0;continue}let t=this.types.get(r);if(t){for(let e of t.extensions)if(n.endsWith(e))return!0;for(let r of t.globs)if(r.includes(`*`)){if(mG(`^${r.replace(/\./g,`\\.`).replace(/\*/g,`.*`)}$`,`i`).test(e))return!0}else if(n===r.toLowerCase())return!0}}return!1}matchesAnyType(e){let t=e.toLowerCase();for(let n of this.types.values()){for(let e of n.extensions)if(t.endsWith(e))return!0;for(let r of n.globs)if(r.includes(`*`)){if(mG(`^${r.replace(/\./g,`\\.`).replace(/\*/g,`.*`)}$`,`i`).test(e))return!0}else if(t===r.toLowerCase())return!0}return!1}}});function wxe(){return{ignoreCase:!1,caseSensitive:!1,smartCase:!0,fixedStrings:!1,wordRegexp:!1,lineRegexp:!1,invertMatch:!1,multiline:!1,multilineDotall:!1,patterns:[],patternFiles:[],count:!1,countMatches:!1,files:!1,filesWithMatches:!1,filesWithoutMatch:!1,stats:!1,onlyMatching:!1,maxCount:0,lineNumber:!0,noFilename:!1,withFilename:!1,nullSeparator:!1,byteOffset:!1,column:!1,vimgrep:!1,replace:null,afterContext:0,beforeContext:0,contextSeparator:`--`,quiet:!1,heading:!1,passthru:!1,includeZero:!1,sort:`path`,json:!1,globs:[],iglobs:[],globCaseInsensitive:!1,types:[],typesNot:[],typeAdd:[],typeClear:[],hidden:!1,noIgnore:!1,noIgnoreDot:!1,noIgnoreVcs:!1,ignoreFiles:[],maxDepth:256,maxFilesize:536870912,followSymlinks:!1,searchZip:!1,searchBinary:!1,preprocessor:null,preprocessorGlobs:[]}}var Txe=B(()=>{});function Exe(e){let t=e.match(/^(\d+)([KMG])?$/i);if(!t)return 0;let n=parseInt(t[1],10);switch((t[2]||``).toUpperCase()){case`K`:return n*1024;case`M`:return n*1024*1024;case`G`:return n*1024*1024*1024;default:return n}}function Dxe(e){return/^\d+[KMG]?$/i.test(e)?null:{stdout:``,stderr:`rg: invalid --max-filesize value: ${e} +`,exitCode:1}}function Oxe(e,t){return!/^\d+$/.test(t)||!Number.isSafeInteger(Number(t))?{stdout:``,stderr:`rg: invalid --${e} value: ${t} +`,exitCode:1}:null}function cK(e){return null}function kxe(e){e.hidden?e.searchBinary=!0:e.noIgnore?e.hidden=!0:e.noIgnore=!0}function Axe(e,t,n){let r=e[t];for(let i of uK){if(r.startsWith(`--${i.long}=`)){let e=lK(n,i,r.slice(`--${i.long}=`.length));return e?{newIndex:t,error:e}:{newIndex:t}}if(i.short&&r.startsWith(`-${i.short}`)&&r.length>2){let e=lK(n,i,r.slice(2));return e?{newIndex:t,error:e}:{newIndex:t}}if(i.short&&r===`-${i.short}`||r===`--${i.long}`){if(t+1>=e.length)return null;let r=e[t+1],a=lK(n,i,r);return a?{newIndex:t+1,error:a}:{newIndex:t+1}}}return null}function jxe(e){return uK.find(t=>t.short===e)}function lK(e,t,n){if(t.validate){let e=t.validate(n);if(e)return e}if(t.ignored||!t.target)return;let r=t.parse?t.parse(n):n;t.multi?e[t.target].push(r):e[t.target]=r}function Mxe(e,t){let n=e[t];if(n===`--sort`&&t+1=e.length)return{success:!1,error:oV(`rg`,`-${n}`)};let i=lK(t,r,e[c+1]);if(i)return{success:!1,error:i};c++;continue}}let r=dK.get(n);if(r){r(t);continue}if(n.startsWith(`--`))return{success:!1,error:oV(`rg`,n)};if(n.length===1)return{success:!1,error:oV(`rg`,`-${n}`)}}}else n===null&&t.patterns.length===0&&t.patternFiles.length===0?n=l:r.push(l)}return(i>=0||o>=0)&&(t.afterContext=Math.max(i>=0?i:0,o>=0?o:0)),(a>=0||o>=0)&&(t.beforeContext=Math.max(a>=0?a:0,o>=0?o:0)),n!==null&&t.patterns.push(n),(t.column||t.vimgrep)&&(s=!0),{success:!0,options:t,paths:r,explicitLineNumbers:s}}var uK,dK,fK,Ixe=B(()=>{sV(),Txe(),uK=[{short:`g`,long:`glob`,target:`globs`,multi:!0},{long:`iglob`,target:`iglobs`,multi:!0},{short:`t`,long:`type`,target:`types`,multi:!0,validate:cK},{short:`T`,long:`type-not`,target:`typesNot`,multi:!0,validate:cK},{long:`type-add`,target:`typeAdd`,multi:!0},{long:`type-clear`,target:`typeClear`,multi:!0},{short:`m`,long:`max-count`,target:`maxCount`,parse:parseInt},{short:`e`,long:`regexp`,target:`patterns`,multi:!0},{short:`f`,long:`file`,target:`patternFiles`,multi:!0},{short:`r`,long:`replace`,target:`replace`},{short:`d`,long:`max-depth`,target:`maxDepth`,parse:e=>Number(e),validate:e=>Oxe(`max-depth`,e)},{long:`max-filesize`,target:`maxFilesize`,parse:Exe,validate:Dxe},{long:`context-separator`,target:`contextSeparator`},{short:`j`,long:`threads`,ignored:!0},{long:`ignore-file`,target:`ignoreFiles`,multi:!0},{long:`pre`,target:`preprocessor`},{long:`pre-glob`,target:`preprocessorGlobs`,multi:!0}],dK=new Map([[`i`,e=>{e.ignoreCase=!0,e.caseSensitive=!1,e.smartCase=!1}],[`--ignore-case`,e=>{e.ignoreCase=!0,e.caseSensitive=!1,e.smartCase=!1}],[`s`,e=>{e.caseSensitive=!0,e.ignoreCase=!1,e.smartCase=!1}],[`--case-sensitive`,e=>{e.caseSensitive=!0,e.ignoreCase=!1,e.smartCase=!1}],[`S`,e=>{e.smartCase=!0,e.ignoreCase=!1,e.caseSensitive=!1}],[`--smart-case`,e=>{e.smartCase=!0,e.ignoreCase=!1,e.caseSensitive=!1}],[`F`,e=>{e.fixedStrings=!0}],[`--fixed-strings`,e=>{e.fixedStrings=!0}],[`w`,e=>{e.wordRegexp=!0}],[`--word-regexp`,e=>{e.wordRegexp=!0}],[`x`,e=>{e.lineRegexp=!0}],[`--line-regexp`,e=>{e.lineRegexp=!0}],[`v`,e=>{e.invertMatch=!0}],[`--invert-match`,e=>{e.invertMatch=!0}],[`U`,e=>{e.multiline=!0}],[`--multiline`,e=>{e.multiline=!0}],[`--multiline-dotall`,e=>{e.multilineDotall=!0,e.multiline=!0}],[`c`,e=>{e.count=!0}],[`--count`,e=>{e.count=!0}],[`--count-matches`,e=>{e.countMatches=!0}],[`l`,e=>{e.filesWithMatches=!0}],[`--files`,e=>{e.files=!0}],[`--files-with-matches`,e=>{e.filesWithMatches=!0}],[`--files-without-match`,e=>{e.filesWithoutMatch=!0}],[`--stats`,e=>{e.stats=!0}],[`o`,e=>{e.onlyMatching=!0}],[`--only-matching`,e=>{e.onlyMatching=!0}],[`q`,e=>{e.quiet=!0}],[`--quiet`,e=>{e.quiet=!0}],[`N`,e=>{e.lineNumber=!1}],[`--no-line-number`,e=>{e.lineNumber=!1}],[`H`,e=>{e.withFilename=!0}],[`--with-filename`,e=>{e.withFilename=!0}],[`I`,e=>{e.noFilename=!0}],[`--no-filename`,e=>{e.noFilename=!0}],[`0`,e=>{e.nullSeparator=!0}],[`--null`,e=>{e.nullSeparator=!0}],[`b`,e=>{e.byteOffset=!0}],[`--byte-offset`,e=>{e.byteOffset=!0}],[`--column`,e=>{e.column=!0,e.lineNumber=!0}],[`--no-column`,e=>{e.column=!1}],[`--vimgrep`,e=>{e.vimgrep=!0,e.column=!0,e.lineNumber=!0}],[`--json`,e=>{e.json=!0}],[`--hidden`,e=>{e.hidden=!0}],[`--no-ignore`,e=>{e.noIgnore=!0}],[`--no-ignore-dot`,e=>{e.noIgnoreDot=!0}],[`--no-ignore-vcs`,e=>{e.noIgnoreVcs=!0}],[`L`,e=>{e.followSymlinks=!0}],[`--follow`,e=>{e.followSymlinks=!0}],[`z`,e=>{e.searchZip=!0}],[`--search-zip`,e=>{e.searchZip=!0}],[`a`,e=>{e.searchBinary=!0}],[`--text`,e=>{e.searchBinary=!0}],[`--heading`,e=>{e.heading=!0}],[`--passthru`,e=>{e.passthru=!0}],[`--include-zero`,e=>{e.includeZero=!0}],[`--glob-case-insensitive`,e=>{e.globCaseInsensitive=!0}]]),fK=new Set([`n`,`--line-number`])});function Lxe(e){return`'${e.replace(/'/g,`'\\''`)}'`}function pK(e){return e.map(Lxe).join(` `)}var mK=B(()=>{});async function hK(e,t,n=!1,r=!1,i=[]){let a=new _K(e,t,n,r);await a.load(t);for(let n of i)try{let r=e.resolvePath(t,n),i=await e.readFile(r);a.addPatternsFromContent(i,t)}catch{}return a}var gK,_K,Rxe=B(()=>{yG(),gK=class{patterns=[];basePath;constructor(e=`/`){this.basePath=e}parse(e){let t=e.split(` +`);for(let e of t){let t=e.replace(/\s+$/,``);if(!t||t.startsWith(`#`))continue;let n=!1;t.startsWith(`!`)&&(n=!0,t=t.slice(1));let r=!1;t.endsWith(`/`)&&(r=!0,t=t.slice(0,-1));let i=!1;t.startsWith(`/`)?(i=!0,t=t.slice(1)):t.includes(`/`)&&!t.startsWith(`**/`)&&(i=!0);let a=this.patternToRegex(t,i);this.patterns.push({pattern:e,regex:a,negated:n,directoryOnly:r,rooted:i})}}patternToRegex(e,t){let n=``;n=t?`^`:`(?:^|/)`;let r=0;for(;r=2&&e[0]===31&&e[1]===139}function Bxe(e){let t=!1;for(let n=0;ne.limits.maxStringLength||t>Math.floor(e.limits.maxLiveBytes/3))throw new H(t>e.limits.maxStringLength?`rg: pattern file exceeds string limit (${e.limits.maxStringLength} bytes)`:`rg: live byte limit exceeded (${e.limits.maxLiveBytes} bytes)`,`string_length`);return e.executionScope?.reserveBytes(`rg pattern files`,t*3,`rg`)??{release:()=>{}}}function Vxe(e,t,n){let r=0;for(let i=0;i<=t.length;i++)if(!(ir){if(e.length>=n.limits.maxArrayElements)throw new H(`rg: pattern limit exceeded (${n.limits.maxArrayElements})`,`iterations`);n.executionScope?.consumeWork(1,`rg pattern insertion`),e.push(t.slice(r,i))}r=i+1}}function yK(e,t,n){if(t>e.limits.maxInputBytes-n)throw new H(`rg: aggregate input size limit exceeded (${e.limits.maxInputBytes} bytes)`,`string_length`);return e.executionScope?.consumeInput(t,`rg pattern files`),n+t}async function Hxe(e){let{ctx:t,options:n,paths:r,explicitLineNumbers:i}=e;for(let e of n.globs){let t=Bxe(e.startsWith(`!`)?e.slice(1):e);if(t)return{stdout:``,stderr:`${t} +`,exitCode:1}}if(n.files)return Gxe(t,[...n.patterns,...r],n);if(n.patterns.length>t.limits.maxArrayElements)throw new H(`rg: pattern limit exceeded (${t.limits.maxArrayElements})`,`iterations`);let a=n.patterns.slice(),o=[],s=0,c,l;try{for(let e of n.patternFiles)try{let n,r;if(e===`-`)n=t.stdin,r=t.stdin.length,s=yK(t,r,s);else{let i=t.fs.resolvePath(t.cwd,e);r=(await t.fs.stat(i)).size,s=yK(t,r,s);let a=vK(t,r);o.push(a),n=await xB(t.fs,i);let c=n.length;if(c>r)throw new H(`rg: pattern file grew while being read`,`string_length`);r=c}e===`-`&&o.push(vK(t,r));let i=vB(n,t.limits.maxStringLength);t.executionScope?.consumeWork(i.length,`rg pattern file parsing`),Vxe(a,i,t)}catch(t){return nV(t),{stdout:``,stderr:`rg: ${e}: No such file or directory +`,exitCode:2}}if(a.length===0)return n.patternFiles.length>0?{stdout:``,stderr:``,exitCode:1}:{stdout:``,stderr:`rg: no pattern given +`,exitCode:2};let e=Uxe(n,a);try{let t=Wxe(a,n,e);c=t.regex,l=t.kResetGroup}catch{return{stdout:``,stderr:`rg: invalid regex: ${a.join(`, `)} +`,exitCode:2}}}finally{for(let e of o)e.release()}let u=n.patternFiles.includes(`-`),d=vB(t.stdin);if(r.length===0&&d.length>0&&!u){let e=EG(d,c,{invertMatch:n.invertMatch,showLineNumbers:n.lineNumber,countOnly:n.count,countMatches:n.countMatches,filename:``,onlyMatching:n.onlyMatching,beforeContext:n.beforeContext,afterContext:n.afterContext,maxCount:n.maxCount,contextSeparator:n.contextSeparator,showColumn:n.column,vimgrep:n.vimgrep,showByteOffset:n.byteOffset,replace:n.replace===null?null:kG(n.replace),passthru:n.passthru,multiline:n.multiline,kResetGroup:l,maxWork:t.limits.maxLoopIterations,maxMatches:t.limits.maxArrayElements,signal:t.signal});return n.quiet?{stdout:``,stderr:``,exitCode:+!e.matched}:n.filesWithMatches?{stdout:e.matched?`(standard input) +`:``,stderr:``,exitCode:+!e.matched}:n.filesWithoutMatch?{stdout:e.matched?``:`(standard input) +`,stderr:``,exitCode:+!!e.matched}:{stdout:e.output,stderr:``,exitCode:+!e.matched}}let f=r.length===0?[`.`]:r,p=null;n.noIgnore||(p=await hK(t.fs,t.cwd,n.noIgnoreDot,n.noIgnoreVcs,n.ignoreFiles));let m=new oK;for(let e of n.typeClear)m.clearType(e);for(let e of n.typeAdd)m.addType(e);let{files:h,singleExplicitFile:g}=await bK(t,f,n,p,m);if(h.length===0)return{stdout:``,stderr:``,exitCode:1};let _=!n.noFilename&&(n.withFilename||!g||h.length>1),v=n.lineNumber;return i||(g&&h.length===1&&(v=!1),n.onlyMatching&&(v=!1)),Yxe(t,h,c,n,_,v,l)}function Uxe(e,t){return e.caseSensitive?!1:e.ignoreCase?!0:e.smartCase?!t.some(e=>/[A-Z]/.test(e)):!1}function Wxe(e,t,n){let r;return r=e.length===1?e[0]:e.map(e=>t.fixedStrings?e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`):`(?:${e})`).join(`|`),OG(r,{mode:t.fixedStrings&&e.length===1?`fixed`:`perl`,ignoreCase:n,wholeWord:t.wordRegexp,lineRegexp:t.lineRegexp,multiline:t.multiline,multilineDotall:t.multilineDotall})}async function bK(e,t,n,r,i){let a=[],o=new EH({limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:`rg`}),s=0,c=0;for(let l of t){o.checkpoint();let t=e.fs.resolvePath(e.cwd,l);try{let u=await e.fs.stat(t);if(u.isFile){if(s++,n.maxFilesize>0&&u.size>n.maxFilesize)continue;if(SK(l,n,r,t,i)){if(a.length>=e.limits.maxArrayElements)throw new H(`rg: file collection limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);a.push(l)}}else u.isDirectory&&(c++,await xK(e,l,t,0,n,r,i,a,o,new Set))}catch(e){nV(e)}}return{files:n.sort===`path`?a.sort():a,singleExplicitFile:s===1&&c===0}}async function xK(e,t,n,r,i,a,o,s,c,l){if(r>=i.maxDepth)return;c.visit(r);let u;if(i.followSymlinks)try{let t=await e.fs.stat(n);if(u=t.identity===void 0?t.dev!==void 0&&t.ino!==void 0?`inode:${String(t.dev)}:${String(t.ino)}`:`path:${await e.fs.realpath(n)}`:`identity:${t.identity}`,l.has(u))return;l.add(u)}catch(e){nV(e);return}a&&await a.loadForDirectory(n);try{let u=e.fs.readdirWithFileTypes?await e.fs.readdirWithFileTypes(n):(await e.fs.readdir(n)).map(e=>({name:e,isFile:void 0}));for(let d of u){c.checkpoint();let u=d.name;if(!i.noIgnore&&_K.isCommonIgnored(u))continue;let f=u.startsWith(`.`),p=t===`.`?u:t===`./`?`./${u}`:t.endsWith(`/`)?`${t}${u}`:`${t}/${u}`,m=e.fs.resolvePath(n,u),h,g,_=!1;if(d.isFile!==void 0&&`isDirectory`in d){let t=d;if(_=t.isSymbolicLink===!0,_&&!i.followSymlinks)continue;if(_&&i.followSymlinks)try{let t=await e.fs.stat(m);h=t.isFile,g=t.isDirectory}catch{continue}else h=t.isFile,g=t.isDirectory}else try{let t=e.fs.lstat?await e.fs.lstat(m):await e.fs.stat(m);if(_=t.isSymbolicLink===!0,_&&!i.followSymlinks)continue;let n=_&&i.followSymlinks?await e.fs.stat(m):t;h=n.isFile,g=n.isDirectory}catch{continue}if(!a?.matches(m,g)&&(!f||i.hidden||a?.isWhitelisted(m,g))){if(g)await xK(e,p,m,r+1,i,a,o,s,c,l);else if(h){if(c.visit(r+1),i.maxFilesize>0)try{if((await e.fs.stat(m)).size>i.maxFilesize)continue}catch{continue}if(SK(p,i,a,m,o)){if(s.length>=e.limits.maxArrayElements)throw new H(`rg: file collection limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);s.push(p)}}}}}catch(e){nV(e)}finally{u!==void 0&&l.delete(u)}}function SK(e,t,n,r,i){let a=e.split(`/`).pop()||e;if(n?.matches(r,!1)||t.types.length>0&&!i.matchesType(a,t.types)||t.typesNot.length>0&&i.matchesType(a,t.typesNot))return!1;if(t.globs.length>0){let n=t.globCaseInsensitive,r=t.globs.filter(e=>!e.startsWith(`!`)),i=t.globs.filter(e=>e.startsWith(`!`)).map(e=>e.slice(1));if(r.length>0){let t=!1;for(let i of r)if(CK(a,i,n)||CK(e,i,n)){t=!0;break}if(!t)return!1}for(let t of i)if(t.startsWith(`/`)){if(CK(e,t.slice(1),n))return!1}else if(CK(a,t,n)||CK(e,t,n))return!1}if(t.iglobs.length>0){let n=t.iglobs.filter(e=>!e.startsWith(`!`)),r=t.iglobs.filter(e=>e.startsWith(`!`)).map(e=>e.slice(1));if(n.length>0){let t=!1;for(let r of n)if(CK(a,r,!0)||CK(e,r,!0)){t=!0;break}if(!t)return!1}for(let t of r)if(t.startsWith(`/`)){if(CK(e,t.slice(1),!0))return!1}else if(CK(a,t,!0)||CK(e,t,!0))return!1}return!0}function CK(e,t,n=!1){let r=`^`;for(let e=0;en.size)throw r?.release(),new H(`rg: file grew while being read`,`string_length`);if(e.executionScope?.consumeInput(i.byteLength,`rg`),zxe(i)){let t;try{let n=Math.min(e.limits.maxStringLength,e.limits.maxOutputSize,Math.floor((e.executionScope?.remainingLiveBytes??e.limits.maxLiveBytes)/2));t=e.executionScope?.reserveBytes(`rg decompressed text`,n*2,`rg`);let a=(0,SR.gunzipSync)(i,{maxOutputLength:n}),o=new TextDecoder().decode(a);return{content:o,isBinary:o.slice(0,8192).includes(`\0`),lease:Jxe(r,t)}}catch(e){return t?.release(),r?.release(),nV(e),null}}r?.release()}let a=await e.fs.stat(t);i=e.executionScope?.reserveBytes(`rg file text`,a.size*2,`rg`);let o=await xB(e.fs,t),s=o.length;if(s>a.size)throw new H(`rg: file grew while being read`,`string_length`);e.executionScope?.consumeInput(s,`rg`);let c=vB(o,e.limits.maxStringLength);return{content:c,isBinary:c.slice(0,8192).includes(`\0`),lease:i}}catch(e){return i?.release(),nV(e),null}}function Jxe(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return{release:()=>{for(let e of t)e.release()}}}async function Yxe(e,t,n,r,i,a,o){let s=``,c=!1,l=[],u=0,d=0,f=0,p=r.searchZip?2:50;e:for(let m=0;m{let s=await qxe(e,e.fs.resolvePath(e.cwd,t),t,r);if(!s)return null;let{content:c,isBinary:l,lease:u}=s;if(f+=c.length,l&&!r.searchBinary)return u?.release(),null;let d=i&&!r.heading?t:``;try{let i=EG(c,n,{invertMatch:r.invertMatch,showLineNumbers:a,countOnly:r.count,countMatches:r.countMatches,filename:d,onlyMatching:r.onlyMatching,beforeContext:r.beforeContext,afterContext:r.afterContext,maxCount:r.maxCount,contextSeparator:r.contextSeparator,showColumn:r.column,vimgrep:r.vimgrep,showByteOffset:r.byteOffset,replace:r.replace===null?null:kG(r.replace),passthru:r.passthru,multiline:r.multiline,kResetGroup:o,maxWork:e.limits.maxLoopIterations,maxMatches:e.limits.maxArrayElements,signal:e.signal});return r.json&&i.matched?{file:t,result:i,content:c,isBinary:!1,lease:u}:(u?.release(),{file:t,result:i})}catch(e){throw u?.release(),e}}));for(let e of g){if(!e)continue;let{file:t,result:i}=e;if(i.matched){if(c=!0,d++,u+=i.matchCount,r.quiet&&!r.json)break e;if(r.json&&!r.quiet){let a=e.content||``;l.push(JSON.stringify({type:`begin`,data:{path:{text:t}}}));let o=a.split(` +`);n.lastIndex=0;let s=0;for(let e=0;e0){let n={type:`match`,data:{path:{text:t},lines:{text:`${i} +`},line_number:e+1,absolute_offset:s,submatches:a}};l.push(JSON.stringify(n))}s+=i.length+1}l.push(JSON.stringify({type:`end`,data:{path:{text:t},binary_offset:null,stats:{elapsed:{secs:0,nanos:0,human:`0s`},searches:1,searches_with_match:1,bytes_searched:a.length,bytes_printed:0,matched_lines:i.matchCount,matches:i.matchCount}}}))}else if(r.filesWithMatches){let e=r.nullSeparator?`\0`:` +`;s+=`${t}${e}`}else r.filesWithoutMatch||(r.heading&&!r.noFilename&&(s+=`${t} +`),s+=i.output)}else if(r.filesWithoutMatch){let e=r.nullSeparator?`\0`:` +`;s+=`${t}${e}`}else r.includeZero&&(r.count||r.countMatches)&&(s+=i.output);e.lease?.release()}}r.json&&(l.push(JSON.stringify({type:`summary`,data:{elapsed_total:{secs:0,nanos:0,human:`0s`},stats:{elapsed:{secs:0,nanos:0,human:`0s`},searches:t.length,searches_with_match:d,bytes_searched:f,bytes_printed:0,matched_lines:u,matches:u}}})),s=`${l.join(` +`)} +`);let m=r.quiet&&!r.json?``:s;if(r.stats&&!r.json){let e=[``,`${u} matches`,`${u} matched lines`,`${d} files contained matches`,`${t.length} files searched`,`${f} bytes searched`].join(` +`);m+=`${e} +`}let h;return h=r.filesWithoutMatch?s.length>0?0:1:+!c,{stdout:m,stderr:``,exitCode:h}}var Xxe=B(()=>{sH(),kB(),rV(),DH(),mK(),U(),yG(),jG(),sK(),Rxe()}),wK={};wz(wK,{flagsForFuzzing:()=>DK,rgCommand:()=>EK});var TK,EK,DK,Zxe=B(()=>{sV(),sK(),Ixe(),Xxe(),TK={name:`rg`,summary:`recursively search for a pattern`,usage:`rg [OPTIONS] PATTERN [PATH ...]`,description:`rg (ripgrep) recursively searches directories for a regex pattern. +Unlike grep, rg is recursive by default and respects .gitignore files. + +EXAMPLES: + rg foo Search for 'foo' in current directory + rg foo src/ Search in src/ directory + rg -i foo Case-insensitive search + rg -w foo Match whole words only + rg -t js foo Search only JavaScript files + rg -g '*.ts' foo Search files matching glob + rg --hidden foo Include hidden files + rg -l foo List files with matches only`,options:[`-e, --regexp PATTERN search for PATTERN (can be used multiple times)`,`-f, --file FILE read patterns from FILE, one per line`,`-i, --ignore-case case-insensitive search`,`-s, --case-sensitive case-sensitive search (overrides smart-case)`,`-S, --smart-case smart case (default: case-insensitive unless pattern has uppercase)`,`-F, --fixed-strings treat pattern as literal string`,`-w, --word-regexp match whole words only`,`-x, --line-regexp match whole lines only`,`-v, --invert-match select non-matching lines`,`-r, --replace TEXT replace matches with TEXT`,`-c, --count print count of matching lines per file`,` --count-matches print count of individual matches per file`,`-l, --files-with-matches print only file names with matches`,` --files-without-match print file names without matches`,` --files list files that would be searched`,`-o, --only-matching print only matching parts`,`-m, --max-count NUM stop after NUM matches per file`,`-q, --quiet suppress output, exit 0 on match`,` --stats print search statistics`,`-n, --line-number print line numbers (default: on)`,`-N, --no-line-number do not print line numbers`,`-I, --no-filename suppress the prefixing of file names`,`-0, --null use NUL as filename separator`,`-b, --byte-offset show byte offset of each match`,` --column show column number of first match`,` --vimgrep show results in vimgrep format`,` --json show results in JSON Lines format`,`-A NUM print NUM lines after each match`,`-B NUM print NUM lines before each match`,`-C NUM print NUM lines before and after each match`,` --context-separator SEP separator for context groups (default: --)`,`-U, --multiline match patterns across lines`,`-z, --search-zip search in compressed files (gzip only)`,`-g, --glob GLOB include files matching GLOB`,`-t, --type TYPE only search files of TYPE (e.g., js, py, ts)`,`-T, --type-not TYPE exclude files of TYPE`,`-L, --follow follow symbolic links`,`-u, --unrestricted reduce filtering (-u: no ignore, -uu: +hidden, -uuu: +binary)`,`-a, --text search binary files as text`,` --hidden search hidden files and directories`,` --no-ignore don't respect .gitignore/.ignore files`,`-d, --max-depth NUM maximum search depth`,` --sort TYPE sort files (path, none)`,` --heading show file path above matches`,` --passthru print all lines (non-matches use - separator)`,` --include-zero include files with 0 matches in count output`,` --type-list list all available file types`,` --help display this help and exit`]},EK={name:`rg`,async execute(e,t){if(aV(e))return iV(TK);if(e.includes(`--type-list`))return{stdout:Cxe(),stderr:``,exitCode:0};let n=Fxe(e);return n.success?Hxe({ctx:t,options:n.options,paths:n.paths,explicitLineNumbers:n.explicitLineNumbers}):n.error}},DK={name:`rg`,flags:[{flag:`-i`,type:`boolean`},{flag:`-s`,type:`boolean`},{flag:`-S`,type:`boolean`},{flag:`-F`,type:`boolean`},{flag:`-w`,type:`boolean`},{flag:`-x`,type:`boolean`},{flag:`-v`,type:`boolean`},{flag:`-c`,type:`boolean`},{flag:`-l`,type:`boolean`},{flag:`-o`,type:`boolean`},{flag:`-n`,type:`boolean`},{flag:`-N`,type:`boolean`},{flag:`--hidden`,type:`boolean`},{flag:`--no-ignore`,type:`boolean`},{flag:`-m`,type:`value`,valueHint:`number`},{flag:`-A`,type:`value`,valueHint:`number`},{flag:`-B`,type:`value`,valueHint:`number`},{flag:`-C`,type:`value`,valueHint:`number`},{flag:`-g`,type:`value`,valueHint:`pattern`},{flag:`-t`,type:`value`,valueHint:`string`},{flag:`-T`,type:`value`,valueHint:`string`}],needsArgs:!0}});function OK(e,t,n){if(!e||iB.isInSandboxedContext())return;let r=`${t} ${n} attempted outside defense context`;throw new eB(r,{timestamp:Date.now(),type:`missing_defense_context`,message:r,path:`DefenseInDepthBox.context`,stack:Error().stack,executionId:iB.getCurrentExecutionId()})}async function kK(e,t,n,r){OK(e,t,`${n} (pre-await)`);let i=await r();return OK(e,t,`${n} (post-await)`),i}var AK=B(()=>{aB()});function jK(e){let t=``,n=0,r=!1;for(;n=127?`\\${i.toString(8).padStart(3,`0`)}`:r}return`${t}$`}var NK,$xe=B(()=>{NK=new Map([[`alnum`,`a-zA-Z0-9`],[`alpha`,`a-zA-Z`],[`ascii`,`\\x00-\\x7F`],[`blank`,` \\t`],[`cntrl`,`\\x00-\\x1F\\x7F`],[`digit`,`0-9`],[`graph`,`!-~`],[`lower`,`a-z`],[`print`,` -~`],[`punct`,"!-/:-@\\[-`{-~"],[`space`,` \\t\\n\\r\\f\\v`],[`upper`,`A-Z`],[`word`,`a-zA-Z0-9_`],[`xdigit`,`0-9A-Fa-f`]])});function eSe(e,t,n){return{patternSpace:``,holdSpace:``,lineNumber:0,totalLines:e,deleted:!1,printed:!1,quit:!1,quitSilent:!1,exitCode:void 0,errorMessage:void 0,appendBuffer:[],substitutionMade:!1,lineNumberOutput:[],nCommandOutput:[],restartCycle:!1,inDRestartedCycle:!1,currentFilename:t,pendingFileReads:[],pendingFileWrites:[],rangeStates:n||new Map,linesConsumedInCycle:0}}function tSe(e){return typeof e==`object`&&`first`in e&&`step`in e}function nSe(e){return typeof e==`object`&&`offset`in e}function PK(e,t,n,r,i){if(e===`$`)return t===n;if(typeof e==`number`)return t===e;if(tSe(e)){let{first:n,step:r}=e;return r===0?t===n:(t-n)%r===0&&t>=n}if(typeof e==`object`&&`pattern`in e)try{let t=e.pattern;return t===``&&i?.lastPattern?t=i.lastPattern:t!==``&&i&&(i.lastPattern=t),mG(MK(jK(t))).test(r)}catch{return!1}return!1}function FK(e){let t=e=>e===void 0?`undefined`:e===`$`?`$`:typeof e==`number`?String(e):`pattern`in e?`/${e.pattern}/`:`first`in e?`${e.first}~${e.step}`:`unknown`;return`${t(e.start)},${t(e.end)}`}function rSe(e,t,n,r,i,a){if(!e||!e.start&&!e.end)return!0;let o=e.start,s=e.end;if(o!==void 0&&s===void 0)return PK(o,t,n,r,a);if(o!==void 0&&s!==void 0){let c=typeof o==`object`&&`pattern`in o,l=typeof s==`object`&&`pattern`in s,u=nSe(s);if(u&&i){let c=FK(e),l=i.get(c);return l||(l={active:!1},i.set(c,l)),l.active?(t>=(l.startLine||t)+s.offset&&(l.active=!1,i.set(c,l)),!0):PK(o,t,n,r,a)?(l.active=!0,l.startLine=t,i.set(c,l),s.offset===0&&(l.active=!1,i.set(c,l)),!0):!1}if(!c&&!l&&!u){let r=typeof o==`number`?o:o===`$`?n:1,a=typeof s==`number`?s:n;if(r<=a)return t>=r&&t<=a;if(i){let n=FK(e),a=i.get(n);return a||(a={active:!1},i.set(n,a)),!a.completed&&t>=r&&(a.completed=!0,i.set(n,a),!0)}return!1}if(i){let c=FK(e),l=i.get(c);if(l||(l={active:!1},i.set(c,l)),l.active)return PK(s,t,n,r,a)&&(l.active=!1,typeof o==`number`&&(l.completed=!0),i.set(c,l)),!0;{if(l.completed)return!1;let e=!1;return e=typeof o==`number`?t>=o:PK(o,t,n,r,a),e?(l.active=!0,l.startLine=t,i.set(c,l),PK(s,t,n,r,a)&&(l.active=!1,typeof o==`number`&&(l.completed=!0),i.set(c,l)),!0):!1}}return PK(o,t,n,r,a)}return!0}function IK(e,t,n,r,i,a){let o=rSe(e,t,n,r,i,a);return e?.negated?!o:o}function iSe(e,t,n,r){let i=``,a=0,o=!1;for(;a<=e.length;){t.lastIndex=a;let n=t.exec(e);if(!n){i+=e.slice(a);break}if(n.index!==a){i+=e.slice(a,n.index),a=n.index,o=!1;continue}let s=n[0],c=n.slice(1);if(o&&s.length===0){if(a=1&&o<=9){r+=n[o-1]||``,i+=2;continue}r+=a,i+=2;continue}if(e[i]===`&`){r+=t,i++;continue}r+=e[i],i++}return r}function RK(e,t,n){if(t>0&&e.length>t)throw new H(`sed: ${n} size limit exceeded (${t} bytes)`,`string_length`)}function aSe(e,t,n){let{lineNumber:r,totalLines:i,patternSpace:a}=t;if(e.type===`label`){t.coverage?.hit(`sed:cmd:${e.type}`);return}if(IK(e.address,r,i,a,t.rangeStates,t))switch(t.coverage?.hit(`sed:cmd:${e.type}`),e.type){case`substitute`:{let n=e,r=``;n.global&&(r+=`g`),n.ignoreCase&&(r+=`i`);let i=n.pattern;i===``&&t.lastPattern?i=t.lastPattern:i!==``&&(t.lastPattern=i);let a=MK(n.extendedRegex?i:jK(i));try{let e=mG(a,r),i=e.test(t.patternSpace);if(e.lastIndex=0,i){if(t.substitutionMade=!0,n.nthOccurrence&&n.nthOccurrence>0&&!n.global){let e=0,r=n.nthOccurrence;t.patternSpace=mG(a,`g${n.ignoreCase?`i`:``}`).replace(t.patternSpace,(t,...i)=>{if(e++,e===r){let e=i.slice(0,-2);return LK(n.replacement,t,e)}return t})}else if(n.global){let e=mG(a,`g${n.ignoreCase?`i`:``}`);t.patternSpace=iSe(t.patternSpace,e,n.replacement,(e,t)=>LK(n.replacement,e,t))}else t.patternSpace=e.replace(t.patternSpace,(e,...t)=>{let r=t.slice(0,-2);return LK(n.replacement,e,r)});n.printOnMatch&&t.lineNumberOutput.push(t.patternSpace)}}catch{}break}case`print`:t.lineNumberOutput.push(t.patternSpace);break;case`printFirstLine`:{let e=t.patternSpace.indexOf(` +`);e===-1?t.lineNumberOutput.push(t.patternSpace):t.lineNumberOutput.push(t.patternSpace.slice(0,e));break}case`delete`:t.deleted=!0;break;case`deleteFirstLine`:{let e=t.patternSpace.indexOf(` +`);e===-1?t.deleted=!0:(t.patternSpace=t.patternSpace.slice(e+1),t.restartCycle=!0,t.inDRestartedCycle=!0);break}case`zap`:t.patternSpace=``;break;case`append`:t.appendBuffer.push(e.text);break;case`insert`:t.appendBuffer.unshift(`__INSERT__${e.text}`);break;case`change`:t.deleted=!0,t.changedText=e.text;break;case`hold`:t.holdSpace=t.patternSpace;break;case`holdAppend`:t.holdSpace?t.holdSpace+=` +${t.patternSpace}`:t.holdSpace=t.patternSpace,RK(t.holdSpace,n?.maxStringLength??0,`hold space`);break;case`get`:t.patternSpace=t.holdSpace;break;case`getAppend`:t.patternSpace+=` +${t.holdSpace}`,RK(t.patternSpace,n?.maxStringLength??0,`pattern space`);break;case`exchange`:{let e=t.patternSpace;t.patternSpace=t.holdSpace,t.holdSpace=e;break}case`next`:t.printed=!0;break;case`quit`:t.quit=!0,e.exitCode!==void 0&&(t.exitCode=e.exitCode);break;case`quitSilent`:t.quit=!0,t.quitSilent=!0,e.exitCode!==void 0&&(t.exitCode=e.exitCode);break;case`list`:{let e=Qxe(t.patternSpace);t.lineNumberOutput.push(e);break}case`printFilename`:t.currentFilename&&t.lineNumberOutput.push(t.currentFilename);break;case`version`:{let n=[4,8,0];if(e.minVersion){let r=e.minVersion.split(`.`),i=[],a=!1;for(let n of r){let r=parseInt(n,10);if(Number.isNaN(r)||r<0){t.quit=!0,t.exitCode=1,t.errorMessage=`sed: invalid version string: ${e.minVersion}`,a=!0;break}i.push(r)}if(!a){for(;i.length<3;)i.push(0);for(let r=0;r<3;r++){if(i[r]>n[r]){t.quit=!0,t.exitCode=1,t.errorMessage=`sed: this is not GNU sed version ${e.minVersion}`;break}if(i[r]a)throw new H(`sed: command execution exceeded maximum iterations (${a})`,`iterations`);if(t.deleted||t.quit||t.quitSilent||t.restartCycle)break;let c=e[s];if(c.type===`next`){if(IK(c.address,t.lineNumber,t.totalLines,t.patternSpace,t.rangeStates,t)){if(t.coverage?.hit(`sed:cmd:next`),t.nCommandOutput.push(t.patternSpace),n&&n.currentLineIndex+t.linesConsumedInCycle+1{U(),yG(),$xe(),BK=1e4}),VK,HK,cSe=B(()=>{U(),(function(e){e.NUMBER=`NUMBER`,e.DOLLAR=`DOLLAR`,e.PATTERN=`PATTERN`,e.STEP=`STEP`,e.RELATIVE_OFFSET=`RELATIVE_OFFSET`,e.LBRACE=`LBRACE`,e.RBRACE=`RBRACE`,e.SEMICOLON=`SEMICOLON`,e.NEWLINE=`NEWLINE`,e.COMMA=`COMMA`,e.NEGATION=`NEGATION`,e.COMMAND=`COMMAND`,e.SUBSTITUTE=`SUBSTITUTE`,e.TRANSLITERATE=`TRANSLITERATE`,e.LABEL_DEF=`LABEL_DEF`,e.BRANCH=`BRANCH`,e.BRANCH_ON_SUBST=`BRANCH_ON_SUBST`,e.BRANCH_ON_NO_SUBST=`BRANCH_ON_NO_SUBST`,e.TEXT_CMD=`TEXT_CMD`,e.FILE_READ=`FILE_READ`,e.FILE_READ_LINE=`FILE_READ_LINE`,e.FILE_WRITE=`FILE_WRITE`,e.FILE_WRITE_LINE=`FILE_WRITE_LINE`,e.EXECUTE=`EXECUTE`,e.VERSION=`VERSION`,e.EOF=`EOF`,e.ERROR=`ERROR`})(VK||={}),HK=class{maxInputLength;maxTokens;input;pos=0;line=1;column=1;constructor(e,t=1048576,n=1e5){this.maxInputLength=t,this.maxTokens=n,this.input=e}tokenize(){if(this.input.length>this.maxInputLength)throw new H(`sed: script size limit exceeded (${this.maxInputLength} bytes)`,`string_length`);let e=[];for(;this.pos=this.maxTokens-1)throw new H(`sed: token limit exceeded (${this.maxTokens})`,`array_elements`);e.push(t)}}return e.push(this.makeToken(VK.EOF,``)),e}makeToken(e,t,n){return{type:e,value:t,line:this.line,column:this.column,...n}}peek(e=0){return this.input[this.pos+e]||``}advance(){let e=this.input[this.pos++]||``;return e===` +`?(this.line++,this.column=1):this.column++,e}readEscapedString(e){let t=``;for(;this.pos=this.input.length)return null;let e=this.line,t=this.column,n=this.peek();return n===` +`?(this.advance(),{type:VK.NEWLINE,value:` +`,line:e,column:t}):n===`;`?(this.advance(),{type:VK.SEMICOLON,value:`;`,line:e,column:t}):n===`{`?(this.advance(),{type:VK.LBRACE,value:`{`,line:e,column:t}):n===`}`?(this.advance(),{type:VK.RBRACE,value:`}`,line:e,column:t}):n===`,`?(this.advance(),{type:VK.COMMA,value:`,`,line:e,column:t}):n===`!`?(this.advance(),{type:VK.NEGATION,value:`!`,line:e,column:t}):n===`$`?(this.advance(),{type:VK.DOLLAR,value:`$`,line:e,column:t}):this.isDigit(n)?this.readNumber():n===`+`&&this.isDigit(this.input[this.pos+1]||``)?this.readRelativeOffset():n===`/`?this.readPattern():n===`:`?this.readLabelDef():this.readCommand()}readNumber(){let e=this.line,t=this.column,n=``;for(;this.isDigit(this.peek());)n+=this.advance();if(this.peek()===`~`){this.advance();let r=``;for(;this.isDigit(this.peek());)r+=this.advance();let i=parseInt(n,10),a=parseInt(r,10)||0;return{type:VK.STEP,value:`${i}~${a}`,first:i,step:a,line:e,column:t}}return{type:VK.NUMBER,value:parseInt(n,10),line:e,column:t}}readRelativeOffset(){let e=this.line,t=this.column;this.advance();let n=``;for(;this.isDigit(this.peek());)n+=this.advance();let r=parseInt(n,10)||0;return{type:VK.RELATIVE_OFFSET,value:`+${r}`,offset:r,line:e,column:t}}readPattern(){let e=this.line,t=this.column;this.advance();let n=``,r=!1;for(;this.pos=`0`&&e<=`9`}}});function lSe(e,t=!1,n){if(n){if(e.length>n.maxArrayElements)throw new H(`sed: script count limit exceeded (${n.maxArrayElements})`,`array_elements`);let t=Math.max(0,e.length-1);for(let r of e)if(t+=V(r),t>n.maxStringLength)throw new H(`sed: script size limit exceeded (${n.maxStringLength} bytes)`,`string_length`)}let r=!1,i=!1,a=[];for(let t=0;t0&&a[a.length-1].endsWith(`\\`)){let e=a[a.length-1];a[a.length-1]=`${e} +${n}`}else a.push(n)}let o=a.join(` +`),s=new KK([o],t||i,n).parse();if(!s.error&&s.commands.length>0){let e=UK(s.commands);if(e)return{commands:[],error:e,silentMode:r,extendedRegexMode:i}}return{...s,silentMode:r,extendedRegexMode:i}}function UK(e){let t=new Set;WK(e,t);let n=GK(e,t);if(n)return`undefined label '${n}'`}function WK(e,t){for(let n of e)n.type===`label`?t.add(n.name):n.type===`group`&&WK(n.commands,t)}function GK(e,t){for(let n of e){if((n.type===`branch`||n.type===`branchOnSubst`||n.type===`branchOnNoSubst`)&&n.label&&!t.has(n.label))return n.label;if(n.type===`group`){let e=GK(n.commands,t);if(e)return e}}}var KK,uSe=B(()=>{U(),XB(),cSe(),KK=class{scripts;limits;tokens=[];pos=0;extendedRegex=!1;constructor(e,t=!1,n){this.scripts=e,this.limits=n,this.extendedRegex=t}parse(){let e=[];for(let t of this.scripts){let n=new HK(t,this.limits?.maxStringLength,this.limits?.maxArrayElements);for(this.tokens=n.tokenize(),this.pos=0;!this.isAtEnd();){if(this.check(VK.NEWLINE)||this.check(VK.SEMICOLON)){this.advance();continue}let t=this.pos,n=this.parseCommand();if(n.error)return{commands:[],error:n.error};if(n.command&&e.push(n.command),this.pos===t&&!this.isAtEnd())return{commands:[],error:`unknown command: '${this.peek()?.value??this.peek()?.type}'`}}}return{commands:e}}parseCommand(){let e=this.parseAddressRange();if(e?.error)return{command:null,error:e.error};let t=e?.address;for(this.check(VK.NEGATION)&&(this.advance(),t&&(t.negated=!0));this.check(VK.NEWLINE)||this.check(VK.SEMICOLON);)this.advance();if(this.isAtEnd())return t&&(t.start!==void 0||t.end!==void 0)?{command:null,error:`command expected`}:{command:null};let n=this.peek();switch(n.type){case VK.COMMAND:return this.parseSimpleCommand(n,t);case VK.SUBSTITUTE:return this.parseSubstituteFromToken(n,t);case VK.TRANSLITERATE:return this.parseTransliterateFromToken(n,t);case VK.LABEL_DEF:return this.advance(),{command:{type:`label`,name:n.label||``}};case VK.BRANCH:return this.advance(),{command:{type:`branch`,address:t,label:n.label}};case VK.BRANCH_ON_SUBST:return this.advance(),{command:{type:`branchOnSubst`,address:t,label:n.label}};case VK.BRANCH_ON_NO_SUBST:return this.advance(),{command:{type:`branchOnNoSubst`,address:t,label:n.label}};case VK.TEXT_CMD:return this.advance(),this.parseTextCommand(n,t);case VK.FILE_READ:return this.advance(),{command:{type:`readFile`,address:t,filename:n.filename||``}};case VK.FILE_READ_LINE:return this.advance(),{command:{type:`readFileLine`,address:t,filename:n.filename||``}};case VK.FILE_WRITE:return this.advance(),{command:{type:`writeFile`,address:t,filename:n.filename||``}};case VK.FILE_WRITE_LINE:return this.advance(),{command:{type:`writeFirstLine`,address:t,filename:n.filename||``}};case VK.EXECUTE:return this.advance(),{command:{type:`execute`,address:t,command:n.command}};case VK.VERSION:return this.advance(),{command:{type:`version`,address:t,minVersion:n.label}};case VK.LBRACE:return this.parseGroup(t);case VK.RBRACE:return{command:null};case VK.ERROR:return{command:null,error:`invalid command: ${n.value}`};default:return t&&(t.start!==void 0||t.end!==void 0)?{command:null,error:`command expected`}:{command:null}}}parseSimpleCommand(e,t){this.advance();let n=e.value;switch(n){case`p`:return{command:{type:`print`,address:t}};case`P`:return{command:{type:`printFirstLine`,address:t}};case`d`:return{command:{type:`delete`,address:t}};case`D`:return{command:{type:`deleteFirstLine`,address:t}};case`h`:return{command:{type:`hold`,address:t}};case`H`:return{command:{type:`holdAppend`,address:t}};case`g`:return{command:{type:`get`,address:t}};case`G`:return{command:{type:`getAppend`,address:t}};case`x`:return{command:{type:`exchange`,address:t}};case`n`:return{command:{type:`next`,address:t}};case`N`:return{command:{type:`nextAppend`,address:t}};case`q`:return{command:{type:`quit`,address:t}};case`Q`:return{command:{type:`quitSilent`,address:t}};case`z`:return{command:{type:`zap`,address:t}};case`=`:return{command:{type:`lineNumber`,address:t}};case`l`:return{command:{type:`list`,address:t}};case`F`:return{command:{type:`printFilename`,address:t}};default:return{command:null,error:`unknown command: ${n}`}}}parseSubstituteFromToken(e,t){this.advance();let n=e.flags||``,r,i=n.match(/(\d+)/);return i&&(r=parseInt(i[1],10)),{command:{type:`substitute`,address:t,pattern:e.pattern||``,replacement:e.replacement||``,global:n.includes(`g`),ignoreCase:n.includes(`i`)||n.includes(`I`),printOnMatch:n.includes(`p`),nthOccurrence:r,extendedRegex:this.extendedRegex}}}parseTransliterateFromToken(e,t){this.advance();let n=e.source||``,r=e.dest||``;return n.length===r.length?{command:{type:`transliterate`,address:t,source:n,dest:r}}:{command:null,error:`transliteration sets must have same length`}}parseTextCommand(e,t){let n=e.value,r=e.text||``;switch(n){case`a`:return{command:{type:`append`,address:t,text:r}};case`i`:return{command:{type:`insert`,address:t,text:r}};case`c`:return{command:{type:`change`,address:t,text:r}};default:return{command:null,error:`unknown text command: ${n}`}}}parseGroup(e){this.advance();let t=[];for(;!this.isAtEnd()&&!this.check(VK.RBRACE);){if(this.check(VK.NEWLINE)||this.check(VK.SEMICOLON)){this.advance();continue}let e=this.pos,n=this.parseCommand();if(n.error)return{command:null,error:n.error};if(n.command&&t.push(n.command),this.pos===e&&!this.isAtEnd())return{command:null,error:`unknown command: '${this.peek()?.value??this.peek()?.type}'`}}return this.check(VK.RBRACE)?(this.advance(),{command:{type:`group`,address:e,commands:t}}):{command:null,error:`unmatched brace in grouped commands`}}parseAddressRange(){if(this.check(VK.COMMA))return{error:`expected context address`};let e=this.parseAddress();if(e===void 0)return;let t;if(this.check(VK.RELATIVE_OFFSET))t={offset:this.advance().offset||0};else if(this.check(VK.COMMA)&&(this.advance(),t=this.parseAddress(),t===void 0))return{error:`expected context address`};return{address:{start:e,end:t}}}parseAddress(){let e=this.peek();switch(e.type){case VK.NUMBER:return this.advance(),e.value;case VK.DOLLAR:return this.advance(),`$`;case VK.PATTERN:return this.advance(),{pattern:e.pattern||e.value};case VK.STEP:return this.advance(),{first:e.first||0,step:e.step||0};case VK.RELATIVE_OFFSET:return this.advance(),{offset:e.offset||0};default:return}}peek(){return this.tokens[this.pos]||{type:VK.EOF,value:``,line:0,column:0}}advance(){return this.isAtEnd()||this.pos++,this.tokens[this.pos-1]}check(e){return this.peek().type===e}isAtEnd(){return this.peek().type===VK.EOF}}}),qK={};wz(qK,{flagsForFuzzing:()=>ZK,sedCommand:()=>XK});async function JK(e,t,n,r={}){let{limits:i,filename:a,fs:o,cwd:s,coverage:c,requireDefenseContext:l}=r;OK(l,`sed`,`processing entry`);let u=(e,t)=>kK(l,`sed`,e,t),d=e.endsWith(` +`),f=e.split(` +`);f.length>0&&f[f.length-1]===``&&f.pop();let p=f.length,m=``,h,g=!1,_=i?.maxStringLength??0,v=e=>{if(m+=e,_>0&&m.length>_)throw new H(`sed: output size limit exceeded (${_} bytes)`,`string_length`)},y=``,b,x=new Map,S=new Map,C=new Map,w=new Map,T=i?{maxIterations:i.maxSedIterations,maxStringLength:_}:void 0;for(let e=0;e1e4)break;if(r.restartCycle=!1,r.pendingFileReads=[],r.pendingFileWrites=[],zK(t,r,i,T),o&&s){for(let e of r.pendingFileReads){let t=o.resolvePath(s,e.filename);try{if(e.wholeFile){let e=await u(`read command file`,()=>o.readFile(t));r.appendBuffer.push(e.replace(/\n$/,``))}else{if(!S.has(t)){let e=await u(`read command file line cache`,()=>o.readFile(t));S.set(t,e.split(` +`)),C.set(t,0)}let e=S.get(t),n=C.get(t);e&&n!==void 0&&n0;for(let e of r.lineNumberOutput)v(`${e} +`);let m=[],_=[];for(let e of r.appendBuffer)e.startsWith(`__INSERT__`)?m.push(e.slice(10)):_.push(e);for(let e of m)v(`${e} +`);let E=!1;!r.deleted&&!r.quitSilent?n?r.printed&&(v(`${r.patternSpace} +`),E=!0):(v(`${r.patternSpace} +`),E=!0):r.changedText!==void 0&&(v(`${r.changedText} +`),E=!0);for(let e of _)v(`${e} +`);if(g=(d||E)&&_.length===0,r.quit||r.quitSilent){if(r.exitCode!==void 0&&(h=r.exitCode),r.errorMessage)return{output:``,exitCode:h||1,errorMessage:r.errorMessage};break}}if(o&&s)for(let[e,t]of w)try{await u(`flush pending file writes`,()=>o.writeFile(e,t))}catch(e){if(e instanceof eB)throw e}return!d&&g&&m.endsWith(` +`)&&(m=m.slice(0,-1)),{output:m,exitCode:h}}var YK,XK,ZK,dSe=B(()=>{kB(),vH(),U(),AK(),aB(),sV(),sSe(),uSe(),YK={name:`sed`,summary:`stream editor for filtering and transforming text`,usage:`sed [OPTION]... {script} [input-file]...`,options:[`-n, --quiet, --silent suppress automatic printing of pattern space`,`-e script add the script to commands to be executed`,`-f script-file read script from file`,`-i, --in-place edit files in place`,`-E, -r, --regexp-extended use extended regular expressions`,` --help display this help and exit`],description:`Commands: + s/regexp/replacement/[flags] substitute + d delete pattern space + p print pattern space + a\\ text append text after line + i\\ text insert text before line + c\\ text change (replace) line with text + h copy pattern space to hold space + H append pattern space to hold space + g copy hold space to pattern space + G append hold space to pattern space + x exchange pattern and hold spaces + n read next line into pattern space + N append next line to pattern space + y/source/dest/ transliterate characters + = print line number + l list pattern space (escape special chars) + b [label] branch to label + t [label] branch on substitution + T [label] branch if no substitution + :label define label + q quit + Q quit without printing + +Addresses: + N line number + $ last line + /regexp/ lines matching regexp + N,M range from line N to M + first~step every step-th line starting at first`},XK={name:`sed`,async execute(e,t){OK(t.requireDefenseContext,`sed`,`execution entry`);let n=(e,n)=>kK(t.requireDefenseContext,`sed`,e,n);if(aV(e))return iV(YK);let r=[],i=[],a=!1,o=!1,s=!1,c=[];for(let t=0;t1){for(let e of n.slice(1))if(e!==`n`&&e!==`e`&&e!==`f`&&e!==`i`&&e!==`E`&&e!==`r`)return oV(`sed`,`-${e}`);n.includes(`n`)&&(a=!0),n.includes(`i`)&&(o=!0),(n.includes(`E`)||n.includes(`r`))&&(s=!0),n.includes(`e`)&&!n.includes(`n`)&&!n.includes(`i`)&&t+1t.fs.readFile(i));for(let t of e.split(` +`)){let e=t.trim();e&&!e.startsWith(`#`)&&r.push(e)}}catch(t){if(t instanceof eB)throw t;return{stdout:``,stderr:`sed: couldn't open file ${e}: No such file or directory +`,exitCode:1}}}if(r.length===0)return{stdout:``,stderr:`sed: no script specified +`,exitCode:1};let{commands:l,error:u,silentMode:d}=lSe(r,s,t.limits);if(u)return{stdout:``,stderr:`sed: ${u} +`,exitCode:1};let f=!!(a||d);if(o){if(c.length===0)return{stdout:``,stderr:`sed: -i requires at least one file argument +`,exitCode:1};for(let e of c){if(e===`-`)continue;let r=t.fs.resolvePath(t.cwd,e);try{let i=await n(`in-place input read`,()=>t.fs.readFile(r)),a=await n(`in-place processing`,()=>JK(i,l,f,{limits:t.limits,filename:e,fs:t.fs,cwd:t.cwd,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext}));if(a.errorMessage)return{stdout:``,stderr:`${a.errorMessage} +`,exitCode:a.exitCode??1};await n(`in-place output write`,()=>t.fs.writeFile(r,a.output))}catch(t){if(t instanceof eB)throw t;return t instanceof H?{stdout:``,stderr:`sed: ${_H(t.message)} +`,exitCode:H.EXIT_CODE}:{stdout:``,stderr:`sed: ${e}: No such file or directory +`,exitCode:1}}}return{stdout:``,stderr:``,exitCode:0}}let p=``;if(c.length===0){p=vB(t.stdin);try{let e=await n(`stdin processing`,()=>JK(p,l,f,{limits:t.limits,fs:t.fs,cwd:t.cwd,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext}));return{stdout:e.output,stderr:e.errorMessage?`${e.errorMessage} +`:``,exitCode:e.exitCode??0}}catch(e){if(e instanceof eB)throw e;if(e instanceof H)return{stdout:``,stderr:`sed: ${_H(e.message)} +`,exitCode:H.EXIT_CODE};throw e}}let m=!1;for(let e of c){let r;if(e===`-`)m?r=``:(r=vB(t.stdin),m=!0);else{let i=t.fs.resolvePath(t.cwd,e);try{r=await n(`input file read`,()=>t.fs.readFile(i))}catch(t){if(t instanceof eB)throw t;return t instanceof H?{stdout:``,stderr:`sed: ${_H(t.message)} +`,exitCode:H.EXIT_CODE}:{stdout:``,stderr:`sed: ${e}: No such file or directory +`,exitCode:1}}}p.length>0&&r.length>0&&!p.endsWith(` +`)&&(p+=` +`),p+=r}try{let e=await n(`final processing`,()=>JK(p,l,f,{limits:t.limits,filename:c.length===1?c[0]:void 0,fs:t.fs,cwd:t.cwd,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext}));return{stdout:e.output,stderr:e.errorMessage?`${e.errorMessage} +`:``,exitCode:e.exitCode??0}}catch(e){if(e instanceof eB)throw e;if(e instanceof H)return{stdout:``,stderr:`sed: ${_H(e.message)} +`,exitCode:H.EXIT_CODE};throw e}}},ZK={name:`sed`,flags:[{flag:`-n`,type:`boolean`},{flag:`-i`,type:`boolean`},{flag:`-E`,type:`boolean`},{flag:`-r`,type:`boolean`},{flag:`-e`,type:`value`,valueHint:`string`}],stdinType:`text`,needsArgs:!0}});function QK(e){return Object.assign(Object.create(null),Object.fromEntries(e))}function $K(e,t){return Object.assign(Object.create(null),Object.fromEntries(e),t)}function eq(...e){return Object.assign(Object.create(null),...e)}var tq=B(()=>{});function fSe(e={}){let{fieldSep:t=iq,maxIterations:n=nq,maxRecursionDepth:r=rq,maxOutputSize:i=0,maxArrayElements:a=1e5,fs:o,cwd:s,exec:c,coverage:l,requireDefenseContext:u}=e;return{FS:` `,OFS:` `,ORS:` +`,OFMT:`%.6g`,NR:0,NF:0,FNR:0,FILENAME:``,RSTART:0,RLENGTH:-1,SUBSEP:``,fields:[],line:``,vars:Object.create(null),arrays:Object.create(null),arrayAliases:new Map,ARGC:0,ARGV:Object.create(null),ENVIRON:Object.create(null),functions:new Map,getlineCommandStreams:new Map,getlineFileStreams:new Map,fieldSep:t,maxIterations:n,maxRecursionDepth:r,maxOutputSize:i,maxArrayElements:a,arrayElementCount:0,recordsProcessed:0,currentRecursionDepth:0,exitCode:0,shouldExit:!1,shouldNext:!1,shouldNextFile:!1,loopBreak:!1,loopContinue:!1,hasReturn:!1,inEndBlock:!1,output:``,openedFiles:new Set,fs:o,cwd:s,exec:c,coverage:l,requireDefenseContext:u}}var nq,rq,iq,pSe=B(()=>{yG(),nq=1e4,rq=100,iq=new vG(/\s+/)});function mSe(e,t,n){switch(n){case`+`:return e+t;case`-`:return e-t;case`*`:return e*t;case`/`:return t===0?0:e/t;case`%`:return t===0?0:e%t;case`^`:case`**`:return e**t;default:return 0}}var hSe=B(()=>{});function aq(e){if(typeof e==`number`)return e;let t=parseFloat(e);return Number.isNaN(t)?0:t}function oq(e){return typeof e==`string`?e:String(e)}function sq(e){return new oH(e,`awk string`,()=>new H(`string size limit exceeded (${e} bytes)`,`string_length`))}function cq(e){return e.maxOutputSize>0?e.maxOutputSize:vq}function lq(e,t,n,r,i){let a=sq(i),o=0,s=0,c=0;for(let i of t.matchAll(e)){let t=i.index??0;s++,a.append(e.slice(o,t)),n(s)?(a.append(r(i)),c++):a.append(i[0]),o=t+i[0].length}return a.append(e.slice(o)),{value:a.build(),replacements:c}}async function uq(e,t){if(e.type===`regex`)return e.pattern;let n=oq(await t.evalExpr(e));return n.startsWith(`/`)&&n.endsWith(`/`)&&(n=n.slice(1,-1)),n}async function dq(e,t){return e?e.type===`variable`?e.name:e.type===`field`?`$${Math.floor(aq(await t.evalExpr(e.index)))}`:`$0`:`$0`}function fq(e,t){if(e===`$0`)return t.line;if(e.startsWith(`$`)){let n=parseInt(e.slice(1),10)-1;return t.fields[n]||``}return oq(t.vars[e]??``)}function pq(e,t,n){if(e===`$0`)n.line=t,n.fields=n.FS===` `?t.trim().split(/\s+/).filter(Boolean):n.fieldSep.split(t),n.NF=n.fields.length;else if(e.startsWith(`$`)){let r=parseInt(e.slice(1),10)-1;for(;n.fields.length<=r;)n.fields.push(``);n.fields[r]=t,n.NF=n.fields.length,n.line=n.fields.join(n.OFS)}else n.vars[e]=t}async function gSe(e,t,n){return e.length===0?t.line.length:oq(await n.evalExpr(e[0])).length}async function _Se(e,t,n){if(e.length<2)return``;let r=oq(await n.evalExpr(e[0])),i=Math.floor(aq(await n.evalExpr(e[1])))-1;if(e.length>=3){let t=Math.floor(aq(await n.evalExpr(e[2])));return r.substr(Math.max(0,i),t)}return r.substr(Math.max(0,i))}async function vSe(e,t,n){if(e.length<2)return 0;let r=oq(await n.evalExpr(e[0])),i=oq(await n.evalExpr(e[1])),a=r.indexOf(i);return a===-1?0:a+1}async function ySe(e,t,n){if(e.length<2)return 0;let r=oq(await n.evalExpr(e[0])),i=e[1];if(i.type!==`variable`)return 0;let a=i.name,o=t.FS;if(e.length>=3){let t=e[2];if(t.type===`regex`)o=mG(t.pattern);else{let e=oq(await n.evalExpr(t));o=e===` `?mG(`\\s+`):e}}else t.FS===` `&&(o=mG(`\\s+`));let s=Object.keys(t.arrays[a]??{}).length,c=t.maxArrayElements-t.arrayElementCount+s,l=typeof o==`string`?r.split(o,c+1):o.split(r,c+1);if(l.length>c)throw new H(`array element limit exceeded (${t.maxArrayElements})`,`array_elements`);t.arrays[a]=Object.create(null);for(let e=0;ee===1,e=>mq(i,e[0],cq(t)),cq(t));return pq(a,e.value,t),e.replacements}catch(e){return nV(e),0}}async function xSe(e,t,n){if(e.length<2)return 0;let r=await uq(e[0],n),i=oq(await n.evalExpr(e[1])),a=await dq(e[2],n),o=fq(a,t);try{let e=lq(o,mG(r,`g`),()=>!0,e=>mq(i,e[0],cq(t)),cq(t));return pq(a,e.value,t),e.replacements}catch(e){return nV(e),0}}function mq(e,t,n){let r=sq(n),i=0;for(;i=4?oq(await n.evalExpr(e[3])):t.line;try{let e=a.toLowerCase()===`g`,n=e?0:parseInt(a,10)||1;return e?lq(o,mG(r,`g`),()=>!0,e=>hq(i,e[0],e.slice(1),cq(t)),cq(t)).value:lq(o,mG(r,`g`),e=>e===n,e=>hq(i,e[0],e.slice(1),cq(t)),cq(t)).value}catch(e){return nV(e),o}}function hq(e,t,n,r){let i=sq(r),a=0;for(;a=`1`&&r<=`9`){let e=parseInt(r,10)-1;i.append(n[e]||``),a+=2}else r===`n`?(i.append(` +`),a+=2):r===`t`?(i.append(` `),a+=2):(i.append(r),a+=2)}else e[a]===`&`?(i.append(t),a++):(i.append(e[a]),a++);return i.build()}async function wSe(e,t,n){return e.length===0?``:oq(await n.evalExpr(e[0])).toLowerCase()}async function TSe(e,t,n){return e.length===0?``:oq(await n.evalExpr(e[0])).toUpperCase()}async function ESe(e,t,n){if(e.length===0)return``;let r=oq(await n.evalExpr(e[0])),i=[];for(let t=1;t0?aq(await n.evalExpr(e[0])):0,i=e.length>1?aq(await n.evalExpr(e[1])):0;return Math.atan2(r,i)}async function MSe(e,t,n){return e.length===0?0:Math.log(aq(await n.evalExpr(e[0])))}async function NSe(e,t,n){return e.length===0?1:Math.exp(aq(await n.evalExpr(e[0])))}function PSe(e,t,n){return t.random?t.random():Math.random()}async function FSe(e,t,n){let r=e.length>0?aq(await n.evalExpr(e[0])):Date.now();return t.vars._srand_seed=r,r}function ISe(e,t){return()=>{throw Error(`${e}() is not supported - ${t}`)}}function gq(e){return()=>{throw Error(`function '${e}()' is not implemented`)}}function _q(e,t,n=vq){let r=0,i=``,a=0,o=0,s=Math.min(yq,n),c=e=>{let t=V(e);if(t>n-a)throw new H(`formatted string size limit exceeded (${n} bytes)`,`string_length`);i+=e,a+=t};for(;od&&e[n]===`$`?(u=parseInt(e.substring(d,n),10)-1,n++):n=d;let f=()=>{if(ns)throw new H(`printf width limit exceeded (${s} bytes)`,`string_length`);if(e[n]===`.`){if(n++,e[n]===`*`){let e=t[r++],i=e===void 0?0:Math.floor(Number(e));if(!Number.isFinite(i)||!Number.isSafeInteger(i))throw new H(`printf precision limit exceeded (${s} bytes)`,`string_length`);l=i<0?``:String(i),n++}else for(;ns)throw new H(`printf precision limit exceeded (${s} bytes)`,`string_length`)}f();let p=e[n],m=t[u===void 0?r:u];switch(p){case`s`:{let e=m===void 0?``:String(m);if(l&&(e=e.substring(0,parseInt(l,10))),a){let t=parseInt(a,10);e=i.includes(`-`)?e.padEnd(t):e.padStart(t)}c(e),u===void 0&&r++;break}case`d`:case`i`:{let e=m===void 0?0:Math.floor(Number(m));Number.isNaN(e)&&(e=0);let t=e<0,n=Math.abs(e).toString();if(l){let e=parseInt(l,10);n=n.padStart(e,`0`)}let o=``;t?o=`-`:i.includes(`+`)?o=`+`:i.includes(` `)&&(o=` `);let s=o+n;if(a){let e=parseInt(a,10);s=i.includes(`-`)?s.padEnd(e):i.includes(`0`)&&!l?o+n.padStart(e-o.length,`0`):s.padStart(e)}c(s),u===void 0&&r++;break}case`f`:{let e=m===void 0?0:Number(m);Number.isNaN(e)&&(e=0);let t=l?parseInt(l,10):6;if(t>100)throw new H(`printf floating-point precision limit exceeded (100 digits)`,`string_length`);let n=e.toFixed(t);if(a){let e=parseInt(a,10);n=i.includes(`-`)?n.padEnd(e):n.padStart(e)}c(n),u===void 0&&r++;break}case`e`:case`E`:{let e=m===void 0?0:Number(m);Number.isNaN(e)&&(e=0);let t=l?parseInt(l,10):6;if(t>100)throw new H(`printf floating-point precision limit exceeded (100 digits)`,`string_length`);let n=e.toExponential(t);if(p===`E`&&(n=n.toUpperCase()),a){let e=parseInt(a,10);n=i.includes(`-`)?n.padEnd(e):n.padStart(e)}c(n),u===void 0&&r++;break}case`g`:case`G`:{let e=m===void 0?0:Number(m);Number.isNaN(e)&&(e=0);let t=l?parseInt(l,10):6;if(t>100)throw new H(`printf floating-point precision limit exceeded (100 digits)`,`string_length`);let n=e===0?0:Math.floor(Math.log10(Math.abs(e))),o;if(e===0?o=`0`:n<-4||n>=t?(o=e.toExponential(t-1),p===`G`&&(o=o.toUpperCase())):o=e.toPrecision(t),o.includes(`.`)&&(o=o.replace(/\.?0+$/,``).replace(/\.?0+e/,`e`)),o.includes(`e`)&&(o=o.replace(/\.?0+e/,`e`)),a){let e=parseInt(a,10);o=i.includes(`-`)?o.padEnd(e):o.padStart(e)}c(o),u===void 0&&r++;break}case`x`:case`X`:{let e=m===void 0?0:Math.floor(Number(m));Number.isNaN(e)&&(e=0);let t=Math.abs(e).toString(16);if(p===`X`&&(t=t.toUpperCase()),l){let e=parseInt(l,10);t=t.padStart(e,`0`)}let n=e<0?`-`:``,o=n+t;if(a){let e=parseInt(a,10);o=i.includes(`-`)?o.padEnd(e):i.includes(`0`)&&!l?n+t.padStart(e-n.length,`0`):o.padStart(e)}c(o),u===void 0&&r++;break}case`o`:{let e=m===void 0?0:Math.floor(Number(m));Number.isNaN(e)&&(e=0);let t=Math.abs(e).toString(8);if(l){let e=parseInt(l,10);t=t.padStart(e,`0`)}let n=e<0?`-`:``,o=n+t;if(a){let e=parseInt(a,10);o=i.includes(`-`)?o.padEnd(e):i.includes(`0`)&&!l?n+t.padStart(e-n.length,`0`):o.padStart(e)}c(o),u===void 0&&r++;break}case`c`:c(typeof m==`number`?String.fromCharCode(m):String(m??``).charAt(0)||``),u===void 0&&r++;break;case`%`:c(`%`);break;default:c(e.substring(o,n+1))}o=n+1}else if(e[o]===`\\`&&o+1{sH(),kB(),rV(),U(),yG(),vq=10485760,yq=1e4,bq=new Map([[`length`,gSe],[`substr`,_Se],[`index`,vSe],[`split`,ySe],[`sub`,bSe],[`gsub`,xSe],[`match`,SSe],[`gensub`,CSe],[`tolower`,wSe],[`toupper`,TSe],[`sprintf`,ESe],[`int`,DSe],[`sqrt`,OSe],[`sin`,kSe],[`cos`,ASe],[`atan2`,jSe],[`log`,MSe],[`exp`,NSe],[`rand`,PSe],[`srand`,FSe],[`system`,ISe(`system`,`shell execution not allowed in sandboxed environment`)],[`close`,()=>0],[`fflush`,()=>0],[`systime`,gq(`systime`)],[`mktime`,gq(`mktime`)],[`strftime`,gq(`strftime`)]])});function Sq(e){return typeof e==`number`?e!==0:e!==``&&e!==`0`}function Cq(e){if(typeof e==`number`)return e;let t=parseFloat(e);return Number.isNaN(t)?0:t}function wq(e){return typeof e==`string`?e:String(e)}function Tq(e){if(typeof e==`number`)return!0;let t=String(e).trim();return t!==``&&!Number.isNaN(Number(t))}function Eq(e,t){try{return mG(e).test(t)}catch{return!1}}var Dq=B(()=>{yG()});function Oq(e,t){return t===``?[]:e.FS===` `?t.trim().split(/\s+/).filter(Boolean):e.fieldSep.split(t)}function kq(e,t){return t===0?e.line:t<0||t>e.fields.length?``:e.fields[t-1]??``}function Aq(e,t,n){if(t===0)e.line=wq(n),e.fields=Oq(e,e.line),e.NF=e.fields.length;else if(t>0){for(;e.fields.length{yG(),Dq()});function Nq(e,t){switch(t){case`FS`:return e.FS;case`OFS`:return e.OFS;case`ORS`:return e.ORS;case`OFMT`:return e.OFMT;case`NR`:return e.NR;case`NF`:return e.NF;case`FNR`:return e.FNR;case`FILENAME`:return e.FILENAME;case`RSTART`:return e.RSTART;case`RLENGTH`:return e.RLENGTH;case`SUBSEP`:return e.SUBSEP;case`ARGC`:return e.ARGC}return e.vars[t]??``}function Pq(e,t,n){switch(t){case`FS`:LSe(e,wq(n));return;case`OFS`:e.OFS=wq(n);return;case`ORS`:e.ORS=wq(n);return;case`OFMT`:e.OFMT=wq(n);return;case`NR`:e.NR=Math.floor(Cq(n));return;case`NF`:{let t=Math.floor(Cq(n));if(te.NF){for(;e.fields.length=e.maxArrayElements)throw new H(`array element limit exceeded (${e.maxArrayElements})`,`array_elements`);e.arrayElementCount++}e.arrays[i][n]=r}function RSe(e,t,n){if(t===`ARGV`)return e.ARGV[n]!==void 0;if(t===`ENVIRON`)return e.ENVIRON[n]!==void 0;let r=Fq(e,t);return e.arrays[r]?.[n]!==void 0}function zSe(e,t,n){let r=Fq(e,t);e.arrays[r]&&(n in e.arrays[r]&&e.arrayElementCount--,delete e.arrays[r][n])}function BSe(e,t){let n=Fq(e,t);e.arrayElementCount-=Object.keys(e.arrays[n]??{}).length,delete e.arrays[n]}var Rq=B(()=>{U(),Mq(),Dq()});function VSe(e){Uq=e}function zq(e,t){OK(e.requireDefenseContext,`awk`,t)}function Bq(e,t,n){return kK(e.requireDefenseContext,`awk`,t,n)}async function Vq(e,t){switch(zq(e,`expression evaluation`),e.coverage?.hit(`awk:expr:${t.type}`),t.type){case`number`:return t.value;case`string`:return t.value;case`regex`:return+!!Eq(t.pattern,e.line);case`field`:return HSe(e,t);case`variable`:return Nq(e,t.name);case`array_access`:return USe(e,t);case`binary`:return WSe(e,t);case`unary`:return qSe(e,t);case`ternary`:return Sq(await Bq(e,`ternary condition evaluation`,()=>Vq(e,t.condition)))?await Bq(e,`ternary consequent evaluation`,()=>Vq(e,t.consequent)):await Bq(e,`ternary alternate evaluation`,()=>Vq(e,t.alternate));case`call`:return JSe(e,t.name,t.args);case`assignment`:return XSe(e,t);case`pre_increment`:return ZSe(e,t.operand);case`pre_decrement`:return QSe(e,t.operand);case`post_increment`:return $Se(e,t.operand);case`post_decrement`:return eCe(e,t.operand);case`in`:return tCe(e,t.key,t.array);case`getline`:return nCe(e,t.variable,t.file,t.command);case`tuple`:return aCe(e,t.elements);default:return``}}async function HSe(e,t){return zq(e,`field reference evaluation`),kq(e,Math.floor(Cq(await Bq(e,`field index evaluation`,()=>Vq(e,t.index)))))}async function USe(e,t){zq(e,`array access evaluation`);let n=wq(await Bq(e,`array key evaluation`,()=>Vq(e,t.key)));return Iq(e,t.array,n)}async function WSe(e,t){zq(e,`binary expression evaluation`);let n=t.operator;if(n===`||`)return Sq(await Bq(e,`logical-or left evaluation`,()=>Vq(e,t.left)))||Sq(await Bq(e,`logical-or right evaluation`,()=>Vq(e,t.right)))?1:0;if(n===`&&`)return Sq(await Bq(e,`logical-and left evaluation`,()=>Vq(e,t.left)))&&Sq(await Bq(e,`logical-and right evaluation`,()=>Vq(e,t.right)))?1:0;if(n===`~`){let n=await Bq(e,`regex left evaluation`,()=>Vq(e,t.left));t.right.type===`regex`&&e.coverage?.hit(`awk:expr:regex`);let r=t.right.type===`regex`?t.right.pattern:wq(await Bq(e,`regex right evaluation`,()=>Vq(e,t.right)));try{return+!!mG(r).test(wq(n))}catch{return 0}}if(n===`!~`){let n=await Bq(e,`negated-regex left evaluation`,()=>Vq(e,t.left));t.right.type===`regex`&&e.coverage?.hit(`awk:expr:regex`);let r=t.right.type===`regex`?t.right.pattern:wq(await Bq(e,`negated-regex right evaluation`,()=>Vq(e,t.right)));try{return+!mG(r).test(wq(n))}catch{return 1}}let r=await Bq(e,`binary left evaluation`,()=>Vq(e,t.left)),i=await Bq(e,`binary right evaluation`,()=>Vq(e,t.right));if(n===` `){let t=wq(r)+wq(i);if(e.maxOutputSize>0&&t.length>e.maxOutputSize)throw new H(`awk: string concatenation size limit exceeded (${e.maxOutputSize} bytes)`,`string_length`,e.output);return t}return GSe(n)?KSe(r,i,n):mSe(Cq(r),Cq(i),n)}function GSe(e){return[`<`,`<=`,`>`,`>=`,`==`,`!=`].includes(e)}function KSe(e,t,n){let r=Tq(e),i=Tq(t);if(r&&i){let r=Cq(e),i=Cq(t);switch(n){case`<`:return+(r`:return+(r>i);case`>=`:return+(r>=i);case`==`:return+(r===i);case`!=`:return r===i?0:1}}let a=wq(e),o=wq(t);switch(n){case`<`:return+(a`:return+(a>o);case`>=`:return+(a>=o);case`==`:return+(a===o);case`!=`:return a===o?0:1}return 0}async function qSe(e,t){zq(e,`unary expression evaluation`);let n=await Bq(e,`unary operand evaluation`,()=>Vq(e,t.operand));switch(t.operator){case`!`:return+!Sq(n);case`-`:return-Cq(n);case`+`:return+Cq(n);default:return n}}async function JSe(e,t,n){zq(e,`function call evaluation`);let r=bq.get(t);if(r)return r(n,e,{evalExpr:t=>Vq(e,t)});let i=e.functions.get(t);return i?YSe(e,i,n):``}async function YSe(e,t,n){if(zq(e,`user function call`),e.currentRecursionDepth++,e.currentRecursionDepth>e.maxRecursionDepth)throw e.currentRecursionDepth--,new H(`awk: recursion depth exceeded maximum (${e.maxRecursionDepth})`,`recursion`,e.output);let r=Object.create(null);for(let n of t.params)r[n]=e.vars[n];let i=[];for(let r=0;rVq(e,t));e.vars[a]=o}else e.vars[a]=``}e.hasReturn=!1,e.returnValue=void 0;let a=Uq;a&&await Bq(e,`user function body execution`,()=>a(e,t.body.statements));let o=e.returnValue??``;for(let n of t.params)r[n]===void 0?delete e.vars[n]:e.vars[n]=r[n];for(let t of i)e.arrayAliases.delete(t);return e.hasReturn=!1,e.returnValue=void 0,e.currentRecursionDepth--,o}async function XSe(e,t){zq(e,`assignment evaluation`);let n=await Bq(e,`assignment value evaluation`,()=>Vq(e,t.value)),r=t.target,i=t.operator,a;if(i===`=`)a=n;else{let t;if(r.type===`field`)t=kq(e,Math.floor(Cq(await Bq(e,`assignment field index`,()=>Vq(e,r.index)))));else if(r.type===`variable`)t=Nq(e,r.name);else{let n=wq(await Bq(e,`assignment array key`,()=>Vq(e,r.key)));t=Iq(e,r.array,n)}let o=Cq(t),s=Cq(n);switch(i){case`+=`:a=o+s;break;case`-=`:a=o-s;break;case`*=`:a=o*s;break;case`/=`:a=s===0?0:o/s;break;case`%=`:a=s===0?0:o%s;break;case`^=`:a=o**s;break;default:a=n}}if(r.type===`field`)Aq(e,Math.floor(Cq(await Bq(e,`assignment target field index`,()=>Vq(e,r.index)))),a);else if(r.type===`variable`)Pq(e,r.name,a);else{let t=wq(await Bq(e,`assignment target array key`,()=>Vq(e,r.key)));Lq(e,r.array,t,a)}return a}async function Hq(e,t,n,r){zq(e,`inc/dec evaluation`);let i;if(t.type===`field`){let r=Math.floor(Cq(await Bq(e,`inc/dec field index`,()=>Vq(e,t.index))));i=Cq(kq(e,r)),Aq(e,r,i+n)}else if(t.type===`variable`)i=Cq(Nq(e,t.name)),Pq(e,t.name,i+n);else{let r=wq(await Bq(e,`inc/dec array key`,()=>Vq(e,t.key)));i=Cq(Iq(e,t.array,r)),Lq(e,t.array,r,i+n)}return r?i+n:i}async function ZSe(e,t){return Hq(e,t,1,!0)}async function QSe(e,t){return Hq(e,t,-1,!0)}async function $Se(e,t){return Hq(e,t,1,!1)}async function eCe(e,t){return Hq(e,t,-1,!1)}async function tCe(e,t,n){zq(e,`in-expression evaluation`);let r;if(t.type===`tuple`){e.coverage?.hit(`awk:expr:tuple`);let n=[];for(let r of t.elements)n.push(wq(await Bq(e,`tuple key element evaluation`,()=>Vq(e,r))));r=n.join(e.SUBSEP)}else r=wq(await Bq(e,`in-expression key evaluation`,()=>Vq(e,t)));return+!!RSe(e,n,r)}async function nCe(e,t,n,r){if(zq(e,`getline evaluation`),r)return rCe(e,t,r);if(n)return iCe(e,t,n);if(!e.lines||e.lineIndex===void 0)return-1;let i=e.lineIndex+1;if(i>=e.lines.length)return 0;let a=e.lines[i];return t?Pq(e,t,a):jq(e,a),e.NR++,e.lineIndex=i,1}async function rCe(e,t,n){let r=e.exec;if(!r)return-1;zq(e,`getline command source`);let i=wq(await Bq(e,`getline command expression`,()=>Vq(e,n))),a=e.getlineCommandStreams.get(i);if(!a)try{let t=vB((await Bq(e,`getline command exec`,()=>r(i))).stdout).split(` +`);t.length>0&&t[t.length-1]===``&&t.pop(),a={lines:t,index:-1},e.getlineCommandStreams.set(i,a)}catch(e){if(e instanceof eB)throw e;return-1}let o=a.index+1;if(o>=a.lines.length)return 0;let s=a.lines[o];return a.index=o,t?Pq(e,t,s):jq(e,s),1}async function iCe(e,t,n){let r=e.fs;if(!r||!e.cwd)return-1;zq(e,`getline file source`);let i=wq(await Bq(e,`getline filename evaluation`,()=>Vq(e,n)));if(i===`/dev/null`)return 0;let a=r.resolvePath(e.cwd,i),o=e.getlineFileStreams.get(a);if(!o)try{let t=(await Bq(e,`getline file read`,()=>r.readFile(a))).split(` +`);t.length>0&&t[t.length-1]===``&&t.pop(),o={lines:t,index:-1},e.getlineFileStreams.set(a,o)}catch(e){if(e instanceof eB)throw e;return-1}let s=o.index+1;if(s>=o.lines.length)return 0;let c=o.lines[s];return o.index=s,t?Pq(e,t,c):jq(e,c),1}async function aCe(e,t){if(zq(e,`tuple evaluation`),t.length===0)return``;for(let n=0;nVq(e,t[n]));return Bq(e,`tuple final element`,()=>Vq(e,t[t.length-1]))}var Uq,Wq=B(()=>{kB(),U(),yG(),AK(),aB(),hSe(),xq(),Mq(),Dq(),Rq(),Uq=null});function Gq(e){if(e.maxOutputSize>0&&e.output.length>e.maxOutputSize)throw new H(`awk: output size limit exceeded (${e.maxOutputSize} bytes)`,`string_length`,e.output)}function Kq(e,t){OK(e.requireDefenseContext,`awk`,t)}function qq(e,t,n){return kK(e.requireDefenseContext,`awk`,t,n)}async function Jq(e,t){Kq(e,`block execution`);for(let n of t)if(await qq(e,`statement execution`,()=>Yq(e,n)),oCe(e))break}function oCe(e){return e.shouldExit||e.shouldNext||e.shouldNextFile||e.loopBreak||e.loopContinue||e.hasReturn}async function Yq(e,t){switch(Kq(e,`single statement execution`),e.coverage?.hit(`awk:stmt:${t.type}`),t.type){case`block`:await qq(e,`nested block statement`,()=>Jq(e,t.statements));break;case`expr_stmt`:await qq(e,`expression statement`,()=>Vq(e,t.expression));break;case`print`:await qq(e,`print statement`,()=>sCe(e,t.args,t.output));break;case`printf`:await qq(e,`printf statement`,()=>cCe(e,t.format,t.args,t.output));break;case`if`:await qq(e,`if statement`,()=>lCe(e,t));break;case`while`:await qq(e,`while statement`,()=>uCe(e,t));break;case`do_while`:await qq(e,`do-while statement`,()=>dCe(e,t));break;case`for`:await qq(e,`for statement`,()=>fCe(e,t));break;case`for_in`:await qq(e,`for-in statement`,()=>pCe(e,t));break;case`break`:e.loopBreak=!0;break;case`continue`:e.loopContinue=!0;break;case`next`:e.shouldNext=!0;break;case`nextfile`:e.shouldNextFile=!0;break;case`exit`:e.shouldExit=!0;{let n=t.code;e.exitCode=n?Math.floor(Cq(await qq(e,`exit code expression`,()=>Vq(e,n)))):0}break;case`return`:e.hasReturn=!0;{let n=t.value;e.returnValue=n?await qq(e,`return expression`,()=>Vq(e,n)):``}break;case`delete`:await qq(e,`delete statement`,()=>mCe(e,t.target))}}async function sCe(e,t,n){Kq(e,`print execution`);let r=[];for(let n of t){let t=await qq(e,`print argument evaluation`,()=>Vq(e,n));typeof t==`number`?Number.isInteger(t)&&Math.abs(t)<2**53-1?r.push(String(t)):r.push(_q(e.OFMT,[t],e.maxOutputSize||void 0)):r.push(wq(t))}let i=r.join(e.OFS)+e.ORS;n?await qq(e,`print redirection write`,()=>Xq(e,n.redirect,n.file,i)):(e.output+=i,Gq(e))}async function cCe(e,t,n,r){Kq(e,`printf execution`);let i=wq(await qq(e,`printf format evaluation`,()=>Vq(e,t))),a=[];for(let t of n)a.push(await qq(e,`printf argument evaluation`,()=>Vq(e,t)));let o=_q(i,a,e.maxOutputSize>0?Math.max(0,e.maxOutputSize-V(e.output)):void 0);r?await qq(e,`printf redirection write`,()=>Xq(e,r.redirect,r.file,o)):(e.output+=o,Gq(e))}async function Xq(e,t,n,r){Kq(e,`file write execution`);let i=e.fs;if(!i||!e.cwd){e.output+=r,Gq(e);return}let a=wq(await qq(e,`redirection filename evaluation`,()=>Vq(e,n))),o=i.resolvePath(e.cwd,a);t===`>`?e.openedFiles.has(o)?await qq(e,`redirection append write`,()=>i.appendFile(o,r)):(await qq(e,`redirection overwrite write`,()=>i.writeFile(o,r)),e.openedFiles.add(o)):(e.openedFiles.has(o)||e.openedFiles.add(o),await qq(e,`redirection append mode write`,()=>i.appendFile(o,r)))}async function lCe(e,t){if(Kq(e,`if execution`),Sq(await qq(e,`if condition evaluation`,()=>Vq(e,t.condition))))await qq(e,`if consequent execution`,()=>Yq(e,t.consequent));else if(t.alternate){let n=t.alternate;await qq(e,`if alternate execution`,()=>Yq(e,n))}}async function uCe(e,t){Kq(e,`while execution`);let n=0;for(;Sq(await qq(e,`while condition evaluation`,()=>Vq(e,t.condition)));){if(n++,n>e.maxIterations)throw new H(`awk: while loop exceeded maximum iterations (${e.maxIterations})`,`iterations`,e.output);if(e.loopContinue=!1,await qq(e,`while body execution`,()=>Yq(e,t.body)),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext||e.hasReturn)break}}async function dCe(e,t){Kq(e,`do-while execution`);let n=0;do{if(n++,n>e.maxIterations)throw new H(`awk: do-while loop exceeded maximum iterations (${e.maxIterations})`,`iterations`,e.output);if(e.loopContinue=!1,await qq(e,`do-while body execution`,()=>Yq(e,t.body)),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext||e.hasReturn)break}while(Sq(await qq(e,`do-while condition evaluation`,()=>Vq(e,t.condition))))}async function fCe(e,t){Kq(e,`for execution`);let n=t.init,r=t.condition,i=t.update;n&&await qq(e,`for init evaluation`,()=>Vq(e,n));let a=0;for(;!r||Sq(await qq(e,`for condition evaluation`,()=>Vq(e,r)));){if(a++,a>e.maxIterations)throw new H(`awk: for loop exceeded maximum iterations (${e.maxIterations})`,`iterations`,e.output);if(e.loopContinue=!1,await qq(e,`for body execution`,()=>Yq(e,t.body)),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext||e.hasReturn)break;i&&await qq(e,`for update evaluation`,()=>Vq(e,i))}}async function pCe(e,t){Kq(e,`for-in execution`);let n=e.arrays[t.array];if(n)for(let r of Object.keys(n)){if(e.vars[t.variable]=r,e.loopContinue=!1,await qq(e,`for-in body execution`,()=>Yq(e,t.body)),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext||e.hasReturn)break}}async function mCe(e,t){if(Kq(e,`delete execution`),t.type===`array_access`){let n=wq(await qq(e,`delete key evaluation`,()=>Vq(e,t.key)));zSe(e,t.array,n)}else t.type===`variable`&&BSe(e,t.name)}var hCe=B(()=>{U(),AK(),XB(),xq(),Wq(),Dq(),Rq(),VSe(Jq)}),Zq,gCe=B(()=>{U(),AK(),Wq(),Mq(),hCe(),Dq(),Zq=class{ctx;program=null;rangeStates=[];constructor(e){this.ctx=e}assertDefenseContext(e){OK(this.ctx.requireDefenseContext,`awk`,e)}withDefenseContext(e,t){return kK(this.ctx.requireDefenseContext,`awk`,e,t)}execute(e){this.assertDefenseContext(`program initialization`),this.program=e,this.ctx.output=``;for(let t of e.functions)this.ctx.functions.set(t.name,t);this.rangeStates=e.rules.map(()=>!1)}async executeBegin(){if(this.assertDefenseContext(`BEGIN execution entry`),this.program){for(let e of this.program.rules)if(e.pattern?.type===`begin`&&(await this.withDefenseContext(`BEGIN block execution`,()=>Jq(this.ctx,e.action.statements)),this.ctx.shouldExit))break}}async executeLine(e){if(this.assertDefenseContext(`line execution entry`),this.program&&!this.ctx.shouldExit){if(this.ctx.recordsProcessed++,this.ctx.recordsProcessed>this.ctx.maxIterations)throw new H(`record limit exceeded (${this.ctx.maxIterations})`,`iterations`);jq(this.ctx,e),this.ctx.NR++,this.ctx.FNR++,this.ctx.shouldNext=!1;for(let e=0;ethis.matchesRule(t,e))&&await this.withDefenseContext(`rule block execution`,()=>Jq(this.ctx,t.action.statements))}}}async executeEnd(){if(this.assertDefenseContext(`END execution entry`),this.program&&!this.ctx.inEndBlock){this.ctx.inEndBlock=!0,this.ctx.shouldExit=!1;for(let e of this.program.rules)if(e.pattern?.type===`end`&&(await this.withDefenseContext(`END block execution`,()=>Jq(this.ctx,e.action.statements)),this.ctx.shouldExit))break;this.ctx.inEndBlock=!1}}getOutput(){return this.ctx.output}getExitCode(){return this.ctx.exitCode}getContext(){return this.ctx}async matchesRule(e,t){this.assertDefenseContext(`rule matching`);let n=e.pattern;if(!n)return!0;switch(n.type){case`begin`:case`end`:return!1;case`regex_pattern`:return Eq(n.pattern,this.ctx.line);case`expr_pattern`:return Sq(await this.withDefenseContext(`expression pattern evaluation`,()=>Vq(this.ctx,n.expression)));case`range`:{let e=await this.withDefenseContext(`range start pattern`,()=>this.matchPattern(n.start)),r=await this.withDefenseContext(`range end pattern`,()=>this.matchPattern(n.end));return this.rangeStates[t]?(r&&(this.rangeStates[t]=!1),!0):e?(this.rangeStates[t]=!0,r&&(this.rangeStates[t]=!1),!0):!1}default:return!1}}async matchPattern(e){switch(this.assertDefenseContext(`pattern matching`),e.type){case`regex_pattern`:return Eq(e.pattern,this.ctx.line);case`expr_pattern`:return Sq(await this.withDefenseContext(`nested expression pattern`,()=>Vq(this.ctx,e.expression)));default:return!1}}}}),_Ce=B(()=>{pSe(),gCe()});function vCe(e){return e.replace(/\[\[:space:\]\]/g,`[ \\t\\n\\r\\f\\v]`).replace(/\[\[:blank:\]\]/g,`[ \\t]`).replace(/\[\[:alpha:\]\]/g,`[a-zA-Z]`).replace(/\[\[:digit:\]\]/g,`[0-9]`).replace(/\[\[:alnum:\]\]/g,`[a-zA-Z0-9]`).replace(/\[\[:upper:\]\]/g,`[A-Z]`).replace(/\[\[:lower:\]\]/g,`[a-z]`).replace(/\[\[:punct:\]\]/g,`[!"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_\`{|}~]`).replace(/\[\[:xdigit:\]\]/g,`[0-9A-Fa-f]`).replace(/\[\[:graph:\]\]/g,`[!-~]`).replace(/\[\[:print:\]\]/g,`[ -~]`).replace(/\[\[:cntrl:\]\]/g,`[\\x00-\\x1f\\x7f]`)}var J,Qq,$q,eJ,yCe=B(()=>{U(),(function(e){e.NUMBER=`NUMBER`,e.STRING=`STRING`,e.REGEX=`REGEX`,e.IDENT=`IDENT`,e.BEGIN=`BEGIN`,e.END=`END`,e.IF=`IF`,e.ELSE=`ELSE`,e.WHILE=`WHILE`,e.DO=`DO`,e.FOR=`FOR`,e.IN=`IN`,e.BREAK=`BREAK`,e.CONTINUE=`CONTINUE`,e.NEXT=`NEXT`,e.NEXTFILE=`NEXTFILE`,e.EXIT=`EXIT`,e.RETURN=`RETURN`,e.DELETE=`DELETE`,e.FUNCTION=`FUNCTION`,e.PRINT=`PRINT`,e.PRINTF=`PRINTF`,e.GETLINE=`GETLINE`,e.PLUS=`PLUS`,e.MINUS=`MINUS`,e.STAR=`STAR`,e.SLASH=`SLASH`,e.PERCENT=`PERCENT`,e.CARET=`CARET`,e.EQ=`EQ`,e.NE=`NE`,e.LT=`LT`,e.GT=`GT`,e.LE=`LE`,e.GE=`GE`,e.MATCH=`MATCH`,e.NOT_MATCH=`NOT_MATCH`,e.AND=`AND`,e.OR=`OR`,e.NOT=`NOT`,e.ASSIGN=`ASSIGN`,e.PLUS_ASSIGN=`PLUS_ASSIGN`,e.MINUS_ASSIGN=`MINUS_ASSIGN`,e.STAR_ASSIGN=`STAR_ASSIGN`,e.SLASH_ASSIGN=`SLASH_ASSIGN`,e.PERCENT_ASSIGN=`PERCENT_ASSIGN`,e.CARET_ASSIGN=`CARET_ASSIGN`,e.INCREMENT=`INCREMENT`,e.DECREMENT=`DECREMENT`,e.QUESTION=`QUESTION`,e.COLON=`COLON`,e.COMMA=`COMMA`,e.SEMICOLON=`SEMICOLON`,e.NEWLINE=`NEWLINE`,e.LPAREN=`LPAREN`,e.RPAREN=`RPAREN`,e.LBRACE=`LBRACE`,e.RBRACE=`RBRACE`,e.LBRACKET=`LBRACKET`,e.RBRACKET=`RBRACKET`,e.DOLLAR=`DOLLAR`,e.APPEND=`APPEND`,e.PIPE=`PIPE`,e.EOF=`EOF`})(J||={}),Qq=new Map([[`BEGIN`,J.BEGIN],[`END`,J.END],[`if`,J.IF],[`else`,J.ELSE],[`while`,J.WHILE],[`do`,J.DO],[`for`,J.FOR],[`in`,J.IN],[`break`,J.BREAK],[`continue`,J.CONTINUE],[`next`,J.NEXT],[`nextfile`,J.NEXTFILE],[`exit`,J.EXIT],[`return`,J.RETURN],[`delete`,J.DELETE],[`function`,J.FUNCTION],[`print`,J.PRINT],[`printf`,J.PRINTF],[`getline`,J.GETLINE]]),$q=new Set([J.COMMA,J.LBRACE,J.AND,J.OR,J.QUESTION,J.COLON,J.DO,J.ELSE,J.IF,J.WHILE]),eJ=class{maxTokens;input;pos=0;line=1;column=1;lastTokenType=null;constructor(e,t=1e5){this.maxTokens=t,this.input=e}tokenize(){let e=[];for(;this.pos=this.maxTokens)throw new H(`awk: token limit exceeded (${this.maxTokens})`,`array_elements`);e.push(t),this.lastTokenType=t.type}}if(e.length>=this.maxTokens)throw new H(`awk: token limit exceeded (${this.maxTokens})`,`array_elements`);return e.push(this.makeToken(J.EOF,``)),e}makeToken(e,t){return{type:e,value:t,line:this.line,column:this.column}}peek(e=0){return this.input[this.pos+e]||``}advance(){let e=this.input[this.pos++]||``;return e===` +`?(this.line++,this.column=1):this.column++,e}skipWhitespace(){for(;this.pos=this.input.length)return null;let e=this.line,t=this.column,n=this.peek();return n===` +`?(this.advance(),{type:J.NEWLINE,value:` +`,line:e,column:t}):n===`"`?this.readString():n===`/`&&this.canBeRegex()?this.readRegex():this.isDigit(n)||n===`.`&&this.isDigit(this.peek(1))?this.readNumber():this.isAlpha(n)||n===`_`?this.readIdentifier():this.readOperator()}canBeRegex(){return new Set([null,J.NEWLINE,J.SEMICOLON,J.LBRACE,J.RBRACE,J.LPAREN,J.LBRACKET,J.COMMA,J.ASSIGN,J.PLUS_ASSIGN,J.MINUS_ASSIGN,J.STAR_ASSIGN,J.SLASH_ASSIGN,J.PERCENT_ASSIGN,J.CARET_ASSIGN,J.AND,J.OR,J.NOT,J.MATCH,J.NOT_MATCH,J.QUESTION,J.COLON,J.LT,J.GT,J.LE,J.GE,J.EQ,J.NE,J.PLUS,J.MINUS,J.STAR,J.PERCENT,J.CARET,J.PRINT,J.PRINTF,J.IF,J.WHILE,J.DO,J.FOR,J.RETURN]).has(this.lastTokenType)}readString(){let e=this.line,t=this.column;this.advance();let n=``;for(;this.pos0?n+=String.fromCharCode(parseInt(e,16)):n+=`x`;break}default:if(/[0-7]/.test(e)){let t=e;for(;t.length<3&&/[0-7]/.test(this.peek());)t+=this.advance();n+=String.fromCharCode(parseInt(t,8))}else n+=e}}else n+=this.advance();return this.peek()===`"`&&this.advance(),{type:J.STRING,value:n,line:e,column:t}}readRegex(){let e=this.line,t=this.column;this.advance();let n=``;for(;this.pos`:return r===`=`?(this.advance(),{type:J.GE,value:`>=`,line:e,column:t}):r===`>`?(this.advance(),{type:J.APPEND,value:`>>`,line:e,column:t}):{type:J.GT,value:`>`,line:e,column:t};case`&`:return r===`&`?(this.advance(),{type:J.AND,value:`&&`,line:e,column:t}):{type:J.IDENT,value:`&`,line:e,column:t};case`|`:return r===`|`?(this.advance(),{type:J.OR,value:`||`,line:e,column:t}):{type:J.PIPE,value:`|`,line:e,column:t};case`~`:return{type:J.MATCH,value:`~`,line:e,column:t};case`?`:return{type:J.QUESTION,value:`?`,line:e,column:t};case`:`:return{type:J.COLON,value:`:`,line:e,column:t};case`,`:return{type:J.COMMA,value:`,`,line:e,column:t};case`;`:return{type:J.SEMICOLON,value:`;`,line:e,column:t};case`(`:return{type:J.LPAREN,value:`(`,line:e,column:t};case`)`:return{type:J.RPAREN,value:`)`,line:e,column:t};case`{`:return{type:J.LBRACE,value:`{`,line:e,column:t};case`}`:return{type:J.RBRACE,value:`}`,line:e,column:t};case`[`:return{type:J.LBRACKET,value:`[`,line:e,column:t};case`]`:return{type:J.RBRACKET,value:`]`,line:e,column:t};case`$`:return{type:J.DOLLAR,value:`$`,line:e,column:t};default:return{type:J.IDENT,value:n,line:e,column:t}}}isDigit(e){return e>=`0`&&e<=`9`}isAlpha(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}isAlphaNumeric(e){return this.isDigit(e)||this.isAlpha(e)}}});function bCe(e){e.expect(sJ.PRINT);let t=[];if(e.check(sJ.NEWLINE)||e.check(sJ.SEMICOLON)||e.check(sJ.RBRACE)||e.check(sJ.PIPE)||e.check(sJ.GT)||e.check(sJ.APPEND))t.push({type:`field`,index:{type:`number`,value:0}});else for(e.assertArrayLength(t.length),t.push(tJ(e));e.check(sJ.COMMA);)e.advance(),e.assertArrayLength(t.length),t.push(tJ(e));let n;return e.check(sJ.GT)?(e.advance(),n={redirect:`>`,file:e.parsePrimary()}):e.check(sJ.APPEND)&&(e.advance(),n={redirect:`>>`,file:e.parsePrimary()}),{type:`print`,args:t,output:n}}function tJ(e){return xCe(e)?nJ(e,!0):nJ(e,!1)}function nJ(e,t){let n=t?e.parseTernary():SCe(e);if(e.match(sJ.ASSIGN,sJ.PLUS_ASSIGN,sJ.MINUS_ASSIGN,sJ.STAR_ASSIGN,sJ.SLASH_ASSIGN,sJ.PERCENT_ASSIGN,sJ.CARET_ASSIGN)){let r=e.advance(),i=e.withDepth(()=>nJ(e,t));if(n.type!==`variable`&&n.type!==`field`&&n.type!==`array_access`)throw Error(`Invalid assignment target`);return{type:`assignment`,operator:new Map([[`=`,`=`],[`+=`,`+=`],[`-=`,`-=`],[`*=`,`*=`],[`/=`,`/=`],[`%=`,`%=`],[`^=`,`^=`]]).get(r.value)??`=`,target:n,value:i}}return n}function xCe(e){let t=0,n=e.pos;for(;n=`,`>=`],[`==`,`==`],[`!=`,`!=`]]).get(n.value)??`==`,left:t,right:r}}return t}function wCe(e){return e.match(sJ.NUMBER,sJ.STRING,sJ.IDENT,sJ.DOLLAR,sJ.LPAREN,sJ.NOT,sJ.MINUS,sJ.PLUS,sJ.INCREMENT,sJ.DECREMENT)}function TCe(e){return e.match(sJ.AND,sJ.OR,sJ.QUESTION,sJ.ASSIGN,sJ.PLUS_ASSIGN,sJ.MINUS_ASSIGN,sJ.STAR_ASSIGN,sJ.SLASH_ASSIGN,sJ.PERCENT_ASSIGN,sJ.CARET_ASSIGN,sJ.COMMA,sJ.SEMICOLON,sJ.NEWLINE,sJ.RBRACE,sJ.RPAREN,sJ.RBRACKET,sJ.COLON,sJ.PIPE,sJ.APPEND,sJ.GT,sJ.IN)}function ECe(e){e.expect(sJ.PRINTF);let t=e.check(sJ.LPAREN);t&&(e.advance(),e.skipNewlines());let n=t?e.parseExpression():tJ(e),r=[];for(;e.check(sJ.COMMA);)e.advance(),t&&e.skipNewlines(),e.assertArrayLength(r.length),r.push(t?e.parseExpression():tJ(e));t&&(e.skipNewlines(),e.expect(sJ.RPAREN));let i;return e.check(sJ.GT)?(e.advance(),i={redirect:`>`,file:e.parsePrimary()}):e.check(sJ.APPEND)&&(e.advance(),i={redirect:`>>`,file:e.parsePrimary()}),{type:`printf`,format:n,args:r,output:i}}var sJ,DCe=B(()=>{sJ={LPAREN:`LPAREN`,RPAREN:`RPAREN`,QUESTION:`QUESTION`,NEWLINE:`NEWLINE`,SEMICOLON:`SEMICOLON`,RBRACE:`RBRACE`,COMMA:`COMMA`,PIPE:`PIPE`,GT:`GT`,APPEND:`APPEND`,AND:`AND`,OR:`OR`,ASSIGN:`ASSIGN`,PLUS_ASSIGN:`PLUS_ASSIGN`,MINUS_ASSIGN:`MINUS_ASSIGN`,STAR_ASSIGN:`STAR_ASSIGN`,SLASH_ASSIGN:`SLASH_ASSIGN`,PERCENT_ASSIGN:`PERCENT_ASSIGN`,CARET_ASSIGN:`CARET_ASSIGN`,RBRACKET:`RBRACKET`,COLON:`COLON`,IN:`IN`,PRINT:`PRINT`,PRINTF:`PRINTF`,IDENT:`IDENT`,LT:`LT`,LE:`LE`,GE:`GE`,EQ:`EQ`,NE:`NE`,MATCH:`MATCH`,NOT_MATCH:`NOT_MATCH`,NUMBER:`NUMBER`,STRING:`STRING`,DOLLAR:`DOLLAR`,NOT:`NOT`,MINUS:`MINUS`,PLUS:`PLUS`,INCREMENT:`INCREMENT`,DECREMENT:`DECREMENT`}}),cJ,OCe=B(()=>{U(),yCe(),DCe(),cJ=class{tokens=[];pos=0;depth=0;operations=0;limits;constructor(e={}){this.limits={maxSourceLength:e.maxSourceLength??10485760,maxTokens:e.maxTokens??1e5,maxDepth:e.maxDepth??100,maxOperations:e.maxOperations??1e5}}parse(e){if(e.length>this.limits.maxSourceLength)throw new H(`awk: source length limit exceeded (${this.limits.maxSourceLength})`,`string_length`);let t=new eJ(e,this.limits.maxTokens);this.tokens=t.tokenize(),this.pos=0,this.depth=0,this.operations=0;let n=0;for(let e of this.tokens)if(this.useOperation(),e.type===J.LPAREN||e.type===J.LBRACKET||e.type===J.LBRACE){if(n++,n>this.limits.maxDepth)throw new H(`awk: parser depth limit exceeded (${this.limits.maxDepth})`,`recursion`)}else(e.type===J.RPAREN||e.type===J.RBRACKET||e.type===J.RBRACE)&&(n=Math.max(0,n-1));return this.parseProgram()}setPos(e){this.pos=e}current(){return this.tokens[this.pos]||{type:J.EOF,value:``,line:0,column:0}}advance(){this.useOperation();let e=this.current();return this.posthis.limits.maxOperations-this.operations)throw new H(`awk: parser operation limit exceeded (${this.limits.maxOperations})`,`iterations`);this.operations+=e}withDepth(e){if(this.depth>=this.limits.maxDepth)throw new H(`awk: parser depth limit exceeded (${this.limits.maxDepth})`,`recursion`);this.depth++;try{return e()}finally{this.depth--}}assertArrayLength(e){if(e>=this.limits.maxTokens)throw new H(`awk: AST array limit exceeded (${this.limits.maxTokens})`,`array_elements`)}match(...e){return e.includes(this.current().type)}check(e){return this.current().type===e}expect(e,t){if(!this.check(e)){let n=this.current();throw Error(t||`Expected ${e}, got ${n.type} at line ${n.line}:${n.column}`)}return this.advance()}skipNewlines(){for(;this.check(J.NEWLINE);)this.advance()}skipTerminators(){for(;this.check(J.NEWLINE)||this.check(J.SEMICOLON);)this.advance()}parseProgram(){let e=[],t=[];for(this.skipNewlines();!this.check(J.EOF)&&(this.skipNewlines(),!this.check(J.EOF));)this.check(J.FUNCTION)?e.push(this.parseFunction()):t.push(this.parseRule()),this.skipTerminators();return{functions:e,rules:t}}parseFunction(){this.expect(J.FUNCTION);let e=this.expect(J.IDENT).value;this.expect(J.LPAREN);let t=[];if(!this.check(J.RPAREN))for(t.push(this.expect(J.IDENT).value);this.check(J.COMMA);)this.advance(),t.push(this.expect(J.IDENT).value);return this.expect(J.RPAREN),this.skipNewlines(),{name:e,params:t,body:this.parseBlock()}}parseRule(){let e;if(this.check(J.BEGIN))this.advance(),e={type:`begin`};else if(this.check(J.END))this.advance(),e={type:`end`};else if(this.check(J.LBRACE))e=void 0;else if(this.check(J.REGEX)){let t=this.advance();if(this.check(J.AND)||this.check(J.OR)){let n={type:`binary`,operator:`~`,left:{type:`field`,index:{type:`number`,value:0}},right:{type:`regex`,pattern:t.value}};e={type:`expr_pattern`,expression:this.parseLogicalOrRest(n)}}else{let n={type:`regex_pattern`,pattern:t.value};if(this.check(J.COMMA)){this.advance();let t;t=this.check(J.REGEX)?{type:`regex_pattern`,pattern:this.advance().value}:{type:`expr_pattern`,expression:this.parseExpression()},e={type:`range`,start:n,end:t}}else e=n}}else{let t={type:`expr_pattern`,expression:this.parseExpression()};if(this.check(J.COMMA)){this.advance();let n;n=this.check(J.REGEX)?{type:`regex_pattern`,pattern:this.advance().value}:{type:`expr_pattern`,expression:this.parseExpression()},e={type:`range`,start:t,end:n}}else e=t}this.skipNewlines();let t;return t=this.check(J.LBRACE)?this.parseBlock():{type:`block`,statements:[{type:`print`,args:[{type:`field`,index:{type:`number`,value:0}}]}]},{pattern:e,action:t}}parseBlock(){this.expect(J.LBRACE),this.skipNewlines();let e=[];for(;!this.check(J.RBRACE)&&!this.check(J.EOF);)e.push(this.parseStatement()),this.skipTerminators();return this.expect(J.RBRACE),{type:`block`,statements:e}}parseStatement(){return this.withDepth(()=>this.parseStatementAtDepth())}parseStatementAtDepth(){if(this.check(J.SEMICOLON)||this.check(J.NEWLINE))return this.advance(),{type:`block`,statements:[]};if(this.check(J.LBRACE))return this.parseBlock();if(this.check(J.IF))return this.parseIf();if(this.check(J.WHILE))return this.parseWhile();if(this.check(J.DO))return this.parseDoWhile();if(this.check(J.FOR))return this.parseFor();if(this.check(J.BREAK))return this.advance(),{type:`break`};if(this.check(J.CONTINUE))return this.advance(),{type:`continue`};if(this.check(J.NEXT))return this.advance(),{type:`next`};if(this.check(J.NEXTFILE))return this.advance(),{type:`nextfile`};if(this.check(J.EXIT)){this.advance();let e;return!this.check(J.NEWLINE)&&!this.check(J.SEMICOLON)&&!this.check(J.RBRACE)&&!this.check(J.EOF)&&(e=this.parseExpression()),{type:`exit`,code:e}}if(this.check(J.RETURN)){this.advance();let e;return!this.check(J.NEWLINE)&&!this.check(J.SEMICOLON)&&!this.check(J.RBRACE)&&!this.check(J.EOF)&&(e=this.parseExpression()),{type:`return`,value:e}}if(this.check(J.DELETE)){this.advance();let e=this.parsePrimary();if(e.type!==`array_access`&&e.type!==`variable`)throw Error(`delete requires array element or array`);return{type:`delete`,target:e}}return this.check(J.PRINT)?bCe(this):this.check(J.PRINTF)?ECe(this):{type:`expr_stmt`,expression:this.parseExpression()}}parseIf(){this.expect(J.IF),this.expect(J.LPAREN);let e=this.parseExpression();this.expect(J.RPAREN),this.skipNewlines();let t=this.parseStatement();this.skipTerminators();let n;return this.check(J.ELSE)&&(this.advance(),this.skipNewlines(),n=this.parseStatement()),{type:`if`,condition:e,consequent:t,alternate:n}}parseWhile(){this.expect(J.WHILE),this.expect(J.LPAREN);let e=this.parseExpression();return this.expect(J.RPAREN),this.skipNewlines(),{type:`while`,condition:e,body:this.parseStatement()}}parseDoWhile(){this.expect(J.DO),this.skipNewlines();let e=this.parseStatement();this.skipNewlines(),this.expect(J.WHILE),this.expect(J.LPAREN);let t=this.parseExpression();return this.expect(J.RPAREN),{type:`do_while`,body:e,condition:t}}parseFor(){if(this.expect(J.FOR),this.expect(J.LPAREN),this.check(J.IDENT)){let e=this.advance();if(this.check(J.IN)){this.advance();let t=this.expect(J.IDENT).value;this.expect(J.RPAREN),this.skipNewlines();let n=this.parseStatement();return{type:`for_in`,variable:e.value,array:t,body:n}}this.pos--}let e;this.check(J.SEMICOLON)||(e=this.parseExpression()),this.expect(J.SEMICOLON);let t;this.check(J.SEMICOLON)||(t=this.parseExpression()),this.expect(J.SEMICOLON);let n;this.check(J.RPAREN)||(n=this.parseExpression()),this.expect(J.RPAREN),this.skipNewlines();let r=this.parseStatement();return{type:`for`,init:e,condition:t,update:n,body:r}}parseExpression(){return this.withDepth(()=>this.parseAssignment())}parseAssignment(){let e=this.parseTernary();if(this.match(J.ASSIGN,J.PLUS_ASSIGN,J.MINUS_ASSIGN,J.STAR_ASSIGN,J.SLASH_ASSIGN,J.PERCENT_ASSIGN,J.CARET_ASSIGN)){let t=this.advance(),n=this.parseExpression();if(e.type!==`variable`&&e.type!==`field`&&e.type!==`array_access`)throw Error(`Invalid assignment target`);let r=new Set([`=`,`+=`,`-=`,`*=`,`/=`,`%=`,`^=`]),i=t.value;if(!r.has(i))throw Error(`Unknown assignment operator: ${i}`);return{type:`assignment`,operator:i,target:e,value:n}}return e}parseTernary(){let e=this.parsePipeGetline();if(this.check(J.QUESTION)){this.advance();let t=this.parseExpression();this.expect(J.COLON);let n=this.parseExpression();e={type:`ternary`,condition:e,consequent:t,alternate:n}}return e}parsePipeGetline(){let e=this.parseOr();if(this.check(J.PIPE)){if(this.advance(),!this.check(J.GETLINE))throw Error(`Expected 'getline' after '|' in expression context`);this.advance();let t;return this.check(J.IDENT)&&(t=this.advance().value),{type:`getline`,command:e,variable:t}}return e}parseOr(){let e=this.parseAnd();for(;this.check(J.OR);){this.advance();let t=this.parseAnd();e={type:`binary`,operator:`||`,left:e,right:t}}return e}parseLogicalOrRest(e){for(e=this.parseLogicalAndRest(e);this.check(J.OR);){this.advance();let t=this.parseAnd();e={type:`binary`,operator:`||`,left:e,right:t}}return e}parseLogicalAndRest(e){for(;this.check(J.AND);){this.advance();let t=this.parseIn();e={type:`binary`,operator:`&&`,left:e,right:t}}return e}parseAnd(){let e=this.parseIn();for(;this.check(J.AND);){this.advance();let t=this.parseIn();e={type:`binary`,operator:`&&`,left:e,right:t}}return e}parseIn(){let e=this.parseConcatenation();return this.check(J.IN)?(this.advance(),{type:`in`,key:e,array:this.expect(J.IDENT).value}):e}parseConcatenation(){let e=this.parseMatch();for(;this.canStartExpression()&&!this.isConcatTerminator();){let t=this.parseMatch();e={type:`binary`,operator:` `,left:e,right:t}}return e}parseMatch(){let e=this.parseComparison();for(;this.match(J.MATCH,J.NOT_MATCH);){let t=this.advance().type===J.MATCH?`~`:`!~`,n=this.parseComparison();e={type:`binary`,operator:t,left:e,right:n}}return e}parseComparison(){let e=this.parseAddSub();for(;this.match(J.LT,J.LE,J.GT,J.GE,J.EQ,J.NE);){let t=this.advance(),n=this.parseAddSub();e={type:`binary`,operator:new Map([[`<`,`<`],[`<=`,`<=`],[`>`,`>`],[`>=`,`>=`],[`==`,`==`],[`!=`,`!=`]]).get(t.value)??`==`,left:e,right:n}}return e}canStartExpression(){return this.match(J.NUMBER,J.STRING,J.IDENT,J.DOLLAR,J.LPAREN,J.NOT,J.MINUS,J.PLUS,J.INCREMENT,J.DECREMENT)}isConcatTerminator(){return this.match(J.AND,J.OR,J.QUESTION,J.ASSIGN,J.PLUS_ASSIGN,J.MINUS_ASSIGN,J.STAR_ASSIGN,J.SLASH_ASSIGN,J.PERCENT_ASSIGN,J.CARET_ASSIGN,J.COMMA,J.SEMICOLON,J.NEWLINE,J.RBRACE,J.RPAREN,J.RBRACKET,J.COLON,J.PIPE,J.APPEND,J.IN)}parseAddSub(){let e=this.parseMulDiv();for(;this.match(J.PLUS,J.MINUS);){let t=this.advance().value,n=this.parseMulDiv();e={type:`binary`,operator:t,left:e,right:n}}return e}parseMulDiv(){let e=this.parseUnary();for(;this.match(J.STAR,J.SLASH,J.PERCENT);){let t=this.advance(),n=this.parseUnary();e={type:`binary`,operator:new Map([[`*`,`*`],[`/`,`/`],[`%`,`%`]]).get(t.value)??`*`,left:e,right:n}}return e}parseUnary(){if(this.check(J.INCREMENT)){this.advance();let e=this.withDepth(()=>this.parseUnary());return e.type!==`variable`&&e.type!==`field`&&e.type!==`array_access`?{type:`unary`,operator:`+`,operand:{type:`unary`,operator:`+`,operand:e}}:{type:`pre_increment`,operand:e}}if(this.check(J.DECREMENT)){this.advance();let e=this.withDepth(()=>this.parseUnary());return e.type!==`variable`&&e.type!==`field`&&e.type!==`array_access`?{type:`unary`,operator:`-`,operand:{type:`unary`,operator:`-`,operand:e}}:{type:`pre_decrement`,operand:e}}return this.match(J.NOT,J.MINUS,J.PLUS)?{type:`unary`,operator:this.advance().value,operand:this.withDepth(()=>this.parseUnary())}:this.parsePower()}parsePower(){let e=this.parsePostfix();if(this.check(J.CARET)){this.advance();let t=this.withDepth(()=>this.parsePower());e={type:`binary`,operator:`^`,left:e,right:t}}return e}parsePostfix(){let e=this.parsePrimary();if(this.check(J.INCREMENT)){if(this.advance(),e.type!==`variable`&&e.type!==`field`&&e.type!==`array_access`)throw Error(`Invalid increment operand`);return{type:`post_increment`,operand:e}}if(this.check(J.DECREMENT)){if(this.advance(),e.type!==`variable`&&e.type!==`field`&&e.type!==`array_access`)throw Error(`Invalid decrement operand`);return{type:`post_decrement`,operand:e}}return e}parseFieldIndex(){if(this.check(J.INCREMENT)){this.advance();let e=this.withDepth(()=>this.parseFieldIndex());return e.type!==`variable`&&e.type!==`field`&&e.type!==`array_access`?{type:`unary`,operator:`+`,operand:{type:`unary`,operator:`+`,operand:e}}:{type:`pre_increment`,operand:e}}if(this.check(J.DECREMENT)){this.advance();let e=this.withDepth(()=>this.parseFieldIndex());return e.type!==`variable`&&e.type!==`field`&&e.type!==`array_access`?{type:`unary`,operator:`-`,operand:{type:`unary`,operator:`-`,operand:e}}:{type:`pre_decrement`,operand:e}}return this.match(J.NOT,J.MINUS,J.PLUS)?{type:`unary`,operator:this.advance().value,operand:this.withDepth(()=>this.parseFieldIndex())}:this.parseFieldIndexPower()}parseFieldIndexPower(){let e=this.parseFieldIndexPrimary();if(this.check(J.CARET)){this.advance();let t=this.withDepth(()=>this.parseFieldIndexPower());e={type:`binary`,operator:`^`,left:e,right:t}}return e}parseFieldIndexPrimary(){if(this.check(J.NUMBER))return{type:`number`,value:this.advance().value};if(this.check(J.STRING))return{type:`string`,value:this.advance().value};if(this.check(J.DOLLAR))return this.advance(),{type:`field`,index:this.parseFieldIndex()};if(this.check(J.LPAREN)){this.advance();let e=this.parseExpression();return this.expect(J.RPAREN),e}if(this.check(J.IDENT)){let e=this.advance().value;if(this.check(J.LPAREN)){this.advance();let t=[];if(!this.check(J.RPAREN))for(t.push(this.parseExpression());this.check(J.COMMA);)this.advance(),t.push(this.parseExpression());return this.expect(J.RPAREN),{type:`call`,name:e,args:t}}if(this.check(J.LBRACKET)){this.advance();let t=this.parseExpression();if(this.check(J.COMMA)){let n=[t];for(;this.check(J.COMMA);)this.advance(),n.push(this.parseExpression());return this.expect(J.RBRACKET),{type:`array_access`,array:e,key:n.reduce((e,t)=>({type:`binary`,operator:` `,left:{type:`binary`,operator:` `,left:e,right:{type:`variable`,name:`SUBSEP`}},right:t}))}}return this.expect(J.RBRACKET),{type:`array_access`,array:e,key:t}}return{type:`variable`,name:e}}throw Error(`Unexpected token in field index: ${this.current().type} at line ${this.current().line}:${this.current().column}`)}parsePrimary(){if(this.check(J.NUMBER))return{type:`number`,value:this.advance().value};if(this.check(J.STRING))return{type:`string`,value:this.advance().value};if(this.check(J.REGEX))return{type:`regex`,pattern:this.advance().value};if(this.check(J.DOLLAR))return this.advance(),{type:`field`,index:this.parseFieldIndex()};if(this.check(J.LPAREN)){this.advance();let e=this.parseExpression();if(this.check(J.COMMA)){let t=[e];for(;this.check(J.COMMA);)this.advance(),t.push(this.parseExpression());return this.expect(J.RPAREN),{type:`tuple`,elements:t}}return this.expect(J.RPAREN),e}if(this.check(J.GETLINE)){this.advance();let e,t;return this.check(J.IDENT)&&(e=this.advance().value),this.check(J.LT)&&(this.advance(),t=this.parsePrimary()),{type:`getline`,variable:e,file:t}}if(this.check(J.IDENT)){let e=this.advance().value;if(this.check(J.LPAREN)){this.advance();let t=[];if(this.skipNewlines(),!this.check(J.RPAREN))for(t.push(this.parseExpression());this.check(J.COMMA);)this.advance(),this.skipNewlines(),t.push(this.parseExpression());return this.skipNewlines(),this.expect(J.RPAREN),{type:`call`,name:e,args:t}}if(this.check(J.LBRACKET)){this.advance();let t=[this.parseExpression()];for(;this.check(J.COMMA);)this.advance(),t.push(this.parseExpression());this.expect(J.RBRACKET);let n;if(t.length===1)n=t[0];else{n=t[0];for(let e=1;emJ,flagsForFuzzing:()=>hJ});function uJ(e){return e.replace(/\\t/g,` `).replace(/\\n/g,` +`).replace(/\\r/g,`\r`).replace(/\\b/g,`\b`).replace(/\\f/g,`\f`).replace(/\\a/g,`\x07`).replace(/\\v/g,`\v`).replace(/\\\\/g,`\\`)}function dJ(e){if(e===` `)return mG(`\\s+`);if(/[[\](){}.*+?^$|\\]/.test(e))try{return mG(e)}catch{return mG(fJ(e))}return mG(fJ(e))}function fJ(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var pJ,mJ,hJ,kCe=B(()=>{kB(),rV(),tq(),U(),yG(),AK(),aB(),sV(),XB(),_Ce(),OCe(),pJ={name:`awk`,summary:`pattern scanning and text processing language`,usage:`awk [OPTIONS] 'PROGRAM' [FILE...]`,options:[`-F FS use FS as field separator`,`-v VAR=VAL assign VAL to variable VAR`,` --help display this help and exit`]},mJ={name:`awk`,async execute(e,t){OK(t.requireDefenseContext,`awk`,`execution entry`);let n=(e,n)=>kK(t.requireDefenseContext,`awk`,e,n);if(aV(e))return iV(pJ);let r=new vG(/\s+/),i=` `,a=Object.create(null),o=0;for(let t=0;t0){let e=n.slice(0,r);a[e]=uJ(n.slice(r+1))}o=t+1}else{if(n.startsWith(`--`))return oV(`awk`,n);if(n.startsWith(`-`)&&n.length>1){let e=n[1];if(e!==`F`&&e!==`v`)return oV(`awk`,`-${e}`);o=t+1}else if(!n.startsWith(`-`)){o=t;break}}}if(o>=e.length)return{stdout:``,stderr:`awk: missing program +`,exitCode:1};let s=e[o],c=e.slice(o+1),l=new cJ({maxSourceLength:t.limits.maxStringLength,maxTokens:t.limits.maxAwkParserTokens,maxDepth:t.limits.maxAwkParserDepth,maxOperations:t.limits.maxAwkParserOperations}),u;try{u=l.parse(s)}catch(e){return nV(e),{stdout:``,stderr:`awk: ${e instanceof Error?e.message:String(e)} +`,exitCode:1}}let d={readFile:t.fs.readFile.bind(t.fs),writeFile:t.fs.writeFile.bind(t.fs),appendFile:async(e,r)=>{try{let i=await n(`appendFile read`,()=>t.fs.readFile(e));await n(`appendFile write`,()=>t.fs.writeFile(e,i+r))}catch(i){if(i instanceof eB)throw i;await n(`appendFile create`,()=>t.fs.writeFile(e,r))}},resolvePath:t.fs.resolvePath.bind(t.fs)},f=t.exec,p=fSe({fieldSep:r,maxIterations:t.limits.maxAwkIterations,maxOutputSize:Math.min(t.limits.maxStringLength,t.limits.maxOutputSize),maxArrayElements:t.limits.maxArrayElements,fs:d,cwd:t.cwd,exec:f?e=>n(`command pipe exec`,()=>f(e,{cwd:t.cwd,signal:t.signal})):void 0,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext});p.FS=i,p.vars=Object.assign(Object.create(null),a),p.ARGC=c.length+1,p.ARGV=Object.create(null),p.ARGV[0]=`awk`;for(let e=0;ee.pattern?.type!==`begin`&&e.pattern?.type!==`end`),g=u.rules.some(e=>e.pattern?.type===`end`);try{if(await n(`BEGIN execution`,()=>m.executeBegin()),p.shouldExit)return await n(`END execution after BEGIN exit`,()=>m.executeEnd()),{stdout:m.getOutput(),stderr:``,exitCode:m.getExitCode()};if(!h&&!g)return{stdout:m.getOutput(),stderr:``,exitCode:m.getExitCode()};let e=Math.min(t.limits.maxInputBytes,t.limits.maxStringLength),r=t.limits.maxArrayElements,i=0,a=async(t,a)=>{let o=V(a);if(o>e-i)throw new H(`aggregate input size limit exceeded (${e} bytes)`,`string_length`);i+=o;let s=+(a.length>0);for(let e=0;er+1)throw new H(`record array limit exceeded (${r})`,`array_elements`);let c=a.split(` +`);if(c.length>0&&c[c.length-1]===``&&c.pop(),c.length>r)throw new H(`record array limit exceeded (${r})`,`array_elements`);for(p.FILENAME=t,p.FNR=0,p.lines=c,p.lineIndex=-1,p.shouldNextFile=!1;p.lineIndexm.executeLine(c[e])),p.shouldExit||p.shouldNextFile)break}};if(c.length>0)for(let r of c){let o;try{let a=t.fs.resolvePath(t.cwd,r);if((await n(`input file stat`,()=>t.fs.stat(a))).size>e-i)throw new H(`aggregate input size limit exceeded (${e} bytes)`,`string_length`);o=await n(`input file read`,()=>t.fs.readFile(a))}catch(e){if(e instanceof eB||e instanceof H)throw e;return{stdout:``,stderr:`awk: ${r}: No such file or directory +`,exitCode:1}}if(await n(`input processing`,()=>a(r,o)),p.shouldExit)break}else await n(`stdin processing`,()=>a(``,vB(t.stdin)));return await n(`END execution`,()=>m.executeEnd()),{stdout:m.getOutput(),stderr:``,exitCode:m.getExitCode()}}catch(e){if(e instanceof eB)throw e;let t=e instanceof Error?e.message:String(e),n=e instanceof H?H.EXIT_CODE:2;return{stdout:m.getOutput(),stderr:`awk: ${t} +`,exitCode:n}}}},hJ={name:`awk`,flags:[{flag:`-F`,type:`value`,valueHint:`delimiter`},{flag:`-v`,type:`value`,valueHint:`string`}],stdinType:`text`,needsArgs:!0}});function gJ(e){let t=e.trim(),n=t.match(/^([+-]?\d*\.?\d+)\s*([kmgtpeKMGTPE])?[iI]?[bB]?$/);if(!n){let e=parseFloat(t);return Number.isNaN(e)?0:e}let r=parseFloat(n[1]),i=(n[2]||``).toLowerCase();return r*(xJ.get(i)??1)}function _J(e){let t=e.trim().toLowerCase().slice(0,3);return SJ.get(t)??0}function ACe(e,t){let n=e.split(/(\d+)/),r=t.split(/(\d+)/),i=Math.max(n.length,r.length);for(let e=0;e=i.length)return``;if(t.endField===void 0){let e=i[a]||``;return t.startChar!==void 0&&(e=e.slice(t.startChar-1)),t.ignoreLeading&&(e=e.trimStart()),e}let o=Math.min(t.endField-1,i.length-1),s=``;for(let e=a;e<=o&&ea&&(s+=n||` `),s+=r}return t.ignoreLeading&&(s=s.trimStart()),s}function bJ(e,t,n){let r=e,i=t;return n.dictionaryOrder&&(r=vJ(r),i=vJ(i)),n.ignoreCase&&(r=r.toLowerCase(),i=i.toLowerCase()),n.monthSort?_J(r)-_J(i):n.humanNumeric?gJ(r)-gJ(i):n.versionSort?ACe(r,i):n.numeric?(parseFloat(r)||0)-(parseFloat(i)||0):r.localeCompare(i)}function jCe(e){let{keys:t,fieldDelimiter:n,numeric:r,ignoreCase:i,reverse:a,humanNumeric:o,versionSort:s,dictionaryOrder:c,monthSort:l,ignoreLeadingBlanks:u,stable:d}=e;return(e,f)=>{let p=e,m=f;if(u&&(p=p.trimStart(),m=m.trimStart()),t.length===0){let t=bJ(p,m,{numeric:r,ignoreCase:i,humanNumeric:o,versionSort:s,dictionaryOrder:c,monthSort:l});if(t!==0)return a?-t:t;if(!d){let t=e.localeCompare(f);return a?-t:t}return 0}for(let e of t){let t=yJ(p,e,n),u=yJ(m,e,n);e.ignoreLeading&&(t=t.trimStart(),u=u.trimStart());let d={numeric:e.numeric??r,ignoreCase:e.ignoreCase??i,humanNumeric:e.humanNumeric??o,versionSort:e.versionSort??s,dictionaryOrder:e.dictionaryOrder??c,monthSort:e.monthSort??l},f=e.reverse??a,h=bJ(t,u,d);if(h!==0)return f?-h:h}if(!d){let t=e.localeCompare(f);return a?-t:t}return 0}}function MCe(e,t){if(t.keys.length===0){if(t.ignoreCase){let t=new Set;return e.filter(e=>{let n=e.toLowerCase();return!t.has(n)&&(t.add(n),!0)})}return[...new Set(e)]}let n=t.keys[0],r=new Set;return e.filter(e=>{let i=yJ(e,n,t.fieldDelimiter);return(n.ignoreCase??t.ignoreCase)&&(i=i.toLowerCase()),!r.has(i)&&(r.add(i),!0)})}var xJ,SJ,NCe=B(()=>{xJ=new Map([[``,1],[`k`,1024],[`m`,1048576],[`g`,1073741824],[`t`,1099511627776],[`p`,0x4000000000000],[`e`,0x1000000000000000]]),SJ=new Map([[`jan`,1],[`feb`,2],[`mar`,3],[`apr`,4],[`may`,5],[`jun`,6],[`jul`,7],[`aug`,8],[`sep`,9],[`oct`,10],[`nov`,11],[`dec`,12]])});function CJ(e){let t={startField:1},n=``,r=e,i=r.match(/([bdfhMnrV]+)$/);i&&(n=i[1],r=r.slice(0,-n.length)),n.includes(`n`)&&(t.numeric=!0),n.includes(`r`)&&(t.reverse=!0),n.includes(`f`)&&(t.ignoreCase=!0),n.includes(`b`)&&(t.ignoreLeading=!0),n.includes(`h`)&&(t.humanNumeric=!0),n.includes(`V`)&&(t.versionSort=!0),n.includes(`d`)&&(t.dictionaryOrder=!0),n.includes(`M`)&&(t.monthSort=!0);let a=r.split(`,`);if(a.length===0||a[0]===``)return null;let o=a[0].split(`.`),s=parseInt(o[0],10);if(Number.isNaN(s)||s<1)return null;if(t.startField=s,o.length>1&&o[1]){let e=parseInt(o[1],10);!Number.isNaN(e)&&e>=1&&(t.startChar=e)}if(a.length>1&&a[1]){let e=a[1],n=e.match(/([bdfhMnrV]+)$/);if(n){let r=n[1];r.includes(`n`)&&(t.numeric=!0),r.includes(`r`)&&(t.reverse=!0),r.includes(`f`)&&(t.ignoreCase=!0),r.includes(`b`)&&(t.ignoreLeading=!0),r.includes(`h`)&&(t.humanNumeric=!0),r.includes(`V`)&&(t.versionSort=!0),r.includes(`d`)&&(t.dictionaryOrder=!0),r.includes(`M`)&&(t.monthSort=!0),e=e.slice(0,-r.length)}let r=e.split(`.`);if(r[0]){let e=parseInt(r[0],10);if(!Number.isNaN(e)&&e>=1&&(t.endField=e),r.length>1&&r[1]){let e=parseInt(r[1],10);!Number.isNaN(e)&&e>=1&&(t.endChar=e)}}}return t}var PCe=B(()=>{}),wJ={};wz(wJ,{flagsForFuzzing:()=>DJ,sortCommand:()=>EJ});var TJ,EJ,DJ,FCe=B(()=>{kB(),mV(),sV(),NCe(),PCe(),TJ={name:`sort`,summary:`sort lines of text files`,usage:`sort [OPTION]... [FILE]...`,options:[`-b, --ignore-leading-blanks ignore leading blanks`,`-d, --dictionary-order consider only blanks and alphanumeric characters`,`-f, --ignore-case fold lower case to upper case characters`,`-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)`,`-M, --month-sort compare (unknown) < 'JAN' < ... < 'DEC'`,`-n, --numeric-sort compare according to string numerical value`,`-r, --reverse reverse the result of comparisons`,`-V, --version-sort natural sort of (version) numbers within text`,`-c, --check check for sorted input; do not sort`,`-o, --output=FILE write result to FILE instead of stdout`,`-s, --stable stabilize sort by disabling last-resort comparison`,`-u, --unique output only unique lines`,`-k, --key=KEYDEF sort via a key; KEYDEF gives location and type`,`-t, --field-separator=SEP use SEP as field separator`,` --help display this help and exit`],description:`KEYDEF is F[.C][OPTS][,F[.C][OPTS]] + F is a field number (1-indexed) + C is a character position within the field (1-indexed) + OPTS can be: b d f h M n r V (per-key modifiers) + +Examples: + -k1 sort by first field + -k2,2 sort by second field only + -k1.3 sort by first field starting at 3rd character + -k1,2n sort by fields 1-2 numerically + -k2 -k1 sort by field 2, then by field 1`},EJ={name:`sort`,async execute(e,t){if(aV(e))return iV(TJ);let n={reverse:!1,numeric:!1,unique:!1,ignoreCase:!1,humanNumeric:!1,versionSort:!1,dictionaryOrder:!1,monthSort:!1,ignoreLeadingBlanks:!1,stable:!1,checkOnly:!1,outputFile:null,keys:[],fieldDelimiter:null},r=[];for(let t=0;t0&&a[a.length-1]===``&&a.pop();let o=jCe(n);if(n.checkOnly){let e=r.length>0?r[0]:`-`;for(let t=1;t0)return{stdout:``,stderr:`sort: ${e}:${t+1}: disorder: ${a[t]} +`,exitCode:1};return{stdout:``,stderr:``,exitCode:0}}a.sort(o),n.unique&&(a=MCe(a,n));let s=a.length>0?`${a.join(` +`)} +`:``;if(n.outputFile){let e=t.fs.resolvePath(t.cwd,n.outputFile);return await t.fs.writeFile(e,s),{stdout:``,stderr:``,exitCode:0}}return{stdout:s,stderr:``,exitCode:0}}},DJ={name:`sort`,flags:[{flag:`-r`,type:`boolean`},{flag:`-n`,type:`boolean`},{flag:`-u`,type:`boolean`},{flag:`-f`,type:`boolean`},{flag:`-h`,type:`boolean`},{flag:`-V`,type:`boolean`},{flag:`-d`,type:`boolean`},{flag:`-M`,type:`boolean`},{flag:`-b`,type:`boolean`},{flag:`-s`,type:`boolean`},{flag:`-c`,type:`boolean`},{flag:`-k`,type:`value`,valueHint:`string`},{flag:`-t`,type:`value`,valueHint:`delimiter`},{flag:`-o`,type:`value`,valueHint:`path`}],stdinType:`text`,needsFiles:!0}}),OJ={};wz(OJ,{flagsForFuzzing:()=>MJ,uniqCommand:()=>jJ});var kJ,AJ,jJ,MJ,ICe=B(()=>{kB(),lV(),mV(),sV(),kJ={name:`uniq`,summary:`report or omit repeated lines`,usage:`uniq [OPTION]... [INPUT [OUTPUT]]`,options:[`-c, --count prefix lines by the number of occurrences`,`-d, --repeated only print duplicate lines`,`-i, --ignore-case ignore case when comparing`,`-u, --unique only print unique lines`,` --help display this help and exit`]},AJ={count:{short:`c`,long:`count`,type:`boolean`},duplicatesOnly:{short:`d`,long:`repeated`,type:`boolean`},uniqueOnly:{short:`u`,long:`unique`,type:`boolean`},ignoreCase:{short:`i`,long:`ignore-case`,type:`boolean`}},jJ={name:`uniq`,async execute(e,t){if(aV(e))return iV(kJ);let n=cV(`uniq`,e,AJ);if(!n.ok)return n.error;let{count:r,duplicatesOnly:i,uniqueOnly:a,ignoreCase:o}=n.result.flags,s=n.result.positional,c=await pV(t,s,{cmdName:`uniq`});if(!c.ok)return c.error;let l=(o?vB(c.content):c.content).split(` +`);if(l.length>0&&l[l.length-1]===``&&l.pop(),l.length===0)return{stdout:``,stderr:``,exitCode:0};let u=[],d=l[0],f=1,p=(e,t)=>o?e.toLowerCase()===t.toLowerCase():e===t;for(let e=1;ee.count>1):a&&(m=u.filter(e=>e.count===1));let h=``;for(let{line:e,count:t}of m)h+=r?`${String(t).padStart(4)} ${e} +`:`${e} +`;return o?{stdout:h,stderr:``,exitCode:0}:{stdout:h,stderr:``,exitCode:0,stdoutKind:`bytes`,stdoutEncoding:`binary`}}},MJ={name:`uniq`,flags:[{flag:`-c`,type:`boolean`},{flag:`-d`,type:`boolean`},{flag:`-u`,type:`boolean`},{flag:`-i`,type:`boolean`}],stdinType:`text`,needsFiles:!0}}),NJ={};wz(NJ,{commCommand:()=>FJ,flagsForFuzzing:()=>IJ});var PJ,FJ,IJ,LCe=B(()=>{kB(),sV(),PJ={name:`comm`,summary:`compare two sorted files line by line`,usage:`comm [OPTION]... FILE1 FILE2`,options:[`-1 suppress column 1 (lines unique to FILE1)`,`-2 suppress column 2 (lines unique to FILE2)`,`-3 suppress column 3 (lines that appear in both files)`,` --help display this help and exit`]},FJ={name:`comm`,async execute(e,t){if(aV(e))return iV(PJ);let n=!1,r=!1,i=!1,a=[];for(let t of e)if(t===`-1`)n=!0;else if(t===`-2`)r=!0;else if(t===`-3`)i=!0;else if(t===`-12`||t===`-21`)n=!0,r=!0;else if(t===`-13`||t===`-31`)n=!0,i=!0;else if(t===`-23`||t===`-32`)r=!0,i=!0;else if(t===`-123`||t===`-132`||t===`-213`||t===`-231`||t===`-312`||t===`-321`)n=!0,r=!0,i=!0;else{if(t.startsWith(`-`)&&t!==`-`)return oV(`comm`,t);a.push(t)}if(a.length!==2)return{stdout:``,stderr:`comm: missing operand +Try 'comm --help' for more information. +`,exitCode:1};let o=async e=>{if(e===`-`)return vB(t.stdin);try{let n=t.fs.resolvePath(t.cwd,e);return await t.fs.readFile(n)}catch{return null}},s=await o(a[0]);if(s===null)return{stdout:``,stderr:`comm: ${a[0]}: No such file or directory +`,exitCode:1};let c=await o(a[1]);if(c===null)return{stdout:``,stderr:`comm: ${a[1]}: No such file or directory +`,exitCode:1};let l=s.split(` +`),u=c.split(` +`);l.length>0&&l[l.length-1]===``&&l.pop(),u.length>0&&u[u.length-1]===``&&u.pop();let d=0,f=0,p=``,m=n?``:` `,h=(n?``:` `)+(r?``:` `);for(;d=l.length?(r||(p+=`${m}${u[f]} +`),f++):f>=u.length||l[d]u[f]?(r||(p+=`${m}${u[f]} +`),f++):(i||(p+=`${h}${l[d]} +`),d++,f++);return{stdout:p,stderr:``,exitCode:0}}},IJ={name:`comm`,flags:[{flag:`-1`,type:`boolean`},{flag:`-2`,type:`boolean`},{flag:`-3`,type:`boolean`}],needsArgs:!0,minArgs:2}}),LJ={};wz(LJ,{cutCommand:()=>zJ,flagsForFuzzing:()=>BJ});function RCe(e,t){let n=[],r=e.split(`,`);if(r.length>t)throw new H(`cut: range count limit exceeded (${t})`,`array_elements`);for(let e of r)if(e.includes(`-`)){let[t,r]=e.split(`-`),i=t?Number(t):1,a=r?Number(r):null;if(!Number.isSafeInteger(i)||i<1||a!==null&&(!Number.isSafeInteger(a)||a=0&&!r.has(i)&&(r.add(i),n.push(e[i]))}return n}var RJ,zJ,BJ,BCe=B(()=>{sH(),kB(),U(),mV(),sV(),RJ={name:`cut`,summary:`remove sections from each line of files`,usage:`cut [OPTION]... [FILE]...`,options:[`-c LIST select only these characters`,`-d DELIM use DELIM instead of TAB for field delimiter`,`-f LIST select only these fields`,`-s, --only-delimited do not print lines without delimiters`,` --help display this help and exit`]},zJ={name:`cut`,async execute(e,t){if(aV(e))return iV(RJ);let n=` `,r=null,i=null,a=!1,o=[];for(let t=0;t0&&c[c.length-1]===``&&c.pop();let l=RCe(r||i||`1`,t.limits.maxArrayElements),u=new oH(Math.min(t.limits.maxOutputSize,t.limits.maxStringLength),`cut`),d=0,f=e=>{if(!Number.isSafeInteger(e)||e<0||e>t.limits.maxLoopIterations-d)throw new H(`cut: range expansion limit exceeded (${t.limits.maxLoopIterations})`,`iterations`);d+=e,t.executionScope?.consumeWork(e,`cut range expansion`)};for(let e of c)if(i){let t=Array.from(e),n=[];for(let e of l){let r=e.start-1,i=e.end===null?t.length:e.end;f(Math.max(0,Math.min(i,t.length)-r));for(let e=r;e=0&&n.push(t[e])}u.append(`${n.join(``)} +`)}else{if(a&&!e.includes(n))continue;let t=e.split(n);for(let e of l){let n=e.start-1,r=e.end===null?t.length:e.end;f(Math.max(0,Math.min(r,t.length)-n))}let r=zCe(t,l);u.append(`${r.join(n)} +`)}return i?{stdout:u.build(),stderr:``,exitCode:0}:{stdout:u.build(),stderr:``,exitCode:0,stdoutKind:`bytes`,stdoutEncoding:`binary`}}},BJ={name:`cut`,flags:[{flag:`-d`,type:`value`,valueHint:`delimiter`},{flag:`-f`,type:`value`,valueHint:`string`},{flag:`-c`,type:`value`,valueHint:`string`},{flag:`-s`,type:`boolean`}],stdinType:`text`,needsFiles:!0}}),VJ={};wz(VJ,{flagsForFuzzing:()=>KJ,pasteCommand:()=>GJ});function HJ(e,t){if(e.length===0)return``;if(e.length===1)return e[0];if(t.length===0)return e.join(``);let n=e[0];for(let r=1;r{sH(),kB(),rV(),U(),lV(),sV(),UJ={name:`paste`,summary:`merge lines of files`,usage:`paste [OPTION]... [FILE]...`,description:[`Write lines consisting of the sequentially corresponding lines from`,`each FILE, separated by TABs, to standard output.`,``,`With no FILE, or when FILE is -, read standard input.`],options:[`-d, --delimiters=LIST reuse characters from LIST instead of TABs`,`-s, --serial paste one file at a time instead of in parallel`,` --help display this help and exit`],examples:[`paste file1 file2 Merge file1 and file2 side by side`,`paste -d, file1 file2 Use comma as delimiter`,`paste -s file1 Paste all lines of file1 on one line`,`paste - - < file Paste pairs of lines from file`]},WJ={delimiter:{short:`d`,long:`delimiters`,type:`string`,default:` `},serial:{short:`s`,long:`serial`,type:`boolean`}},GJ={name:`paste`,async execute(e,t){if(aV(e))return iV(UJ);let n=cV(`paste`,e,WJ);if(!n.ok)return n.error;let r=n.result.flags.delimiter,i=n.result.flags.serial,a=n.result.positional;if(a.length>t.limits.maxArrayElements)throw new H(`paste: file operand limit exceeded (${t.limits.maxArrayElements})`,`array_elements`);if(V(r)>t.limits.maxStringLength)throw new H(`paste: delimiter size limit exceeded (${t.limits.maxStringLength} bytes)`,`string_length`);if(a.length===0)return{stdout:``,stderr:`usage: paste [-s] [-d delimiters] file ... +`,exitCode:1};let o=vB(t.stdin),s=o?o.split(` +`):[``];s.length>0&&s[s.length-1]===``&&s.pop();let c=a.filter(e=>e===`-`).length,l=[],u=0,d=V(o),f=e=>{if(e.length>t.limits.maxArrayElements-u)throw new H(`paste: line limit exceeded (${t.limits.maxArrayElements})`,`array_elements`);u+=e.length,t.executionScope?.consumeWork(e.length,`paste lines`)},p=0;for(let e of a)if(e===`-`){let e=[];for(let t=p;tt.limits.maxInputBytes-d)throw new H(`paste: aggregate input size limit exceeded (${t.limits.maxInputBytes} bytes)`,`string_length`);d+=r,t.executionScope?.consumeInput(r,`paste`);let i=e.split(` +`);i.length>0&&i[i.length-1]===``&&i.pop(),f(i),l.push(i)}catch(t){return nV(t),{stdout:``,stderr:`paste: ${e}: No such file or directory +`,exitCode:1}}}let m=new oH(Math.min(t.limits.maxOutputSize,t.limits.maxStringLength),`paste`);if(i)for(let e of l)e&&m.append(`${HJ(e,r)} +`);else{let e=0;for(let t of l)e=Math.max(e,t?.length??0);for(let t=0;t$J,trCommand:()=>QJ});function JJ(e,t,n,r){let i=``,a=0,o=e=>{if(e.length>t-i.length)throw new H(`tr: expanded SET exceeds string length limit (${t})`,`string_length`);i+=e},s=(e=1)=>{if(e>n-r.iterations)throw new H(`tr: SET expansion iteration limit exceeded (${n})`,`iterations`);r.iterations+=e};for(;a=n?r-n+1:0;if(s(o),o>t-i.length)throw new H(`tr: expanded SET exceeds string length limit (${t})`,`string_length`);for(let e=n;e<=r;e++)i+=String.fromCharCode(e);a+=3;continue}o(e[a]),a++}return i}var YJ,XJ,ZJ,QJ,$J,HCe=B(()=>{kB(),rV(),vH(),U(),lV(),sV(),YJ={name:`tr`,summary:`translate or delete characters`,usage:`tr [OPTION]... SET1 [SET2]`,options:[`-c, -C, --complement use the complement of SET1`,`-d, --delete delete characters in SET1`,`-s, --squeeze-repeats squeeze repeated characters`,` --help display this help and exit`],description:`SET syntax: + a-z character range + [:alnum:] all letters and digits + [:alpha:] all letters + [:digit:] all digits + [:lower:] all lowercase letters + [:upper:] all uppercase letters + [:space:] all whitespace + [:blank:] horizontal whitespace + [:punct:] all punctuation + [:print:] all printable characters + [:graph:] all printable characters except space + [:cntrl:] all control characters + [:xdigit:] all hexadecimal digits + \\n, \\t, \\r escape sequences`},XJ=new Map([[`[:alnum:]`,`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`],[`[:alpha:]`,`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`],[`[:blank:]`,` `],[`[:cntrl:]`,Array.from({length:32},(e,t)=>String.fromCharCode(t)).join(``).concat(``)],[`[:digit:]`,`0123456789`],[`[:graph:]`,Array.from({length:94},(e,t)=>String.fromCharCode(33+t)).join(``)],[`[:lower:]`,`abcdefghijklmnopqrstuvwxyz`],[`[:print:]`,Array.from({length:95},(e,t)=>String.fromCharCode(32+t)).join(``)],[`[:punct:]`,`!"#$%&'()*+,-./:;<=>?@[\\]^_\`{|}~`],[`[:space:]`,` +\r\f\v`],[`[:upper:]`,`ABCDEFGHIJKLMNOPQRSTUVWXYZ`],[`[:xdigit:]`,`0123456789ABCDEFabcdef`]]),ZJ={complement:{short:`c`,long:`complement`,type:`boolean`},complementUpper:{short:`C`,type:`boolean`},delete:{short:`d`,long:`delete`,type:`boolean`},squeeze:{short:`s`,long:`squeeze-repeats`,type:`boolean`}},QJ={name:`tr`,async execute(e,t){if(aV(e))return iV(YJ);let n=cV(`tr`,e,ZJ);if(!n.ok)return n.error;let r=n.result.flags.complement||n.result.flags.complementUpper,i=n.result.flags.delete,a=n.result.flags.squeeze,o=n.result.positional;if(o.length<1)return{stdout:``,stderr:`tr: missing operand +`,exitCode:1};if(!i&&!a&&o.length<2)return{stdout:``,stderr:`tr: missing operand after SET1 +`,exitCode:1};let s,c,l=Math.min(t.limits.maxInputBytes,t.limits.maxStringLength),u=t.limits.maxLoopIterations,d=t.limits.maxArrayElements,f=Math.min(t.limits.maxOutputSize,t.limits.maxStringLength);try{let e={iterations:0};s=JJ(o[0],l,u,e),c=o.length>1?JJ(o[1],l,u,e):``}catch(e){return nV(e),{stdout:``,stderr:`${_H(e.message)} +`,exitCode:1}}if(t.stdin.length>l)throw new H(`tr: input size limit exceeded (${l} bytes)`,`string_length`);let p=vB(t.stdin);if(s.length>d||c.length>d)throw new H(`tr: array element limit exceeded (${d})`,`array_elements`);let m=new Set(s),h=new Set(c),g=e=>{let t=m.has(e);return r?!t:t},_=``,v=0,y=e=>{let t=V(e);if(t>f-v)throw new H(`tr: output size limit exceeded (${f} bytes)`,`output_size`);_+=e,v+=t};if(i)for(let e of p)g(e)||y(e);else if(a&&o.length===1){let e=``;for(let t of p)g(t)&&t===e||(y(t),e=t)}else{let e=``,t=t=>{a&&h.has(t)&&t===e||(y(t),e=t)};if(r){let e=c.length>0?c[c.length-1]:``;for(let n of p)m.has(n)?t(n):t(e)}else{let e=new Map;for(let t=0;trY,rev:()=>nY});function UCe(e){return Array.from(e).reverse().join(``)}var tY,nY,rY,WCe=B(()=>{kB(),sV(),tY={name:`rev`,summary:`reverse lines characterwise`,usage:`rev [file ...]`,description:`Copies the specified files to standard output, reversing the order of characters in every line. If no files are specified, standard input is read.`,examples:[`echo 'hello' | rev # Output: olleh`,`rev file.txt # Reverse each line in file`]},nY={name:`rev`,execute:async(e,t)=>{if(aV(e))return iV(tY);let n=[];for(let t of e)if(t===`--`){let r=e.indexOf(t);n.push(...e.slice(r+1));break}else{if(t.startsWith(`-`)&&t!==`-`)return oV(`rev`,t);n.push(t)}let r=``,i=e=>{let t=e.split(` +`),n=e.endsWith(` +`)&&t[t.length-1]===``;return n&&t.pop(),t.map(UCe).join(` +`)+(n?` +`:``)};if(n.length===0)r=i(vB(t.stdin)??``);else for(let e of n)if(e===`-`){let e=vB(t.stdin)??``;r+=i(e)}else{let n=t.fs.resolvePath(t.cwd,e),a=await t.fs.readFile(n);if(a===null)return{exitCode:1,stdout:r,stderr:`rev: ${e}: No such file or directory +`};r+=i(a)}return{exitCode:0,stdout:r,stderr:``}}},rY={name:`rev`,flags:[],stdinType:`text`,needsFiles:!0}}),iY={};wz(iY,{flagsForFuzzing:()=>cY,nl:()=>sY});function GCe(e,t,n){let r=String(e);switch(t){case`ln`:return r.padEnd(n);case`rn`:return r.padStart(n);case`rz`:return r.padStart(n,`0`);default:return t}}function KCe(e,t){switch(t){case`a`:return!0;case`t`:return e.trim().length>0;case`n`:return!1;default:return t}}function aY(e,t,n,r){if(e===``)return{output:``,nextNumber:n};let i=e.split(` +`),a=[],o=0,s=n,c=e.endsWith(` +`)&&i[i.length-1]===``;c&&i.pop();for(let e of i){let n=+(a.length>0),i=V(t.separator)+V(e);if(KCe(e,t.bodyStyle)){let c=Math.max(String(s).length,t.width)+i+n;if(c>r-o)throw new H(`nl: output size limit exceeded (${r} bytes)`,`output_size`);let l=`${GCe(s,t.numberFormat,t.width)}${t.separator}${e}`;a.push(l),o+=c,s+=t.increment}else{let s=t.width+i+n;if(s>r-o)throw new H(`nl: output size limit exceeded (${r} bytes)`,`output_size`);let c=`${` `.repeat(t.width)}${t.separator}${e}`;a.push(c),o+=s}}if(c&&o+1>r)throw new H(`nl: output size limit exceeded (${r} bytes)`,`output_size`);return{output:a.join(` +`)+(c?` +`:``),nextNumber:s}}var oY,sY,cY,qCe=B(()=>{kB(),U(),sV(),oY={name:`nl`,summary:`number lines of files`,usage:`nl [OPTION]... [FILE]...`,description:`Write each FILE to standard output, with line numbers added. If no FILE is specified, standard input is read.`,options:[`-b STYLE Body numbering style: a (all), t (non-empty), n (none)`,`-n FORMAT Number format: ln (left), rn (right), rz (right zeros)`,`-w WIDTH Number width (default: 6)`,`-s SEP Separator after number (default: TAB)`,`-v START Starting line number (default: 1)`,`-i INCR Line number increment (default: 1)`],examples:[`nl file.txt # Number non-empty lines`,`nl -ba file.txt # Number all lines`,`nl -n rz -w 3 file.txt # Right-justified with zeros`,`nl -s ': ' file.txt # Use ': ' as separator`]},sY={name:`nl`,execute:async(e,t)=>{if(aV(e))return iV(oY);let n={bodyStyle:`t`,numberFormat:`rn`,width:6,separator:` `,startNumber:1,increment:1},r=[],i=Math.min(t.limits.maxStringLength,t.limits.maxOutputSize),a=i,o=0;for(;oi)return{exitCode:1,stdout:``,stderr:`nl: invalid line number field width: '${e[o+1]}' +`};n.width=t,o+=2}else if(t.startsWith(`-w`)){let e=/^\d+$/.test(t.slice(2))?Number(t.slice(2)):NaN;if(!Number.isSafeInteger(e)||e<1||e>i)return{exitCode:1,stdout:``,stderr:`nl: invalid line number field width: '${t.slice(2)}' +`};n.width=e,o++}else if(t===`-s`&&o+1pY,fold:()=>fY});function JCe(e,t,n){return n?V(e):e===` `?8-t%8:e===`\b`?-1:1}function YCe(e,t){if(e.length===0)return e;let{width:n,breakAtSpaces:r,countBytes:i}=t,a=[],o=``,s=0,c=-1,l=0;for(let t of e){let e=JCe(t,s,i);s+e>n&&o.length>0?r&&c>=0?(a.push(o.slice(0,c+1)),o=o.slice(c+1)+t,s=s-l-1+e,c=-1,l=0):(a.push(o),o=t,s=e,c=-1,l=0):(o+=t,s+=e,(t===` `||t===` `)&&(c=o.length-1,l=s-e))}return o.length>0&&a.push(o),a.join(` +`)}function uY(e,t){if(e===``)return``;let n=e.split(` +`),r=e.endsWith(` +`)&&n[n.length-1]===``;return r&&n.pop(),n.map(e=>YCe(e,t)).join(` +`)+(r?` +`:``)}var dY,fY,pY,XCe=B(()=>{kB(),sV(),dY={name:`fold`,summary:`wrap each input line to fit in specified width`,usage:`fold [OPTION]... [FILE]...`,description:`Wrap input lines in each FILE, writing to standard output. If no FILE is specified, standard input is read.`,options:[`-w WIDTH Use WIDTH columns instead of 80`,`-s Break at spaces`,`-b Count bytes rather than columns`],examples:[`fold -w 40 file.txt # Wrap at 40 columns`,`fold -sw 40 file.txt # Word wrap at 40 columns`,`echo 'long line' | fold -w 5 # Force wrap at 5`]},fY={name:`fold`,execute:async(e,t)=>{if(aV(e))return iV(dY);let n={width:80,breakAtSpaces:!1,countBytes:!1},r=[],i=0;for(;i2){let e=parseInt(t.slice(2),10);if(Number.isNaN(e)||e<1)return{exitCode:1,stdout:``,stderr:`fold: invalid number of columns: '${t.slice(2)}' +`};n.width=e,i++}else if(t===`-s`)n.breakAtSpaces=!0,i++;else if(t===`-b`)n.countBytes=!0,i++;else if(t===`-bs`||t===`-sb`)n.breakAtSpaces=!0,n.countBytes=!0,i++;else if(t.match(/^-[sb]+w\d+$/)){t.includes(`s`)&&(n.breakAtSpaces=!0),t.includes(`b`)&&(n.countBytes=!0);let e=t.replace(/^-[sb]+w/,``),r=parseInt(e,10);if(Number.isNaN(r)||r<1)return{exitCode:1,stdout:``,stderr:`fold: invalid number of columns: '${e}' +`};n.width=r,i++}else if(t.match(/^-[sb]+w$/)&&i+1vY,flagsForFuzzing:()=>yY});function hY(e,t,n){let r=e.split(`,`).map(e=>e.trim());if(r.length>n)return null;let i=[];for(let e of r){let n=/^\d+$/.test(e)?Number(e):NaN;if(!Number.isSafeInteger(n)||n<1||n>t)return null;i.push(n)}for(let e=1;ee)return n-e;if(t.length>=2){let n=t[t.length-1]-t[t.length-2],r=t[t.length-1];return r+(Math.floor((e-r)/n)+1)*n-e}return 1}function QCe(e,t,n){let{tabStops:r,leadingOnly:i}=t,a=``,o=0,s=!0,c=0;for(let t of e)if(t===` `){if(i&&!s){if(c+1>n)throw new H(`expand: output size limit exceeded (${n} bytes)`,`output_size`);a+=t,c++,o++}else{let e=ZCe(o,r);if(e>n-c)throw new H(`expand: output size limit exceeded (${n} bytes)`,`output_size`);a+=` `.repeat(e),c+=e,o+=e}}else{t!==` `&&t!==` `&&(s=!1);let e=V(t);if(e>n-c)throw new H(`expand: output size limit exceeded (${n} bytes)`,`output_size`);a+=t,c+=e,o++}return a}function gY(e,t,n){if(e===``)return``;let r=e.split(` +`),i=e.endsWith(` +`)&&r[r.length-1]===``;i&&r.pop();let a=[],o=0;for(let e of r){let r=+(a.length>0),i=QCe(e,t,n-o-r);o+=r+V(i),a.push(i)}if(i&&o+1>n)throw new H(`expand: output size limit exceeded (${n} bytes)`,`output_size`);return a.join(` +`)+(i?` +`:``)}var _Y,vY,yY,$Ce=B(()=>{kB(),U(),sV(),XB(),_Y={name:`expand`,summary:`convert tabs to spaces`,usage:`expand [OPTION]... [FILE]...`,description:`Convert TABs in each FILE to spaces, writing to standard output. If no FILE is specified, standard input is read.`,options:[`-t N Use N spaces per tab (default: 8)`,`-t LIST Use comma-separated list of tab stops`,`-i Only convert leading tabs on each line`],examples:[`expand file.txt # Convert all tabs to 8 spaces`,`expand -t 4 file.txt # Use 4-space tabs`,`expand -t 4,8,12 file.txt # Custom tab stops`]},vY={name:`expand`,execute:async(e,t)=>{if(aV(e))return iV(_Y);let n={tabStops:[8],leadingOnly:!1},r=[],i=Math.min(t.limits.maxStringLength,t.limits.maxOutputSize),a=t.limits.maxArrayElements,o=0;for(;o2){let e=hY(t.slice(2),i,a);if(!e)return{exitCode:1,stdout:``,stderr:`expand: invalid tab size: '${t.slice(2)}' +`};n.tabStops=e,o++}else if(t===`--tabs`&&o+1EY,unexpand:()=>TY});function xY(e){let t=e.split(`,`).map(e=>e.trim()),n=[];for(let e of t){let t=parseInt(e,10);if(Number.isNaN(t)||t<1)return null;n.push(t)}for(let e=1;ee)return n;if(t.length>=2){let n=t[t.length-1]-t[t.length-2],r=t[t.length-1];return r+(Math.floor((e-r)/n)+1)*n}return-1}function ewe(e,t){let{tabStops:n,allBlanks:r}=t,i=``,a=0,o=``,s=0,c=!0,l=()=>{if(o.length===0)return;let e=s+o.length;if(!r&&!c){i+=o,o=``;return}let t=s,a=``;for(;tt)a+=` `,t=r;else break}let l=e-t;l>0&&(a+=` `.repeat(l)),i+=a,o=``};for(let t of e)t===` `?(o.length===0&&(s=a),o+=t,a++):t===` `?(l(),i+=t,a=SY(a,n)):(l(),i+=t,a++,c=!1);return l(),i}function CY(e,t){if(e===``)return``;let n=e.split(` +`),r=e.endsWith(` +`)&&n[n.length-1]===``;return r&&n.pop(),n.map(e=>ewe(e,t)).join(` +`)+(r?` +`:``)}var wY,TY,EY,twe=B(()=>{kB(),sV(),wY={name:`unexpand`,summary:`convert spaces to tabs`,usage:`unexpand [OPTION]... [FILE]...`,description:`Convert blanks in each FILE to TABs, writing to standard output. If no FILE is specified, standard input is read.`,options:[`-t N Use N spaces per tab (default: 8)`,`-t LIST Use comma-separated list of tab stops`,`-a Convert all sequences of blanks (not just leading)`],examples:[`unexpand file.txt # Convert leading spaces to tabs`,`unexpand -a file.txt # Convert all space sequences`,`unexpand -t 4 file.txt # Use 4-space tabs`]},TY={name:`unexpand`,execute:async(e,t)=>{if(aV(e))return iV(wY);let n={tabStops:[8],allBlanks:!1},r=[],i=0;for(;i2){let e=xY(t.slice(2));if(!e)return{exitCode:1,stdout:``,stderr:`unexpand: invalid tab size: '${t.slice(2)}' +`};n.tabStops=e,i++}else if(t===`--tabs`&&i+1MY,strings:()=>jY});function nwe(e){return e>=32&&e<=126||e===9}function OY(e,t){if(t===null)return``;switch(t){case`o`:return`${e.toString(8).padStart(7,` `)} `;case`x`:return`${e.toString(16).padStart(7,` `)} `;case`d`:return`${e.toString(10).padStart(7,` `)} `;default:return t}}function kY(e,t,n,r=!1,i){let a=[],o=0,s=0,c=typeof e==`string`&&!r?new TextEncoder().encode(e):e;if(c.length>n.maxStringLength-n.inputBytes)throw new H(`strings: aggregate input size limit exceeded (${n.maxStringLength} bytes)`,`string_length`);n.inputBytes+=c.length;let l=new TextDecoder,u=(e,t)=>typeof c==`string`?c.slice(e,t):l.decode(c.subarray(e,t)),d=e=>{if(++n.iterations>n.maxIterations)throw new H(`strings: iteration limit exceeded (${n.maxIterations})`,`iterations`);if(n.resultCount>=n.maxArrayElements)throw new H(`strings: array element limit exceeded (${n.maxArrayElements})`,`array_elements`);let t=e.length+1;if(t>n.maxOutputSize-n.outputBytes)throw new H(`strings: output size limit exceeded (${n.maxOutputSize} bytes)`,`output_size`);a.push(e),n.resultCount++,n.outputBytes+=t};for(let e=0;e=n.maxStringLength)throw new H(`strings: string length limit exceeded (${n.maxStringLength} bytes)`,`string_length`);o++}else o>=t.minLength&&d(`${OY(s,t.offsetFormat)}${u(s,e)}`),o=0}return o>=t.minLength&&d(`${OY(s,t.offsetFormat)}${u(s,c.length)}`),a}var AY,jY,MY,rwe=B(()=>{U(),sV(),AY={name:`strings`,summary:`print the sequences of printable characters in files`,usage:`strings [OPTION]... [FILE]...`,description:`For each FILE, print the printable character sequences that are at least MIN characters long. If no FILE is specified, standard input is read.`,options:[`-n MIN Print sequences of at least MIN characters (default: 4)`,`-t FORMAT Print offset before each string (o=octal, x=hex, d=decimal)`,`-a Scan the entire file (default behavior)`,`-e ENCODING Select character encoding (s=7-bit, S=8-bit)`],examples:[`strings file.bin # Extract strings (min 4 chars)`,`strings -n 8 file.bin # Extract strings (min 8 chars)`,`strings -t x file.bin # Show hex offset`,`echo 'hello' | strings # Read from stdin`]},jY={name:`strings`,execute:async(e,t)=>{if(aV(e))return iV(AY);let n={minLength:4,offsetFormat:null},r=[],i=0;for(;it.stdin;if(r.length===0){let e=kY(s(),n,o,!0,t.signal);a=e.length>0?`${e.join(` +`)} +`:``}else for(let e of r){let r;if(e===`-`)r=s();else{let n=t.fs.resolvePath(t.cwd,e);try{r=await t.fs.readFileBuffer(n)}catch{return{exitCode:1,stdout:a,stderr:`strings: ${e}: No such file or directory +`}}}let i=kY(r,n,o,typeof r==`string`,t.signal);i.length>0&&(a+=`${i.join(` +`)} +`)}return{exitCode:0,stdout:a,stderr:``}}},MY={name:`strings`,flags:[{flag:`-n`,type:`value`,valueHint:`number`},{flag:`-t`,type:`value`,valueHint:`string`},{flag:`-a`,type:`boolean`},{flag:`-e`,type:`value`,valueHint:`string`}],stdinType:`text`,needsFiles:!0}}),NY={};wz(NY,{flagsForFuzzing:()=>HY,split:()=>VY});function iwe(e){return Uint8Array.from(e,e=>e.charCodeAt(0))}function PY(e){let t=e.match(/^(\d+)([KMGTPEZY]?)([B]?)$/i);if(!t)return null;let n=Number(t[1]);if(!Number.isSafeInteger(n)||n<1)return null;let r=(t[2]||``).toUpperCase(),i=new Map([[``,1],[`K`,1024],[`M`,1048576],[`G`,1073741824],[`T`,1099511627776],[`P`,0x4000000000000]]).get(r);return i===void 0||n>Math.floor((2**53-1)/i)?null:n*i}function FY(e){if(!/^[0-9]+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)&&t>=1?t:null}function awe(e,t,n){if(t)return e.toString().padStart(n,`0`);let r=Array(n),i=e;for(let e=n-1;e>=0;e--)r[e]=`abcdefghijklmnopqrstuvwxyz`[i%26],i=Math.floor(i/26);return r.join(``)}function owe(e,t){let n=[],r=0,i=0;for(let a=0;a{kB(),rV(),DH(),U(),sV(),RY={name:`split`,summary:`split a file into pieces`,usage:`split [OPTION]... [FILE [PREFIX]]`,description:`Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'.`,options:[`-l N Put N lines per output file`,`-b SIZE Put SIZE bytes per output file (K, M, G suffixes)`,`-n CHUNKS Split into CHUNKS equal-sized files`,`-d Use numeric suffixes (00, 01, ...) instead of alphabetic`,`-a LENGTH Use suffixes of length LENGTH (default: 2)`,`--additional-suffix=SUFFIX Append SUFFIX to file names`],examples:[`split -l 100 file.txt # Split into 100-line chunks`,`split -b 1M file.bin # Split into 1MB chunks`,`split -n 5 file.txt # Split into 5 equal parts`,`split -d file.txt part_ # part_00, part_01, ...`,`split -a 3 -d file.txt x # x000, x001, ...`]},zY=1e5,BY=0,VY={name:`split`,execute:async(e,t)=>{if(aV(e))return iV(RY);let n={mode:`lines`,lines:1e3,bytes:0,chunks:0,useNumericSuffix:!1,suffixLength:2,additionalSuffix:``},r=[],i=0;for(;iMath.min(t.limits.maxStringLength,t.limits.maxArrayElements))return{exitCode:1,stdout:``,stderr:`split: invalid suffix length: '${e[i+1]}' +`};n.suffixLength=r,i+=2}else if(a.match(/^-a\d+$/)){let e=FY(a.slice(2));if(e===null||e>Math.min(t.limits.maxStringLength,t.limits.maxArrayElements))return{exitCode:1,stdout:``,stderr:`split: invalid suffix length: '${a.slice(2)}' +`};n.suffixLength=e,i++}else if(a===`-d`||a===`--numeric-suffixes`)n.useNumericSuffix=!0,i++;else if(a.startsWith(`--additional-suffix=`))n.additionalSuffix=a.slice(20),i++;else if(a===`--additional-suffix`&&i+1=1&&(a=r[0]),r.length>=2&&(o=r[1]),r.length>2)return{exitCode:1,stdout:``,stderr:`split: extra operand '${r[2]}' +`};if(V(o)>t.limits.maxStringLength||V(n.additionalSuffix)>t.limits.maxStringLength||n.suffixLength>t.limits.maxStringLength-Math.min(t.limits.maxStringLength,V(o))-Math.min(t.limits.maxStringLength,V(n.additionalSuffix)))return{exitCode:1,stdout:``,stderr:`split: output filename exceeds configured string limit +`};let s,c=null,l;if(a===`-`){let e=t.stdin.length;l=t.executionScope?.reserveBytes(`split transaction`,e*2,`split`),s=iwe(t.stdin)}else{c=t.fs.resolvePath(t.cwd,a);try{let e=await t.fs.stat(c);if(l=t.executionScope?.reserveBytes(`split transaction`,e.size*2,`split`),s=await t.fs.readFileBuffer(c),s.byteLength>e.size)throw new H(`split: input grew while being read`,`string_length`);t.executionScope?.consumeInput(s.byteLength,`split`)}catch(e){return l?.release(),nV(e),{exitCode:1,stdout:``,stderr:`split: ${a}: No such file or directory +`}}}try{if(s.length===0)return{exitCode:0,stdout:``,stderr:``};if(n.mode===`chunks`&&n.chunks>zY)return{exitCode:1,stdout:``,stderr:`split: too many output files (${n.chunks}), limit is ${zY} +`};let e;switch(n.mode){case`lines`:e=owe(s,n.lines);break;case`bytes`:e=swe(s,n.bytes);break;case`chunks`:e=cwe(s,n.chunks);break;default:return n.mode}if(e.length>zY)return{exitCode:1,stdout:``,stderr:`split: too many output files (${e.length}), limit is ${zY} +`};let r=lwe(n.useNumericSuffix,n.suffixLength);if(e.length>r)return{exitCode:1,stdout:``,stderr:`split: output file suffixes exhausted at ${r} files +`};t.executionScope?.consumeWork(e.length*n.suffixLength,`split suffix generation`);let i=[],a=new Set,l=c?await xH(t.fs,c):null;if(l?.existence===`unknown`)return{exitCode:1,stdout:``,stderr:`split: cannot safely identify input file +`};for(let r=0;r{}),void 0)}catch{for(let e of[...i].reverse())e.committed&&await t.fs.rm(e.path,{force:!0,recursive:!0}).catch(()=>{}),e.backupPath&&await t.fs.mv(e.backupPath,e.path).catch(()=>{}),e.stagePath&&await t.fs.rm(e.stagePath,{force:!0,recursive:!0}).catch(()=>{});return{exitCode:1,stdout:``,stderr:`split: failed to write output +`}}return{exitCode:0,stdout:``,stderr:``}}finally{l?.release()}}},HY={name:`split`,flags:[{flag:`-l`,type:`value`,valueHint:`number`},{flag:`-b`,type:`value`,valueHint:`string`},{flag:`-n`,type:`value`,valueHint:`number`},{flag:`-d`,type:`boolean`},{flag:`-a`,type:`value`,valueHint:`number`}],needsFiles:!0}}),UY={};wz(UY,{column:()=>qY,flagsForFuzzing:()=>JY});function WY(e,t,n,r){return t?n?e.split(t,r):e.split(t,r).filter(e=>e.length>0):n?e.split(/[ \t]/,r):e.split(/[ \t]+/,r).filter(e=>e.length>0)}function fwe(e){let t=[];for(let n of e)for(let e=0;et[e])&&(t[e]=r)}return t}function pwe(e,t,n){if(e.length===0)return``;let r=fwe(e),i=new oH(n,`column`,void 0,1);for(let n=0;n0&&i.append(` +`);for(let e=0;e0&&i.append(t),i.append(a[e]),e0&&l.append(` +`);let r=!1;for(let a=0;a=e.length?(r&&l.append(n),l.append(e[o])):(r&&l.append(n),l.append(e[o]),l.repeat(` `,i-e[o].length)),r=!0)}}return l.build()}var GY,KY,qY,JY,hwe=B(()=>{sH(),kB(),U(),lV(),sV(),GY={name:`column`,summary:`columnate lists`,usage:`column [OPTION]... [FILE]...`,description:`Format input into multiple columns. By default, fills rows first. Use -t to create a table based on whitespace-delimited input.`,options:[`-t Create a table (determine columns from input)`,`-s SEP Input field delimiter (default: whitespace)`,`-o SEP Output field delimiter (default: two spaces)`,`-c WIDTH Output width for fill mode (default: 80)`,`-n Don't merge multiple adjacent delimiters`],examples:[`ls | column # Fill columns with ls output`,`cat data | column -t # Format as table`,`column -t -s ',' file # Format CSV as table`,`column -c 40 file # Fill 40-char wide columns`]},KY={table:{short:`t`,long:`table`,type:`boolean`},separator:{short:`s`,type:`string`},outputSep:{short:`o`,type:`string`},width:{short:`c`,type:`number`,default:80},noMerge:{short:`n`,type:`boolean`}},qY={name:`column`,execute:async(e,t)=>{if(aV(e))return iV(GY);let n=cV(`column`,e,KY);if(!n.ok)return n.error;let{table:r,separator:i,outputSep:a,width:o,noMerge:s}=n.result.flags,c=n.result.positional,l=a??` `,u=Math.min(t.limits.maxInputBytes,t.limits.maxStringLength),d=t.limits.maxArrayElements,f=Math.min(t.limits.maxStringLength,t.limits.maxOutputSize);if(!Number.isFinite(o)||!Number.isSafeInteger(o)||o<=0||o>10485760)return{exitCode:1,stdout:``,stderr:`column: invalid width: ${o} +`};let p;if(c.length===0)p=vB(t.stdin)??``;else{let e=[],n=0;for(let r of c)if(r===`-`){let r=vB(t.stdin)??``;if(n+=V(r),n>u)throw new H(`column: input size limit exceeded (${u} bytes)`,`string_length`);e.push(r)}else{let i=t.fs.resolvePath(t.cwd,r),a=await t.fs.readFile(i);if(a===null)return{exitCode:1,stdout:``,stderr:`column: ${r}: No such file or directory +`};if(n+=V(a),n>u)throw new H(`column: input size limit exceeded (${u} bytes)`,`string_length`);e.push(a)}p=e.join(``)}if(V(p)>u)throw new H(`column: input size limit exceeded (${u} bytes)`,`string_length`);if(p===``||p.trim()===``)return{exitCode:0,stdout:``,stderr:``};let m=p.split(` +`,d+1);if(m.length>d)throw new H(`column: field limit exceeded (${d})`,`array_elements`);p.endsWith(` +`)&&m[m.length-1]===``&&m.pop();let h=m.filter(e=>e.trim().length>0),g;if(r){let e=[],t=0;for(let n of h){let r=WY(n,i,s,d-t+1);if(t+=r.length,t>d)throw new H(`column: field limit exceeded (${d})`,`array_elements`);e.push(r)}g=pwe(e,l,f)}else{let e=[];for(let t of h){let n=d-e.length,r=WY(t,i,s,n+1);if(r.length>n)throw new H(`column: field limit exceeded (${d})`,`array_elements`);for(let t of r)e.push(t)}g=mwe(e,o,l,f)}return g.length>0&&(g+=` +`),{exitCode:0,stdout:g,stderr:``}}},JY={name:`column`,flags:[{flag:`-t`,type:`boolean`},{flag:`-s`,type:`value`,valueHint:`delimiter`},{flag:`-o`,type:`value`,valueHint:`string`},{flag:`-c`,type:`value`,valueHint:`number`},{flag:`-n`,type:`boolean`}],stdinType:`text`,needsFiles:!0}}),YY={};wz(YY,{flagsForFuzzing:()=>$Y,join:()=>QY});function gwe(e,t){return t?e.split(t):e.split(/[ \t]+/).filter(e=>e.length>0)}function _we(e,t,n,r){let i=gwe(e,t),a=i[n-1]??``;return r&&(a=a.toLowerCase()),{fields:i,joinKey:a,original:e}}function XY(e,t,n){let r=n.separator??` `;if(n.outputFormat){let i=[];for(let{file:r,field:a}of n.outputFormat){let o=r===1?e:t;o&&a===0?i.push(o.joinKey):o&&o.fields[a-1]!==void 0?i.push(o.fields[a-1]):i.push(n.emptyString)}return i.join(r)}let i=[],a=e?.joinKey??t?.joinKey??``;if(i.push(a),e)for(let t=0;t{kB(),U(),sV(),XB(),ZY={name:`join`,summary:`join lines of two files on a common field`,usage:`join [OPTION]... FILE1 FILE2`,description:`For each pair of input lines with identical join fields, write a line to standard output. The default join field is the first, delimited by blanks.`,options:[`-1 FIELD Join on this FIELD of file 1 (default: 1)`,`-2 FIELD Join on this FIELD of file 2 (default: 1)`,`-t CHAR Use CHAR as input and output field separator`,`-a FILENUM Also print unpairable lines from file FILENUM (1 or 2)`,`-v FILENUM Like -a but only output unpairable lines`,`-e STRING Replace missing fields with STRING`,`-o FORMAT Output format (comma-separated list of FILENUM.FIELD)`,`-i Ignore case when comparing fields`],examples:[`join file1 file2 # Join on first field`,`join -1 2 -2 1 file1 file2 # Join file1 col 2 with file2 col 1`,`join -t ',' file1.csv file2.csv # Join CSV files`,`join -a 1 file1 file2 # Left outer join`]},QY={name:`join`,execute:async(e,t)=>{if(aV(e))return iV(ZY);let n={field1:1,field2:1,separator:null,printUnpairable:new Set,onlyUnpairable:new Set,emptyString:``,outputFormat:null,ignoreCase:!1},r=[],i=0;for(;i2)n.separator=t.slice(2),i++;else if(t===`-a`&&i+1e+V(t),0)>c)throw new H(`join: aggregate input size limit exceeded (${c} bytes)`,`string_length`);let u=0,d=0,f=()=>{if(++d>s)throw new H(`join: iteration limit exceeded (${s})`,`iterations`)},p=(e,t)=>{let r=+(e.length>0);for(let t=0;to-u)throw new H(`join: array element limit exceeded (${o})`,`array_elements`);u+=r;let i=e.split(` +`);return e.endsWith(` +`)&&i[i.length-1]===``&&i.pop(),i.filter(e=>e.length>0).map(e=>_we(e,n.separator,t,n.ignoreCase))},m=p(a[0],n.field1),h=p(a[1],n.field2),g=new Map;for(let e of h){let t=g.get(e.joinKey);t?t.push(e):g.set(e.joinKey,[e])}let _=[],v=0,y=e=>{if(f(),_.length>=o)throw new H(`join: array element limit exceeded (${o})`,`array_elements`);let t=V(e)+1;if(t>l-v)throw new H(`join: output size limit exceeded (${l} bytes)`,`output_size`);_.push(e),v+=t},b=new Set;for(let e of m){let t=g.get(e.joinKey);if(t&&t.length>0){if(b.add(e.joinKey),n.onlyUnpairable.size===0)for(let r of t)y(XY(e,r,n))}else(n.printUnpairable.has(1)||n.onlyUnpairable.has(1))&&y(XY(e,null,n))}if(n.printUnpairable.has(2)||n.onlyUnpairable.has(2))for(let e of h)b.has(e.joinKey)||y(XY(null,e,n));return{exitCode:0,stdout:yB(_.length>0?`${_.join(` +`)} +`:``),stderr:``,stdoutEncoding:`binary`}}},$Y={name:`join`,flags:[{flag:`-1`,type:`value`,valueHint:`number`},{flag:`-2`,type:`value`,valueHint:`number`},{flag:`-t`,type:`value`,valueHint:`delimiter`},{flag:`-a`,type:`value`,valueHint:`number`},{flag:`-v`,type:`value`,valueHint:`number`},{flag:`-e`,type:`value`,valueHint:`string`},{flag:`-o`,type:`value`,valueHint:`format`},{flag:`-i`,type:`boolean`}],needsArgs:!0,minArgs:2}}),eX={};wz(eX,{flagsForFuzzing:()=>iX,teeCommand:()=>rX});var tX,nX,rX,iX,bwe=B(()=>{kB(),lV(),sV(),tX={name:`tee`,summary:`read from stdin and write to stdout and files`,usage:`tee [OPTION]... [FILE]...`,options:[`-a, --append append to the given FILEs, do not overwrite`,` --help display this help and exit`]},nX={append:{short:`a`,long:`append`,type:`boolean`}},rX={name:`tee`,async execute(e,t){if(aV(e))return iV(tX);let n=cV(`tee`,e,nX);if(!n.ok)return n.error;let{append:r}=n.result.flags,i=n.result.positional,a=t.stdin,o=``,s=0;for(let e of i)try{let n=t.fs.resolvePath(t.cwd,e);r?await t.fs.appendFile(n,a,`binary`):await t.fs.writeFile(n,a,`binary`)}catch{o+=`tee: ${e}: No such file or directory +`,s=1}return{stdout:a,stderr:o,exitCode:s,stdoutEncoding:`binary`}}},iX={name:`tee`,flags:[{flag:`-a`,type:`boolean`}],stdinType:`text`,needsArgs:!0}}),aX,oX=B(()=>{kB(),U(),aX=class{scope;site;stdoutChunks=[];stderrChunks=[];stdoutBytes=0;stderrBytes=0;attachedErrors=new WeakSet;constructor(e,t){this.scope=e,this.site=t}append(e,t,n=0,r=`text`){let i;try{i=this.scope.appendOutput(e,t,this.site,n,r)}catch(e){throw this.prependTo(e),e}t&&(e===`stdout`?this.stdoutChunks:this.stderrChunks).push(t),e===`stdout`?this.stdoutBytes+=i:this.stderrBytes+=i}prependTo(e){e instanceof jB&&(this.attachedErrors.has(e)||(this.attachedErrors.add(e),e.prependOutput(this.stdout,this.stderr)))}appendResult(e,t=e.stdout){let n=e.stdoutKind===`bytes`||e.stdoutEncoding===`binary`?`bytes`:`text`,r=n===`bytes`?t.length:V(t);this.append(`stdout`,t,Math.min(e.internalOutputAccounting?.stdout??0,r),n),this.append(`stderr`,e.stderr,e.internalOutputAccounting?.stderr??0)}build(e,t){return{stdout:this.stdoutChunks.join(``),stderr:this.stderrChunks.join(``),exitCode:e,...t,internalOutputAccounting:{stdout:this.stdoutBytes,stderr:this.stderrBytes}}}get stdout(){return this.stdoutChunks.join(``)}get stderr(){return this.stderrChunks.join(``)}}});function sX(e,t){switch(e.type){case`name`:{let n=e.pattern,r=n.match(/^\*(\.[a-zA-Z0-9]+)$/);if(r){let n=r[1],i=t.name;if(e.ignoreCase){if(!i.toLowerCase().endsWith(n.toLowerCase()))return{matches:!1,pruned:!1,printed:!1}}else if(!i.endsWith(n))return{matches:!1,pruned:!1,printed:!1};return{matches:!0,pruned:!1,printed:!1}}return{matches:bG(t.name,n,e.ignoreCase),pruned:!1,printed:!1}}case`path`:{let n=e.pattern,r=t.relativePath,i=n.split(`/`);for(let t=0;te.days:e.comparison===`less`?nn,pruned:!1,printed:!1}}case`size`:{let n=e.value;switch(e.unit){case`c`:n=e.value;break;case`k`:n=e.value*1024;break;case`M`:n=e.value*1024*1024;break;case`G`:n=e.value*1024*1024*1024;break;case`b`:n=e.value*512}let r;return r=e.comparison===`more`?t.size>n:e.comparison===`less`?t.size{e&&(e.type===`newer`?t.push(e.refPath):e.type===`not`?n(e.expr):(e.type===`and`||e.type===`or`)&&(n(e.left),n(e.right)))};return n(e),t}function uX(e){if(!e)return!0;switch(e.type){case`name`:case`path`:case`regex`:case`type`:case`prune`:return!0;case`action`:return!1;case`empty`:case`mtime`:case`newer`:case`size`:case`perm`:return!1;case`not`:return uX(e.expr);case`and`:case`or`:return uX(e.left)&&uX(e.right)}}function dX(e,t,n,r,i){switch(e.type){case`name`:{let n=e.pattern,r=n.match(/^\*(\.[a-zA-Z0-9]+)$/);if(r){let n=r[1];if(e.ignoreCase){if(!t.toLowerCase().endsWith(n.toLowerCase()))return{matches:!1,pruned:!1,printed:!1}}else if(!t.endsWith(n))return{matches:!1,pruned:!1,printed:!1};return{matches:!0,pruned:!1,printed:!1}}return{matches:bG(t,n,e.ignoreCase),pruned:!1,printed:!1}}case`path`:{let t=e.pattern,r=t.split(`/`);for(let t=0;t{yG(),CG()});function wwe(e,t){let n=[],r=t,i=e=>({expr:null,pathIndex:r,error:`find: missing argument to \`${e}' +`}),a=(e,t)=>({expr:null,pathIndex:r,error:`find: invalid argument \`${t}' to \`${e}' +`});for(;r=e.length)return i(t);n.push({type:`expr`,expr:{type:`name`,pattern:e[++r]}})}else if(t===`-iname`){if(r+1>=e.length)return i(t);n.push({type:`expr`,expr:{type:`name`,pattern:e[++r],ignoreCase:!0}})}else if(t===`-path`){if(r+1>=e.length)return i(t);n.push({type:`expr`,expr:{type:`path`,pattern:e[++r]}})}else if(t===`-ipath`){if(r+1>=e.length)return i(t);n.push({type:`expr`,expr:{type:`path`,pattern:e[++r],ignoreCase:!0}})}else if(t===`-regex`){if(r+1>=e.length)return i(t);n.push({type:`expr`,expr:{type:`regex`,pattern:e[++r]}})}else if(t===`-iregex`){if(r+1>=e.length)return i(t);n.push({type:`expr`,expr:{type:`regex`,pattern:e[++r],ignoreCase:!0}})}else if(t===`-type`){if(r+1>=e.length)return i(t);let a=e[++r];if(a===`f`||a===`d`)n.push({type:`expr`,expr:{type:`type`,fileType:a}});else return{expr:null,pathIndex:r,error:`find: Unknown argument to -type: ${a} +`}}else if(t===`-empty`)n.push({type:`expr`,expr:{type:`empty`}});else if(t===`-mtime`){if(r+1>=e.length)return i(t);let o=e[++r],s=`exact`,c=o;if(o.startsWith(`+`)?(s=`more`,c=o.slice(1)):o.startsWith(`-`)&&(s=`less`,c=o.slice(1)),!/^\d+$/.test(c))return a(t,o);let l=Number(c);if(!Number.isSafeInteger(l))return a(t,o);n.push({type:`expr`,expr:{type:`mtime`,days:l,comparison:s}})}else if(t===`-newer`){if(r+1>=e.length)return i(t);let a=e[++r];n.push({type:`expr`,expr:{type:`newer`,refPath:a}})}else if(t===`-size`){if(r+1>=e.length)return i(t);let o=e[++r],s=`exact`,c=o;o.startsWith(`+`)?(s=`more`,c=o.slice(1)):o.startsWith(`-`)&&(s=`less`,c=o.slice(1));let l=c.match(/^(\d+)([ckMGb])?$/);if(!l)return a(t,o);let u=Number(l[1]);if(!Number.isSafeInteger(u))return a(t,o);let d=l[2]||`b`,f=d===`G`?1024**3:d===`M`?1024**2:d===`k`?1024:d===`b`?512:1;if(!Number.isSafeInteger(u*f))return a(t,o);n.push({type:`expr`,expr:{type:`size`,value:u,unit:d,comparison:s}})}else if(t===`-perm`){if(r+1>=e.length)return i(t);let o=e[++r],s=`exact`,c=o;if(o.startsWith(`-`)?(s=`all`,c=o.slice(1)):o.startsWith(`/`)&&(s=`any`,c=o.slice(1)),!/^[0-7]{1,4}$/.test(c))return a(t,o);let l=Number.parseInt(c,8);n.push({type:`expr`,expr:{type:`perm`,mode:l,matchType:s}})}else if(t===`-prune`)n.push({type:`expr`,expr:{type:`prune`}});else if(t===`-not`||t===`!`)n.push({type:`not`});else if(t===`-o`||t===`-or`)n.push({type:`op`,op:`or`});else if(t===`-a`||t===`-and`)n.push({type:`op`,op:`and`});else if(t===`-maxdepth`||t===`-mindepth`){if(r+1>=e.length)return i(t);r++}else if(t!==`-depth`){if(t===`-exec`){let t=[];for(r++;r=e.length)return{expr:null,pathIndex:r,error:`find: missing argument to \`-exec' +`};if(t.length===0)return i(`-exec`);let o=e[r]===`+`;if(o&&(t.at(-1)!==`{}`||t.filter(e=>e===`{}`).length!==1))return a(`-exec`,`+`);n.push({type:`expr`,expr:{type:`action`,action:{type:`exec`,command:t,batchMode:o}}})}else if(t===`-print`)n.push({type:`expr`,expr:{type:`action`,action:{type:`print`}}});else if(t===`-print0`)n.push({type:`expr`,expr:{type:`action`,action:{type:`print0`}}});else if(t===`-printf`){if(r+1>=e.length)return i(t);let a=e[++r];n.push({type:`expr`,expr:{type:`action`,action:{type:`printf`,format:a}}})}else if(t===`-delete`)n.push({type:`expr`,expr:{type:`action`,action:{type:`delete`}}});else return t.startsWith(`-`)?{expr:null,pathIndex:r,error:`find: unknown predicate '${t}' +`}:{expr:null,pathIndex:r,error:`find: paths must precede expression: \`${t}' +`}}r++}if(n.length===0)return{expr:null,pathIndex:r};let o=Twe(n);return o.error?{expr:null,pathIndex:r,error:o.error}:{expr:o.expr,pathIndex:r}}function Twe(e){let t=0,n;function r(){let r=i();if(!r)return null;for(;t=e.length)return null;let i=e[t];if(i.type===`lparen`){t++;let i=r();return!i||t>=e.length||e[t].type!==`rparen`?(n=`find: missing closing \`)' +`,null):(t++,i)}return i.type===`expr`?(t++,i.expr):(i.type,null)}let s=r();return!n&&t{}),gX={};wz(gX,{findCommand:()=>bX,flagsForFuzzing:()=>xX});function Dwe(){return{readdirCalls:0,readdirTime:0,statCalls:0,statTime:0,evalCalls:0,evalTime:0,nodeCount:0,batchCount:0,batchTime:0,earlyPrunes:0}}function Owe(e,t,n){e({category:`find`,name:`summary`,durationMs:n,details:{readdirCalls:t.readdirCalls,readdirTimeMs:t.readdirTime,statCalls:t.statCalls,statTimeMs:t.statTime,evalCalls:t.evalCalls,evalTimeMs:t.evalTime,nodeCount:t.nodeCount,batchCount:t.batchCount,batchTimeMs:t.batchTime,earlyPrunes:t.earlyPrunes,otherTimeMs:n-t.readdirTime-t.statTime-t.evalTime-t.batchTime}})}function _X(e){return e?e.type===`action`?[e.action]:e.type===`not`?_X(e.expr):e.type===`and`||e.type===`or`?[..._X(e.left),..._X(e.right)]:[]:[]}function kwe(e,t){let n=JB(e),r=``,i=0;for(;i=n.length){r+=`%`;break}let s=n[i],c;switch(s){case`f`:c=t.name,i++;break;case`h`:{let e=t.path.lastIndexOf(`/`);c=e>0?t.path.slice(0,e):`.`,i++;break}case`p`:c=t.path,i++;break;case`P`:{let e=t.startingPoint;c=t.path===e?``:t.path.startsWith(`${e}/`)?t.path.slice(e.length+1):e===`.`&&t.path.startsWith(`./`)?t.path.slice(2):t.path,i++;break}case`s`:c=String(t.size),i++;break;case`d`:c=String(t.depth),i++;break;case`m`:c=(t.mode&511).toString(8),i++;break;case`M`:c=rW(t.mode,t.isDirectory),i++;break;case`t`:c=Awe(new Date(t.mtime)),i++;break;case`T`:if(i+1{kB(),oX(),DH(),mK(),U(),iW(),sV(),XB(),Cwe(),Ewe(),vX=500,yX={name:`find`,summary:`search for files in a directory hierarchy`,usage:`find [path...] [expression]`,options:`-name PATTERN file name matches shell pattern PATTERN.-iname PATTERN like -name but case insensitive.-path PATTERN file path matches shell pattern PATTERN.-ipath PATTERN like -path but case insensitive.-regex PATTERN file path matches regular expression PATTERN.-iregex PATTERN like -regex but case insensitive.-type TYPE file is of type: f (regular file), d (directory).-empty file is empty or directory is empty.-mtime N file's data was modified N*24 hours ago.-newer FILE file was modified more recently than FILE.-size N[ckMGb] file uses N units of space (c=bytes, k=KB, M=MB, G=GB, b=512B blocks).-perm MODE file's permission bits are exactly MODE (octal).-perm -MODE all permission bits MODE are set.-perm /MODE any permission bits MODE are set.-maxdepth LEVELS descend at most LEVELS directories.-mindepth LEVELS do not apply tests at levels less than LEVELS.-depth process directory contents before directory itself.-prune do not descend into this directory.-not, ! negate the following expression.-a, -and logical AND (default).-o, -or logical OR.-exec CMD {} ; execute CMD on each file ({} is replaced by filename).-exec CMD {} + execute CMD with multiple files at once.-print print the full file name (default action).-print0 print the full file name followed by a null character.-printf FORMAT print FORMAT with directives: %f %h %p %P %s %d %m %M %t.-delete delete found files/directories. --help display this help and exit`.split(`.`)},bX={name:`find`,async execute(e,t){if(aV(e))return iV(yX);let n=[],r=null,i=null,a=!1,o=e.length;for(let t=0;t0;l.some(e=>e.type===`delete`)&&(a=!0);let d=[],f=0,p=t.executionScope?new aX(t.executionScope,`find`):void 0,m=[],h=[],g=0,_=new EH({limits:t.limits,signal:t.signal,executionScope:t.executionScope,site:`find`}),v=e=>{if(p)p.append(`stdout`,e);else{let n=V(e);if(n>t.limits.maxOutputSize-g)throw new H(`find: output size limit exceeded (${t.limits.maxOutputSize} bytes)`,`output_size`);e&&m.push(e),g+=n}},y=e=>{if(p)p.append(`stderr`,e);else{let n=V(e);if(n>t.limits.maxOutputSize-g)throw new H(`find: output size limit exceeded (${t.limits.maxOutputSize} bytes)`,`output_size`);e&&h.push(e),g+=n}},b=xwe(s),x=new Map;for(let e of b){let n=t.fs.resolvePath(t.cwd,e);try{let r=await t.fs.stat(n);x.set(e,r.mtime?.getTime()??Date.now())}catch{}}let S=l.some(e=>{if(e.type!==`printf`)return!1;let t=e.format.replace(/%%/g,``);return/%[-+]?[0-9]*\.?[0-9]*(s|m|M|t|T)/.test(t)}),C=cX(s)||S,w=lX(s),T=fX(s),E=uX(s),D=typeof t.fs.readdirWithFileTypes==`function`;for(let e of n){let n=function(t){if(!(i===null||t.depth>=i))return[];let n=!0,r=[];if(s!==null){let e=Date.now(),i;if(E)i=dX(s,t.name,t.relativePath,t.isFile,t.isDirectory);else{let e={name:t.name,relativePath:t.relativePath,isFile:t.isFile,isDirectory:t.isDirectory,isEmpty:t.isEmpty,mtime:t.stat?.mtime?.getTime()??Date.now(),size:t.stat?.size??0,mode:t.stat?.mode??420,newerRefTimes:x};i=sX(s,e)}n=i.matches,r=i.actions??[],c.evalCalls++,c.evalTime+=Date.now()-e}if(!u&&n&&(r=[{type:`print`}]),r.length===0)return[];let a={path:t.relativePath,name:t.name,size:t.stat?.size??0,mtime:t.stat?.mtime?.getTime()??Date.now(),mode:t.stat?.mode??420,isDirectory:t.isDirectory,depth:t.depth,startingPoint:e};_.checkpoint(r.length);let o=[];for(let e of r)o.push({action:e,path:t.relativePath,printfData:a});return o};e.length>1&&e.endsWith(`/`)&&(e=e.slice(0,-1));let o=t.fs.resolvePath(t.cwd,e);try{await t.fs.stat(o)}catch{y(`find: ${e}: No such file or directory +`),f=1;continue}let c=Dwe(),l=Date.now();async function p(n){let{path:i,depth:l,typeInfo:u}=n;if(_.visit(l),c.nodeCount++,l>(r??t.limits.maxTraversalDepth))return null;let d,f,p;if(u&&!C)d=u.isFile,f=u.isDirectory;else{try{let e=Date.now();p=await t.fs.lstat(i),c.statCalls++,c.statTime+=Date.now()-e}catch{return null}if(!p)return null;d=p.isFile,f=p.isDirectory}let m;m=i===o?e.split(`/`).pop()||e:i.split(`/`).pop()||``;let h=i===o?e:e===`.`?`./${i.slice(o===`/`?o.length:o.length+1)}`:e+i.slice(o.length),g=[],v=null,y=null,b=!1;f&&T&&!a&&(b=Swe(s,{name:m,relativePath:h,isFile:d,isDirectory:f}).shouldPrune,b&&c.earlyPrunes++);let S=!(l>=(r??t.limits.maxTraversalDepth))&&!b;if(f&&(S||w)&&!b){let e=Date.now();if(D&&t.fs.readdirWithFileTypes){v=await t.fs.readdirWithFileTypes(i),_.checkpoint(),_.discover(v.length),y=[];for(let e of v)y.push(e.name);if(c.readdirCalls++,c.readdirTime+=Date.now()-e,S)for(let e=0;ep(e.item)));c.batchCount++,c.batchTime+=Date.now()-e;for(let e=0;e=0){let e=i.get(a.parentIndex)||[];e.push(c),i.set(a.parentIndex,e)}t.push({node:n,parentIndex:a.parentIndex,childIndices:[]});for(let e=0;e=0&&e0){let r=[{index:0,visited:!1}];for(;r.length>0;){_.checkpoint();let i=r.pop();if(!i)break;let a=t[i.index];if(a){if(i.visited){for(let t of n(a.node))e.effects.push(t);continue}r.push({index:i.index,visited:!0});for(let e=a.childIndices.length-1;e>=0;e--)r.push({index:a.childIndices[e],visited:!1})}}}}else{let t=new Map,r=0,i=[{item:{path:o,depth:0,resultIndex:0},orderIndex:r++}],a=new Map,s=0;for(;s{let n=await p(e);return n?{node:n,orderIndex:t}:null}));c.batchCount++,c.batchTime+=Date.now()-e;for(let e of u){if(!e)continue;let{node:o,orderIndex:s}=e,c=n(o);if(c.length>0&&t.set(s,c),o.children.length>0){let e=[];for(let t of o.children){let n=r++;e.push(n),i.push({item:t,orderIndex:n})}a.set(s,e)}}}let l=[0];for(;l.length>0;){_.checkpoint();let n=l.pop();if(n===void 0)break;let r=t.get(n);if(r)for(let t of r)e.effects.push(t);let i=a.get(n);if(i)for(let e=i.length-1;e>=0;e--)l.push(i[e])}}return e}let h=await m();for(let e of h.effects)d.push(e);if(t.trace){let n=Date.now()-l;Owe(t.trace,c,n),t.trace({category:`find`,name:`searchPath`,durationMs:n,details:{path:e,resultsFound:h.effects.length}})}}let O=new Map;for(let e of d){let{action:n,path:r}=e;switch(n.type){case`print`:v(`${r} +`);break;case`print0`:v(`${r}\0`);break;case`printf`:v(kwe(n.format,e.printfData));break;case`delete`:{let e=t.fs.resolvePath(t.cwd,r);try{await t.fs.rm(e,{recursive:!1})}catch(e){y(`find: cannot delete '${r}': ${e instanceof Error?e.message:String(e)} +`),f=1}break}case`exec`:{if(!t.exec)return{stdout:``,stderr:`find: -exec not supported in this context +`,exitCode:1};if(n.batchMode){let e=O.get(n)??[];e.push(r),O.set(n,e);break}let e=n.command.map(e=>e===`{}`?r:e),i=await t.exec(pK([e[0]]),{cwd:t.cwd,signal:t.signal,args:e.slice(1)});p?p.appendResult(i):(v(i.stdout),y(i.stderr)),i.exitCode!==0&&(f=i.exitCode);break}}}for(let[e,n]of O){if(e.type!==`exec`||!t.exec||n.length===0)continue;let r=[];for(let t of e.command)t===`{}`?r.push(...n):r.push(t);let i=await t.exec(pK([r[0]]),{cwd:t.cwd,signal:t.signal,args:r.slice(1)});p?p.appendResult(i):(v(i.stdout),y(i.stderr)),i.exitCode!==0&&(f=i.exitCode)}return p?.build(f)??{stdout:m.join(``),stderr:h.join(``),exitCode:f}}},xX={name:`find`,flags:[{flag:`-name`,type:`value`,valueHint:`pattern`},{flag:`-iname`,type:`value`,valueHint:`pattern`},{flag:`-type`,type:`value`,valueHint:`string`},{flag:`-maxdepth`,type:`value`,valueHint:`number`},{flag:`-mindepth`,type:`value`,valueHint:`number`},{flag:`-empty`,type:`boolean`},{flag:`-print`,type:`boolean`},{flag:`-print0`,type:`boolean`}],needsFiles:!0}}),SX={};wz(SX,{basenameCommand:()=>wX,flagsForFuzzing:()=>TX});var CX,wX,TX,Nwe=B(()=>{sV(),CX={name:`basename`,summary:`strip directory and suffix from filenames`,usage:`basename NAME [SUFFIX] +basename OPTION... NAME...`,options:[`-a, --multiple support multiple arguments`,`-s, --suffix=SUFFIX remove a trailing SUFFIX`,` --help display this help and exit`]},wX={name:`basename`,async execute(e,t){if(aV(e))return iV(CX);let n=!1,r=``,i=[];for(let t=0;t=2&&(r=i.pop()??``);let a=[];for(let e of i){let t=e.replace(/\/+$/,``),n=t.split(`/`).pop()||t;r&&n.endsWith(r)&&(n=n.slice(0,-r.length)),a.push(n)}return{stdout:`${a.join(` +`)} +`,stderr:``,exitCode:0}}},TX={name:`basename`,flags:[{flag:`-a`,type:`boolean`},{flag:`-s`,type:`value`,valueHint:`string`}],needsArgs:!0}}),EX={};wz(EX,{dirnameCommand:()=>OX,flagsForFuzzing:()=>kX});var DX,OX,kX,Pwe=B(()=>{sV(),DX={name:`dirname`,summary:`strip last component from file name`,usage:`dirname [OPTION] NAME...`,options:[` --help display this help and exit`]},OX={name:`dirname`,async execute(e,t){if(aV(e))return iV(DX);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return{stdout:``,stderr:`dirname: missing operand +`,exitCode:1};let r=[];for(let e of n){let t=e.replace(/\/+$/,``),n=t.lastIndexOf(`/`);n===-1?r.push(`.`):n===0?r.push(`/`):r.push(t.slice(0,n))}return{stdout:`${r.join(` +`)} +`,stderr:``,exitCode:0}}},kX={name:`dirname`,flags:[],needsArgs:!0}}),AX={};wz(AX,{flagsForFuzzing:()=>FX,treeCommand:()=>PX});async function Fwe(e,t,n,r,i){let a={output:``,stderr:``,dirCount:0,fileCount:0},o=e.fs.resolvePath(e.cwd,t);try{if(!(await e.fs.stat(o)).isDirectory)return a.output=`${t} +`,a.fileCount=1,a}catch{return a.stderr=`tree: ${t}: No such file or directory +`,a}if(a.output=`${t} +`,n.maxDepth!==null&&i>=n.maxDepth)return a;try{let t=[];if(e.fs.readdirWithFileTypes)t=(await e.fs.readdirWithFileTypes(o)).map(e=>({name:e.name,isDirectory:e.isDirectory}));else{let n=await e.fs.readdir(o);for(let r=0;r{let n=o===`/`?`/${t}`:`${o}/${t}`;try{return{name:t,isDirectory:(await e.fs.stat(n)).isDirectory}}catch{return null}}));t.push(...a.filter(e=>e!==null))}}let s=t.filter(e=>!(!n.showHidden&&e.name.startsWith(`.`)||n.directoriesOnly&&!e.isDirectory));s.sort((e,t)=>e.name.localeCompare(t.name));for(let t=0;t=n.maxDepth)return a;try{let o=[];if(e.fs.readdirWithFileTypes)o=(await e.fs.readdirWithFileTypes(t)).map(e=>({name:e.name,isDirectory:e.isDirectory}));else{let n=await e.fs.readdir(t);for(let r=0;r{let r=t===`/`?`/${n}`:`${t}/${n}`;try{return{name:n,isDirectory:(await e.fs.stat(r)).isDirectory}}catch{return null}}));o.push(...a.filter(e=>e!==null))}}let s=o.filter(e=>!(!n.showHidden&&e.name.startsWith(`.`)||n.directoriesOnly&&!e.isDirectory));s.sort((e,t)=>e.name.localeCompare(t.name));for(let o=0;o{lV(),uV(),sV(),MX={name:`tree`,summary:`list contents of directories in a tree-like format`,usage:`tree [OPTION]... [DIRECTORY]...`,options:[`-a include hidden files`,`-d list directories only`,`-L LEVEL limit depth of directory tree`,`-f print full path prefix for each file`,` --help display this help and exit`]},NX={showHidden:{short:`a`,type:`boolean`},directoriesOnly:{short:`d`,type:`boolean`},fullPath:{short:`f`,type:`boolean`},maxDepth:{short:`L`,type:`number`}},PX={name:`tree`,async execute(e,t){if(aV(e))return iV(MX);let n=cV(`tree`,e,NX);if(!n.ok)return n.error;let r={showHidden:n.result.flags.showHidden,directoriesOnly:n.result.flags.directoriesOnly,maxDepth:n.result.flags.maxDepth??null,fullPath:n.result.flags.fullPath},i=n.result.positional;i.length===0&&i.push(`.`);let a=``,o=``,s=0,c=0;for(let e of i){let n=await Fwe(t,e,r,``,0);a+=n.output,o+=n.stderr,s+=n.dirCount,c+=n.fileCount}return a+=` +${s} director${s===1?`y`:`ies`}`,r.directoriesOnly||(a+=`, ${c} file${c===1?``:`s`}`),a+=` +`,{stdout:a,stderr:o,exitCode:+!!o}}},FX={name:`tree`,flags:[{flag:`-a`,type:`boolean`},{flag:`-d`,type:`boolean`},{flag:`-f`,type:`boolean`},{flag:`-L`,type:`value`,valueHint:`number`}],needsFiles:!0}}),IX={};wz(IX,{duCommand:()=>BX,flagsForFuzzing:()=>VX});async function Lwe(e,t,n,r,i){let a={output:``,totalSize:0,stderr:``},o=new Map;return await wH({fs:e.fs,root:t,limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:`du`,symlinks:`never`,includeLeave:!0},e=>{let s=e.path.slice(t.length).replace(/^\//,``),c=s?n===`.`?s:`${n}/${s}`:n,l=e.path===`/`?`/`:e.path.slice(0,e.path.lastIndexOf(`/`))||`/`;if(e.phase===`enter`){if(e.stat.isDirectory){o.set(e.path,0);return}o.set(l,(o.get(l)??0)+e.stat.size),(r.allFiles||e.depth===i)&&!r.summarize&&(a.output+=`${LX(e.stat.size,r.humanReadable)} ${c} +`),e.depth===i&&(a.totalSize=e.stat.size);return}let u=o.get(e.path)??0;e.depth>i?o.set(l,(o.get(l)??0)+u):a.totalSize=u;let d=e.depth-i;(r.summarize&&d===0||!r.summarize&&(r.maxDepth===null||d<=r.maxDepth))&&(a.output+=`${LX(u,r.humanReadable)} ${c} +`)}),a}function LX(e,t){return t?e<1024?`${e}`:e<1048576?`${(e/1024).toFixed(1)}K`:e<1073741824?`${(e/1048576).toFixed(1)}M`:`${(e/1073741824).toFixed(1)}G`:String(Math.ceil(e/1024)||1)}var RX,zX,BX,VX,Rwe=B(()=>{DH(),U(),lV(),sV(),RX={name:`du`,summary:`estimate file space usage`,usage:`du [OPTION]... [FILE]...`,options:[`-a write counts for all files, not just directories`,`-h print sizes in human readable format`,`-s display only a total for each argument`,`-c produce a grand total`,`--max-depth=N print total for directory only if N or fewer levels deep`,` --help display this help and exit`]},zX={allFiles:{short:`a`,type:`boolean`},humanReadable:{short:`h`,type:`boolean`},summarize:{short:`s`,type:`boolean`},grandTotal:{short:`c`,type:`boolean`},maxDepth:{long:`max-depth`,type:`number`}},BX={name:`du`,async execute(e,t){if(aV(e))return iV(RX);let n=cV(`du`,e,zX);if(!n.ok)return n.error;let r={allFiles:n.result.flags.allFiles,humanReadable:n.result.flags.humanReadable,summarize:n.result.flags.summarize,grandTotal:n.result.flags.grandTotal,maxDepth:n.result.flags.maxDepth??null},i=n.result.positional;i.length===0&&i.push(`.`);let a=``,o=``,s=0;for(let e of i){let n=t.fs.resolvePath(t.cwd,e);try{await t.fs.stat(n);let i=await Lwe(t,n,e,r,0);a+=i.output,s+=i.totalSize,o+=i.stderr}catch(t){if(t instanceof H||t instanceof HB)throw t;o+=`du: cannot access '${e}': No such file or directory +`}}return r.grandTotal&&i.length>0&&(a+=`${LX(s,r.humanReadable)} total +`),{stdout:a,stderr:o,exitCode:+!!o}}},VX={name:`du`,flags:[{flag:`-a`,type:`boolean`},{flag:`-h`,type:`boolean`},{flag:`-s`,type:`boolean`},{flag:`-c`,type:`boolean`},{flag:`--max-depth`,type:`value`,valueHint:`number`}],needsFiles:!0}}),HX={};wz(HX,{envCommand:()=>WX,flagsForFuzzing:()=>qX,printenvCommand:()=>KX,printenvFlagsForFuzzing:()=>JX});var UX,WX,GX,KX,qX,JX,YX=B(()=>{kB(),tq(),sV(),UX={name:`env`,summary:`run a program in a modified environment`,usage:`env [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]`,options:[`-i, --ignore-environment start with an empty environment`,`-u NAME, --unset=NAME remove NAME from the environment`,` --help display this help and exit`]},WX={name:`env`,async execute(e,t){if(aV(e))return iV(UX);let n=!1,r=[],i=new Map,a=-1;for(let t=0;t0?` +`:``),stderr:``,exitCode:0}}if(!t.exec)return{stdout:``,stderr:`env: command execution not supported in this context +`,exitCode:1};let s=e.slice(a);return t.exec(`command`,{cwd:t.cwd,env:QK(o),replaceEnv:!0,stdin:t.stdin,stdinKind:`bytes`,signal:t.signal,args:s})}},GX={name:`printenv`,summary:`print all or part of environment`,usage:`printenv [OPTION]... [VARIABLE]...`,options:[` --help display this help and exit`]},KX={name:`printenv`,async execute(e,t){if(aV(e))return iV(GX);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0){let e=[];for(let[n,r]of t.env)e.push(`${n}=${r}`);return{stdout:e.join(` +`)+(e.length>0?` +`:``),stderr:``,exitCode:0}}let r=[],i=0;for(let e of n){let n=t.env.get(e);n===void 0?i=1:r.push(n)}return{stdout:r.join(` +`)+(r.length>0?` +`:``),stderr:``,exitCode:i}}},qX={name:`env`,flags:[{flag:`-i`,type:`boolean`},{flag:`-u`,type:`value`,valueHint:`string`}]},JX={name:`printenv`,flags:[]}}),XX={};wz(XX,{aliasCommand:()=>$X,flagsForFuzzing:()=>tZ,unaliasCommand:()=>eZ,unaliasFlagsForFuzzing:()=>nZ});var ZX,QX,$X,eZ,tZ,nZ,rZ=B(()=>{sV(),ZX={name:`alias`,summary:`define or display aliases`,usage:`alias [name[=value] ...]`,options:[` --help display this help and exit`]},QX=`BASH_ALIAS_`,$X={name:`alias`,async execute(e,t){if(aV(e))return iV(ZX);if(e.length===0){let e=``;for(let[n,r]of t.env)if(n.startsWith(QX)){let t=n.slice(QX.length);e+=`alias ${t}='${r}' +`}return{stdout:e,stderr:``,exitCode:0}}let n=e[0]===`--`?e.slice(1):e;for(let e of n){let n=e.indexOf(`=`);if(n===-1){let n=QX+e;return t.env.get(n)?{stdout:`alias ${e}='${t.env.get(n)}' +`,stderr:``,exitCode:0}:{stdout:``,stderr:`alias: ${e}: not found +`,exitCode:1}}{let r=e.slice(0,n),i=e.slice(n+1);(i.startsWith(`'`)&&i.endsWith(`'`)||i.startsWith(`"`)&&i.endsWith(`"`))&&(i=i.slice(1,-1)),t.env.set(QX+r,i)}}return{stdout:``,stderr:``,exitCode:0}}},eZ={name:`unalias`,async execute(e,t){if(aV(e))return iV({name:`unalias`,summary:`remove alias definitions`,usage:`unalias name [name ...]`,options:[`-a remove all aliases`,` --help display this help and exit`]});if(e.length===0)return{stdout:``,stderr:`unalias: usage: unalias [-a] name [name ...] +`,exitCode:1};if(e[0]===`-a`){for(let e of t.env.keys())e.startsWith(QX)&&t.env.delete(e);return{stdout:``,stderr:``,exitCode:0}}let n=e[0]===`--`?e.slice(1):e,r=!1,i=``;for(let e of n){let n=QX+e;t.env.get(n)?t.env.delete(n):(i+=`unalias: ${e}: not found +`,r=!0)}return{stdout:``,stderr:i,exitCode:+!!r}}},tZ={name:`alias`,flags:[]},nZ={name:`unalias`,flags:[{flag:`-a`,type:`boolean`}]}}),iZ={};wz(iZ,{flagsForFuzzing:()=>cZ,historyCommand:()=>sZ});var aZ,oZ,sZ,cZ,zwe=B(()=>{sV(),aZ={name:`history`,summary:`display command history`,usage:`history [n]`,options:[`-c clear the history list`,` --help display this help and exit`]},oZ=`BASH_HISTORY`,sZ={name:`history`,async execute(e,t){if(aV(e))return iV(aZ);let n=t.env.get(oZ)||`[]`,r;try{r=JSON.parse(n)}catch{r=[]}if(e[0]===`-c`)return t.env.set(oZ,`[]`),{stdout:``,stderr:``,exitCode:0};let i=r.length;e[0]&&/^\d+$/.test(e[0])&&(i=Math.min(parseInt(e[0],10),r.length));let a=r.length-i,o=``;for(let e=a;epZ,xargsCommand:()=>fZ});function uZ(e,t,n){if(t.length===0)throw Error(`xargs: delimiter must not be empty`);let r=[],i=0;for(;i<=e.length;){let a=e.indexOf(t,i),o=e.slice(i,a===-1?e.length:a);if(o.length>0){if(r.length>=n)throw new H(`xargs: array element limit exceeded (${n})`,`array_elements`);r.push(o)}if(a===-1)break;i=a+t.length}return r}function Bwe(e,t){let n=[],r=-1;for(let i=0;i<=e.length;i++){let a=i===e.length||/\s/.test(e[i]);if(!a&&r===-1&&(r=i),a&&r!==-1){if(n.length>=t)throw new H(`xargs: array element limit exceeded (${t})`,`array_elements`);n.push(e.slice(r,i)),r=-1}}return n}var dZ,fZ,pZ,Vwe=B(()=>{kB(),oX(),mK(),U(),sV(),XB(),dZ={name:`xargs`,summary:`build and execute command lines from standard input`,usage:`xargs [OPTION]... [COMMAND [INITIAL-ARGS]]`,options:[`-I REPLACE replace occurrences of REPLACE with input`,`-d DELIM use DELIM as input delimiter (e.g., -d '\\n' for newline)`,`-n NUM use at most NUM arguments per command line`,`-P NUM run at most NUM processes at a time`,`-0, --null items are separated by null, not whitespace`,`-t, --verbose print commands before executing`,`-r, --no-run-if-empty do not run command if input is empty`,` --help display this help and exit`]},fZ={name:`xargs`,async execute(e,t){if(aV(e))return iV(dZ);let n=null,r=null,i=null,a=null,o=!1,s=!1,c=0;for(let t=0;t1){for(let e of l.slice(1))if(!`0tr`.includes(e))return oV(`xargs`,`-${e}`);l.includes(`0`)&&(o=!0),l.includes(`t`)&&(s=!0),l.includes(`r`),c=t+1}else if(!l.startsWith(`-`)){c=t;break}}}let l=e.slice(c);l.length===0&&l.push(`echo`);let u=vB(t.stdin),d=Math.min(t.limits.maxInputBytes,t.limits.maxStringLength),f=t.limits.maxArrayElements,p=t.limits.maxLoopIterations,m=t.limits.maxOutputSize;if(V(u)>d)throw new H(`xargs: input size limit exceeded (${d} bytes)`,`string_length`);if(a!==null&&a>f)throw new H(`xargs: array element limit exceeded (${f})`,`array_elements`);let h;if(o)h=uZ(u,`\0`,f);else if(r!==null){let e=u.replace(/\n$/,``);try{h=uZ(e,r,f)}catch(e){if(e instanceof H)throw e;return{stdout:``,stderr:`xargs: delimiter must not be empty +`,exitCode:1}}}else h=Bwe(u,f);if(h.length===0)return{stdout:``,stderr:``,exitCode:0};let g=[],_=[],v=0,y=0,b=0,x=t.executionScope?new aX(t.executionScope,`xargs`):void 0,S=e=>{if(x){x.appendResult(e);return}let t=V(e.stdout)+V(e.stderr);if(t>m-y)throw new H(`xargs: output size limit exceeded (${m} bytes)`,`output_size`);e.stdout&&g.push(e.stdout),e.stderr&&_.push(e.stderr),y+=t},C=e=>{if(x){x.append(`stderr`,e);return}let t=V(e);if(t>m-y)throw new H(`xargs: output size limit exceeded (${m} bytes)`,`output_size`);e&&_.push(e),y+=t},w=e=>/[\s"'\\$`!*?[\]{}();&|<>#]/.test(e)?`"${e.replace(/([\\"`$])/g,`\\$1`)}"`:e,T=async e=>{if(++b>p)throw new H(`xargs: iteration limit exceeded (${p})`,`iterations`);if(e.length>f)throw new H(`xargs: array element limit exceeded (${f})`,`array_elements`);for(let t of e)if(V(t)>d)throw new H(`xargs: string length limit exceeded (${d} bytes)`,`string_length`);if(s){let t=e.map(w).join(` `);C(`${t} +`)}return t.exec?t.exec(pK([e[0]]),{cwd:t.cwd,signal:t.signal,args:e.slice(1)}):{stdout:`${e.map(w).join(` `)} +`,stderr:``,exitCode:0}},E=async e=>{if(a!==null&&a>1)for(let t=0;tp)throw new H(`xargs: iteration limit exceeded (${p})`,`iterations`);if(n.length===0)return{stdout:``,stderr:`xargs: replacement string must not be empty +`,exitCode:1};if(l.length>0&&h.length>Math.floor(f/l.length))throw new H(`xargs: array element limit exceeded (${f})`,`array_elements`);let e=(e,t)=>{let r=0,i=0;for(;i=e.indexOf(n,i),i!==-1;)r++,i+=n.length;if(V(e)+r*(V(t)-V(n))>d)throw new H(`xargs: string length limit exceeded (${d} bytes)`,`string_length`);return e.replaceAll(n,t)};await E(h.map(t=>l.map(n=>e(n,t))))}else if(i!==null){let e=[],t=Math.ceil(h.length/i);if(t>Math.min(f,p))throw new H(`xargs: iteration limit exceeded (${p})`,`iterations`);if(h.length+t*l.length>f)throw new H(`xargs: array element limit exceeded (${f})`,`array_elements`);for(let t=0;tgZ,falseFlagsForFuzzing:()=>vZ,flagsForFuzzing:()=>_Z,trueCommand:()=>hZ});var hZ,gZ,_Z,vZ,yZ=B(()=>{hZ={name:`true`,async execute(){return{stdout:``,stderr:``,exitCode:0}}},gZ={name:`false`,async execute(){return{stdout:``,stderr:``,exitCode:1}}},_Z={name:`true`,flags:[]},vZ={name:`false`,flags:[]}}),bZ={};wz(bZ,{clearCommand:()=>SZ,flagsForFuzzing:()=>CZ});var xZ,SZ,CZ,Hwe=B(()=>{sV(),xZ={name:`clear`,summary:`clear the terminal screen`,usage:`clear [OPTIONS]`,options:[` --help display this help and exit`]},SZ={name:`clear`,async execute(e,t){return aV(e)?iV(xZ):{stdout:`\x1B[2J\x1B[H`,stderr:``,exitCode:0}}},CZ={name:`clear`,flags:[]}}),wZ={};wz(wZ,{bashCommand:()=>DZ,flagsForFuzzing:()=>kZ,shCommand:()=>OZ,shFlagsForFuzzing:()=>AZ});async function TZ(e,t,n,r){if(!r.exec)return{stdout:``,stderr:`bash: internal error: exec function not available +`,exitCode:1};let i=eq(r.exportedEnv||{},{0:t,"#":String(n.length),"@":n.join(` `),"*":n.join(` `)});n.forEach((e,t)=>{i[String(t+1)]=e});let a=e;if(a.startsWith(`#!`)){let e=a.indexOf(` +`);e!==-1&&(a=a.slice(e+1))}let o=r.execWithInheritedStdin;return o?await o(a,{env:i,cwd:r.cwd,signal:r.signal}):await r.exec(a,{env:i,cwd:r.cwd,stdin:r.stdin,stdinKind:`bytes`,signal:r.signal})}var EZ,DZ,OZ,kZ,AZ,jZ=B(()=>{kB(),tq(),sV(),EZ={name:`bash`,summary:`execute shell commands or scripts`,usage:`bash [OPTIONS] [SCRIPT_FILE] [ARGUMENTS...]`,options:[`-c COMMAND execute COMMAND string`,` --help display this help and exit`],notes:[`Without -c, reads and executes commands from SCRIPT_FILE.`,`Arguments are passed as $1, $2, etc. to the script.`,`$0 is set to the script name (or "bash" with -c).`]},DZ={name:`bash`,async execute(e,t){if(aV(e))return iV(EZ);if(e[0]===`-c`&&e.length>=2){let n=e[1];return TZ(n,e[2]||`bash`,e.slice(3),t)}if(e.length===0){let e=vB(t.stdin);return e.trim()?TZ(e,`bash`,[],t):{stdout:``,stderr:``,exitCode:0}}let n=e[0],r=e.slice(1);try{let e=t.fs.resolvePath(t.cwd,n);return TZ(await t.fs.readFile(e),n,r,t)}catch{return{stdout:``,stderr:`bash: ${n}: No such file or directory +`,exitCode:127}}}},OZ={name:`sh`,async execute(e,t){if(aV(e))return iV({...EZ,name:`sh`,summary:`execute shell commands or scripts (POSIX shell)`});if(e[0]===`-c`&&e.length>=2){let n=e[1];return TZ(n,e[2]||`sh`,e.slice(3),t)}if(e.length===0){let e=vB(t.stdin);return e.trim()?TZ(e,`sh`,[],t):{stdout:``,stderr:``,exitCode:0}}let n=e[0],r=e.slice(1);try{let e=t.fs.resolvePath(t.cwd,n);return TZ(await t.fs.readFile(e),n,r,t)}catch{return{stdout:``,stderr:`sh: ${n}: No such file or directory +`,exitCode:127}}}},kZ={name:`bash`,flags:[{flag:`-c`,type:`value`,valueHint:`string`}],stdinType:`text`},AZ={name:`sh`,flags:[{flag:`-c`,type:`value`,valueHint:`string`}],stdinType:`text`}});function MZ(e,t,n=1){let r=e.limits.maxArrayElements;if(n<0||t>r-n)throw new H(`query result element limit exceeded (${r})`,`array_elements`)}function Uwe(e,t,n,r,i,a,o,s,c,l){switch(t){case`sort`:return Array.isArray(e)?[[...e].sort(o)]:[null];case`sort_by`:return!Array.isArray(e)||n.length===0?[null]:[[...e].sort((e,t)=>{let a=i(e,n[0],r)[0],s=i(t,n[0],r)[0];return o(a,s)})];case`bsearch`:if(!Array.isArray(e))throw Error(`${e===null?`null`:typeof e==`object`?`object`:typeof e} (${JSON.stringify(e)}) cannot be searched from`);return n.length===0?[null]:i(e,n[0],r).map(t=>{let n=0,r=e.length;for(;n>>1;o(e[i],t)<0?n=i+1:r=i}return no(e.key,t.key)),[a.map(e=>e.item)]}case`group_by`:{if(!Array.isArray(e)||n.length===0)return[null];let t=new Map;for(let a of e){let e=JSON.stringify(i(a,n[0],r)[0]);t.has(e)||t.set(e,[]),t.get(e)?.push(a)}return[[...t.values()]]}case`max`:return Array.isArray(e)&&e.length>0?[e.reduce((e,t)=>o(e,t)>0?e:t)]:[null];case`max_by`:return!Array.isArray(e)||e.length===0||n.length===0?[null]:[e.reduce((e,t)=>{let a=i(e,n[0],r)[0],s=i(t,n[0],r)[0];return o(a,s)>0?e:t})];case`min`:return Array.isArray(e)&&e.length>0?[e.reduce((e,t)=>o(e,t)<0?e:t)]:[null];case`min_by`:return!Array.isArray(e)||e.length===0||n.length===0?[null]:[e.reduce((e,t)=>{let a=i(e,n[0],r)[0],s=i(t,n[0],r)[0];return o(a,s)<0?e:t})];case`add`:{let t=e=>{let t=e.filter(e=>e!==null);return t.length===0?null:t.every(e=>typeof e==`number`)?t.reduce((e,t)=>e+t,0):t.every(e=>typeof e==`string`)?t.join(``):t.every(e=>Array.isArray(e))?t.flat():t.every(e=>e&&typeof e==`object`&&!Array.isArray(e))?eq(...t):null};return n.length>=1?[t(i(e,n[0],r))]:Array.isArray(e)?[t(e)]:[null]}case`any`:if(n.length>=2){try{let t=a(e,n[0],r);for(let e of t)if(i(e,n[1],r).some(s))return[!0]}catch(e){if(e instanceof l)throw e}return[!1]}return n.length===1?Array.isArray(e)?[e.some(e=>s(i(e,n[0],r)[0]))]:[!1]:Array.isArray(e)?[e.some(s)]:[!1];case`all`:if(n.length>=2){try{let t=a(e,n[0],r);for(let e of t)if(!i(e,n[1],r).some(s))return[!1]}catch(e){if(e instanceof l)throw e}return[!0]}return n.length===1?Array.isArray(e)?[e.every(e=>s(i(e,n[0],r)[0]))]:[!0]:Array.isArray(e)?[e.every(s)]:[!0];case`select`:return n.length===0||i(e,n[0],r).some(s)?[e]:[];case`map`:{if(n.length===0||!Array.isArray(e))return[null];MZ(r,0,e.length);let t=[];for(let a of e){let e=i(a,n[0],r);MZ(r,t.length,e.length);for(let n of e)t.push(n)}return[t]}case`map_values`:if(n.length===0)return[null];if(Array.isArray(e)){MZ(r,0,e.length);let t=[];for(let a of e){let e=i(a,n[0],r);MZ(r,t.length,e.length);for(let n of e)t.push(n)}return[t]}if(e&&typeof e==`object`){let t=Object.create(null),a=Object.keys(e);MZ(r,0,a.length);for(let o of a){if(!XG(o))continue;let a=e[o],s=i(a,n[0],r);s.length>0&&ZG(t,o,s[0])}return[t]}return[null];case`has`:{if(n.length===0)return[!1];let t=i(e,n[0],r)[0];return Array.isArray(e)&&typeof t==`number`?[t>=0&&t=0&&e{tq(),U(),iK()});function Gwe(e,t,n,r,i,a,o,s){switch(t){case`first`:if(n.length>0)try{let t=a(e,n[0],r);return t.length>0?[t[0]]:[]}catch(e){if(e instanceof s)throw e;return[]}return Array.isArray(e)&&e.length>0?[e[0]]:[null];case`last`:if(n.length>0){let t=i(e,n[0],r);return t.length>0?[t[t.length-1]]:[]}return Array.isArray(e)&&e.length>0?[e[e.length-1]]:[null];case`nth`:{if(n.length<1)return[null];let t=i(e,n[0],r);if(n.length>1){for(let e of t)if(e<0)throw Error(`nth doesn't support negative indices`);let i;try{i=a(e,n[1],r)}catch(e){if(e instanceof s)throw e;i=[]}return t.flatMap(e=>{let t=e;return t{let n=t;if(n<0)throw Error(`nth doesn't support negative indices`);return n{if(e.length>=t)throw new s(`query result element limit exceeded (${t})`,`array_elements`);e.push(n)},o=i(e,n[0],r);if(n.length===1){let e=[];for(let t of o){let n=t;for(let t=0;t0)for(let e=r;ei;e+=o)a(u,e)}}return u}case`limit`:return n.length<2?[]:i(e,n[0],r).flatMap(t=>{let i=t;if(i<0)throw Error(`limit doesn't support negative count`);if(i===0)return[];let o;try{o=a(e,n[1],r)}catch(e){if(e instanceof s)throw e;o=[]}return o.slice(0,i)});case`isempty`:if(n.length<1)return[!0];try{return[a(e,n[0],r).length===0]}catch(e){if(e instanceof s)throw e;return[!0]}case`isvalid`:if(n.length<1)return[!0];try{return[i(e,n[0],r).length>0]}catch(e){if(e instanceof s)throw e;return[!1]}case`skip`:return n.length<2?[]:i(e,n[0],r).flatMap(t=>{let a=t;if(a<0)throw Error(`skip doesn't support negative count`);return i(e,n[1],r).slice(a)});case`until`:{if(n.length<2)return[e];let t=e,a=r.limits.maxIterations;for(let e=0;e=c)throw new s(`jq while: too many iterations (${c}), increase executionLimits.maxJqIterations`,`iterations`);return t}case`repeat`:{if(n.length===0)return[e];let t=[],a=e,o=r.limits.maxIterations;for(let e=0;e=o)throw new s(`jq repeat: too many iterations (${o}), increase executionLimits.maxJqIterations`,`iterations`);return t}default:return null}}var Kwe=B(()=>{});function NZ(e,t){if(!Number.isFinite(e)||Math.abs(e)>864e10)throw Error(`${t} timestamp is outside the supported range`);return new Date(e*1e3)}function PZ(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/);if(!t)return null;let[,n,r,i,a,o,s]=t.map(Number),c=Date.UTC(n,r-1,i,a,o,s);if(!Number.isFinite(c))return null;let l=new Date(c);return l.getUTCFullYear()!==n||l.getUTCMonth()!==r-1||l.getUTCDate()!==i||l.getUTCHours()!==a||l.getUTCMinutes()!==o||l.getUTCSeconds()!==s?null:l}function qwe(e,t,n,r,i){switch(t){case`now`:return[Date.now()/1e3];case`gmtime`:{if(typeof e!=`number`)return[null];let t=NZ(e,`gmtime`),n=t.getUTCFullYear(),r=t.getUTCMonth(),i=t.getUTCDate(),a=t.getUTCHours(),o=t.getUTCMinutes(),s=t.getUTCSeconds(),c=t.getUTCDay(),l=Date.UTC(n,0,1);return[[n,r,i,a,o,s,c,Math.floor((t.getTime()-l)/864e5)]]}case`mktime`:{if(!Array.isArray(e))throw Error(`mktime requires parsed datetime inputs`);let[t,n,r,i=0,a=0,o=0]=e;if(typeof t!=`number`||typeof n!=`number`)throw Error(`mktime requires parsed datetime inputs`);return[Math.floor(Date.UTC(t,n,r??1,i??0,a??0,o??0)/1e3)]}case`strftime`:{if(n.length===0)return[null];let t=i(e,n[0],r)[0];if(typeof t!=`string`)throw Error(`strftime/1 requires a string format`);let a;if(typeof e==`number`)a=NZ(e,`strftime`);else if(Array.isArray(e)){let[t,n,r,i=0,o=0,s=0]=e;if(typeof t!=`number`||typeof n!=`number`)throw Error(`strftime/1 requires parsed datetime inputs`);a=new Date(Date.UTC(t,n,r??1,i??0,o??0,s??0))}else throw Error(`strftime/1 requires parsed datetime inputs`);let o=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],s=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],c=(e,t=2)=>String(e).padStart(t,`0`);return[t.replace(/%Y/g,String(a.getUTCFullYear())).replace(/%m/g,c(a.getUTCMonth()+1)).replace(/%d/g,c(a.getUTCDate())).replace(/%H/g,c(a.getUTCHours())).replace(/%M/g,c(a.getUTCMinutes())).replace(/%S/g,c(a.getUTCSeconds())).replace(/%A/g,o[a.getUTCDay()]).replace(/%B/g,s[a.getUTCMonth()]).replace(/%Z/g,`UTC`).replace(/%%/g,`%`)]}case`strptime`:{if(n.length===0)return[null];if(typeof e!=`string`)throw Error(`strptime/1 requires a string input`);let t=i(e,n[0],r)[0];if(typeof t!=`string`)throw Error(`strptime/1 requires a string format`);if(t!==FZ)throw Error(`strptime format is not supported: ${t}`);let a=PZ(e);if(a){let e=a.getUTCFullYear(),t=a.getUTCMonth(),n=a.getUTCDate(),r=a.getUTCHours(),i=a.getUTCMinutes(),o=a.getUTCSeconds(),s=a.getUTCDay(),c=Date.UTC(e,0,1);return[[e,t,n,r,i,o,s,Math.floor((a.getTime()-c)/864e5)]]}throw Error(`Cannot parse date: ${e}`)}case`fromdate`:{if(typeof e!=`string`)throw Error(`fromdate requires a string input`);let t=PZ(e);if(!t)throw Error(`date "${e}" does not match format "${FZ}"`);return[Math.floor(t.getTime()/1e3)]}case`todate`:if(typeof e!=`number`)throw Error(`todate requires a number input`);return[NZ(e,`todate`).toISOString().replace(/\.\d{3}Z$/,`Z`)];default:return null}}var FZ,Jwe=B(()=>{FZ=`%Y-%m-%dT%H:%M:%SZ`});function IZ(e){return e!==!1&&e!==null}function LZ(e,t){return JSON.stringify(e)===JSON.stringify(t)}function RZ(e,t){return typeof e==`number`&&typeof t==`number`?e-t:typeof e==`string`&&typeof t==`string`?e.localeCompare(t):0}function Ywe(e,t,n={}){let r=n.maxDepth??2e3,i=tK(e),a=[{target:i,source:t,depth:0}];for(;a.length>0;){let e=a.pop();if(!e)break;if(e.depth>r)throw new H(`query depth limit exceeded (${r})`,`recursion`);for(let t of Object.keys(e.source)){if(n.visit?.(),!XG(t))continue;let r=QG(e.target,t)?eK(e.target[t]):null,i=eK(e.source[t]);if(r&&i){let n=tK(r);ZG(e.target,t,n),a.push({target:n,source:i,depth:e.depth+1})}else ZG(e.target,t,e.source[t])}}return i}function zZ(e,t=3e3){if(typeof e!=`object`||!e)return 0;if(t<=1)return t;let n=(e,t)=>({value:e,keys:Array.isArray(e)?void 0:Object.keys(e),nextChild:0,pathDepth:t,maxChildDepth:0}),r=e=>e.keys===void 0?e.value.length:e.keys.length,i=e=>{if(e.keys){let t=e.keys[e.nextChild++];return e.value[t]}return e.value[e.nextChild++]},a=new WeakMap,o=new WeakMap,s=e,c=[n(s,1)];for(a.set(s,`visiting`);c.length>0;){let e=c[c.length-1];if(e.nextChild=t)return t;e.maxChildDepth=Math.max(e.maxChildDepth,n);continue}let l=e.pathDepth+1;if(l>=t)return t;let u=r;a.set(r,`visiting`),c.push(n(u,l));continue}let s=e.maxChildDepth+1;o.set(e.value,s),a.set(e.value,`done`),c.pop();let l=c.at(-1);if(l)l.maxChildDepth=Math.max(l.maxChildDepth,s);else return s}return 0}function BZ(e,t){let n=e=>e===null?0:typeof e==`boolean`?1:typeof e==`number`?2:typeof e==`string`?3:Array.isArray(e)?4:typeof e==`object`?5:6,r=n(e),i=n(t);if(r!==i)return r-i;if(typeof e==`number`&&typeof t==`number`)return e-t;if(typeof e==`string`&&typeof t==`string`)return e.localeCompare(t);if(typeof e==`boolean`&&typeof t==`boolean`)return!!e-+!!t;if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;ne.some(e=>VZ(e,t)));let n=eK(e),r=eK(t);return n&&r?Object.keys(r).every(e=>QG(n,e)&&VZ(n[e],r[e])):!1}var HZ=B(()=>{U(),iK()});function Xwe(e){let t=[];for(let n=0;n{if(e===null)return``;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return String(e);let t=String(e);return t.includes(`,`)||t.includes(`"`)||t.includes(` +`)||t.includes(`\r`)?`"${t.replace(/"/g,`""`)}"`:t}).join(`,`)]:[null];case`@tsv`:return Array.isArray(e)?[e.map(e=>String(e??``).replace(/\t/g,`\\t`).replace(/\n/g,`\\n`)).join(` `)]:[null];case`@json`:{let t=n??UZ;return zZ(e,t+1)>t?[null]:[JSON.stringify(e)]}case`@html`:return typeof e==`string`?[e.replace(/&/g,`&`).replace(//g,`>`).replace(/'/g,`'`).replace(/"/g,`"`)]:[null];case`@sh`:return typeof e==`string`?[`'${e.replace(/'/g,`'\\''`)}'`]:[null];case`@text`:return typeof e==`string`?[e]:e==null?[``]:[String(e)];default:return null}}var UZ,$we=B(()=>{HZ(),UZ=2e3});function eTe(e,t,n,r,i,a){switch(t){case`index`:return n.length===0?[null]:i(e,n[0],r).map(t=>{if(typeof e==`string`&&typeof t==`string`){if(t===``&&e===``)return null;let n=e.indexOf(t);return n>=0?n:null}if(Array.isArray(e)){if(Array.isArray(t)){for(let n=0;n<=e.length-t.length;n++){let r=!0;for(let i=0;ia(e,t));return n>=0?n:null}return null});case`rindex`:return n.length===0?[null]:i(e,n[0],r).map(t=>{if(typeof e==`string`&&typeof t==`string`){let n=e.lastIndexOf(t);return n>=0?n:null}if(Array.isArray(e)){if(Array.isArray(t)){for(let n=e.length-t.length;n>=0;n--){let r=!0;for(let i=0;i=0;n--)if(a(e[n],t))return n;return null}return null});case`indices`:return n.length===0?[[]]:i(e,n[0],r).map(t=>{let n=[];if(typeof e==`string`&&typeof t==`string`){let r=e.indexOf(t);for(;r!==-1;)n.push(r),r=e.indexOf(t,r+1)}else if(Array.isArray(e)){if(Array.isArray(t)){let r=t.length;if(r===0)for(let t=0;t<=e.length;t++)n.push(t);else for(let i=0;i<=e.length-r;i++){let o=!0;for(let n=0;n{});function nTe(e,t,n,r,i){switch(t){case`fabs`:case`abs`:return typeof e==`number`?[Math.abs(e)]:typeof e==`string`?[e]:[null];case`exp10`:return typeof e==`number`?[10**e]:[null];case`exp2`:return typeof e==`number`?[2**e]:[null];case`pow`:{if(n.length<2)return[null];let t=i(e,n[0],r),a=i(e,n[1],r),o=t[0],s=a[0];return typeof o!=`number`||typeof s!=`number`?[null]:[o**s]}case`atan2`:{if(n.length<2)return[null];let t=i(e,n[0],r),a=i(e,n[1],r),o=t[0],s=a[0];return typeof o!=`number`||typeof s!=`number`?[null]:[Math.atan2(o,s)]}case`hypot`:{if(typeof e!=`number`||n.length===0)return[null];let t=i(e,n[0],r)[0];return[Math.hypot(e,t)]}case`fma`:{if(typeof e!=`number`||n.length<2)return[null];let t=i(e,n[0],r)[0],a=i(e,n[1],r)[0];return[e*t+a]}case`copysign`:{if(typeof e!=`number`||n.length===0)return[null];let t=i(e,n[0],r)[0];return[Math.sign(t)*Math.abs(e)]}case`drem`:case`remainder`:{if(typeof e!=`number`||n.length===0)return[null];let t=i(e,n[0],r)[0];return[e-Math.round(e/t)*t]}case`fdim`:{if(typeof e!=`number`||n.length===0)return[null];let t=i(e,n[0],r)[0];return[Math.max(0,e-t)]}case`fmax`:{if(typeof e!=`number`||n.length===0)return[null];let t=i(e,n[0],r)[0];return[Math.max(e,t)]}case`fmin`:{if(typeof e!=`number`||n.length===0)return[null];let t=i(e,n[0],r)[0];return[Math.min(e,t)]}case`ldexp`:return typeof e!=`number`||n.length===0?[null]:[e*2**i(e,n[0],r)[0]];case`scalbn`:case`scalbln`:return typeof e!=`number`||n.length===0?[null]:[e*2**i(e,n[0],r)[0]];case`nearbyint`:return typeof e==`number`?[Math.round(e)]:[null];case`logb`:return typeof e==`number`?[Math.floor(Math.log2(Math.abs(e)))]:[null];case`significand`:return typeof e==`number`?[e/2**Math.floor(Math.log2(Math.abs(e)))]:[null];case`frexp`:if(typeof e==`number`){if(e===0)return[[0,0]];let t=Math.floor(Math.log2(Math.abs(e)))+1;return[[e/2**t,t]]}return[null];case`modf`:if(typeof e==`number`){let t=Math.trunc(e);return[[e-t,t]]}return[null];default:return null}}var rTe=B(()=>{});function WZ(e){let t=e.limits.maxIterations;return{maxDepth:e.limits.maxDepth,maxResults:e.limits.maxArrayElements,maxIterations:t}}function GZ(e){throw new H(e,`array_elements`)}function KZ(e,t){let n=1;for(let r of e){if(!Number.isSafeInteger(r)||r<0)throw Error(`combinations requires finite array lengths`);r!==0&&n>Math.floor(t/r)&&GZ(`query combination limit exceeded (${t})`),n*=r}return n}function iTe(e,t,n,r,i,a,o,s){switch(t){case`recurse`:{let t=[],o=WZ(r),s=n.length>=2?n[1]:null,c=[{value:e,depth:0}],l=0;for(;c.length>0;){let e=c.pop();if(!e)break;if(++l>o.maxIterations)throw new H(`query iteration limit exceeded (${o.maxIterations})`,`iterations`);if(e.depth>o.maxDepth)throw new H(`query depth limit exceeded (${o.maxDepth})`,`recursion`);if(s&&!i(e.value,s,r).some(a))continue;t.length>=o.maxResults&&GZ(`query result element limit exceeded (${o.maxResults})`),t.push(e.value);let u=[];n.length===0?Array.isArray(e.value)?u=e.value:e.value&&typeof e.value==`object`&&(u=Object.keys(e.value).map(t=>e.value[t])):u=i(e.value,n[0],r).filter(e=>e!=null),c.length>o.maxResults-u.length&&GZ(`query traversal queue limit exceeded (${o.maxResults})`);for(let t=u.length-1;t>=0;t--)c.push({value:u[t],depth:e.depth+1})}return t}case`recurse_down`:return s(e,`recurse`,n,r);case`walk`:{if(n.length===0)return[e];let t=WZ(r),a=new WeakSet,o=new WeakMap,s=[{value:e,depth:0,expanded:!1}],c=e,l=0;for(;s.length>0;){let e=s.pop();if(!e)break;if(++l>t.maxIterations)throw new H(`query iteration limit exceeded (${t.maxIterations})`,`iterations`);if(e.depth>t.maxDepth)throw new H(`query depth limit exceeded (${t.maxDepth})`,`recursion`);let u=e.value!==null&&typeof e.value==`object`?e.value:null;if(!e.expanded&&u){if(a.has(u))continue;a.add(u),s.push({...e,expanded:!0});let n=eK(e.value),r=Array.isArray(e.value)?e.value:Object.keys(n??{}).map(e=>n?.[e]);s.length>t.maxResults-r.length&&GZ(`query traversal queue limit exceeded (${t.maxResults})`);for(let t=r.length-1;t>=0;t--)s.push({value:r[t],depth:e.depth+1,expanded:!1});continue}let d=e.value;if(Array.isArray(e.value))d=e.value.map(e=>typeof e==`object`&&e?o.get(e)??e:e);else if(u){let t=Object.create(null),n=eK(e.value);for(let e of Object.keys(n??{})){if(!XG(e))continue;let r=n?.[e];ZG(t,e,typeof r==`object`&&r?o.get(r)??r:r)}d=t}let f=i(d,n[0],r)[0];u&&o.set(u,f),e.depth===0&&(c=f)}return[c]}case`transpose`:{if(!Array.isArray(e))return[null];if(e.length===0)return[[]];let t=WZ(r),n=0;for(let t of e)Array.isArray(t)&&(n=Math.max(n,t.length));KZ([e.length,n],t.maxResults);let i=[];for(let t=0;tArray.isArray(e)?e[t]:null));return[i]}case`combinations`:{if(n.length>0){let t=i(e,n[0],r)[0];if(!Array.isArray(e))return[];if(!Number.isFinite(t)||!Number.isSafeInteger(t)||t<0)throw Error(`combinations length must be a finite non-negative integer`);let a=WZ(r);if(t>a.maxDepth||t>a.maxResults)throw new H(`query depth limit exceeded (${a.maxDepth})`,`recursion`);if(t===0)return a.maxResults<1&&GZ(`query combination limit exceeded (0)`),[[]];let o=KZ(Array.from({length:t},()=>e.length),a.maxResults);if(o===0)return[];let s=[],c=Array(t).fill(0);for(let n=0;ne[t]));for(let n=t-1;n>=0&&(c[n]++,!(c[n]t.maxDepth)throw new H(`query depth limit exceeded (${t.maxDepth})`,`recursion`);let o=KZ(a.map(e=>e.length),t.maxResults);if(o===0)return[];let s=[],c=Array(a.length).fill(0);for(let e=0;ea[t][e]));for(let e=a.length-1;e>=0&&(c[e]++,!(c[e]0?i(e,n[0],r)[0]:1;if(a>=0){if(a>t.length)return[];let e=t.slice(0,t.length-a);return[o(r.root,e)]}{let n=-a-1;if(n>=t.length)return[e];let i=t.slice(0,n);return[o(r.root,i)]}}case`parents`:{if(r.root===void 0||r.currentPath===void 0)return[[]];let e=r.currentPath,t=[];for(let n=e.length-1;n>=0;n--)t.push(o(r.root,e.slice(0,n)));return[t]}case`root`:return r.root===void 0?[]:[r.root];default:return null}}var aTe=B(()=>{U(),iK()});function qZ(e){return e.limits.maxArrayElements}function JZ(e,t){let n=qZ(e);if(t>=n)throw new H(`query result element limit exceeded (${n})`,`array_elements`)}function oTe(e,t){let n=t.limits.maxDepth??YZ;if(e.length>n)throw new H(`query depth limit exceeded (${n})`,`recursion`);let r=t.limits.maxArrayElements;for(let t of e)if(typeof t==`number`){if(!Number.isSafeInteger(t)||t<0||t>=r)throw new H(`query array index limit exceeded (${r})`,`array_elements`)}else if(typeof t!=`string`)throw Error(`stream path components must be strings or integers`)}function sTe(e,t,n,r,i){switch(t){case`keys`:return Array.isArray(e)?[e.map((e,t)=>t)]:e&&typeof e==`object`?[Object.keys(e).sort()]:[null];case`keys_unsorted`:return Array.isArray(e)?[e.map((e,t)=>t)]:e&&typeof e==`object`?[Object.keys(e)]:[null];case`length`:return typeof e==`string`||Array.isArray(e)?[e.length]:e&&typeof e==`object`?[Object.keys(e).length]:e===null?[0]:typeof e==`number`?[Math.abs(e)]:[null];case`utf8bytelength`:{if(typeof e==`string`)return[V(e)];let t=e===null?`null`:Array.isArray(e)?`array`:typeof e,n=t===`array`||t===`object`?JSON.stringify(e):String(e);throw Error(`${t} (${n}) only strings have UTF-8 byte length`)}case`to_entries`:{let t=eK(e);if(t){let e=Object.keys(t);if(e.length>qZ(r))throw new H(`query result element limit exceeded (${qZ(r)})`,`array_elements`);return[e.map(e=>{let n=Object.create(null);return ZG(n,`key`,e),ZG(n,`value`,t[e]),n})]}return[null]}case`from_entries`:if(Array.isArray(e)){let t=Object.create(null);for(let n of e){let e=eK(n);if(e){let n=e.key??e.Key??e.name??e.Name??e.k,r=e.value??e.Value??e.v;if(n!==void 0){let e=String(n);XG(e)&&ZG(t,e,r)}}}return[t]}return[null];case`with_entries`:{if(n.length===0)return[e];let t=eK(e);if(t){let e=Object.keys(t);if(e.length>qZ(r))throw new H(`query result element limit exceeded (${qZ(r)})`,`array_elements`);let a=[];for(let o of e){let e=Object.create(null);ZG(e,`key`,o),ZG(e,`value`,t[o]);let s=i(e,n[0],r);if(a.length>qZ(r)-s.length)throw new H(`query result element limit exceeded (${qZ(r)})`,`array_elements`);for(let e of s)a.push(e)}let o=Object.create(null);for(let e of a){let t=eK(e);if(t){let e=t.key??t.name??t.k,n=t.value??t.v;if(e!==void 0){let t=String(e);XG(t)&&ZG(o,t,n)}}}return[o]}return[null]}case`reverse`:return Array.isArray(e)?[[...e].reverse()]:typeof e==`string`?[e.split(``).reverse().join(``)]:[null];case`flatten`:return Array.isArray(e)?(n.length>0?i(e,n[0],r):[1/0]).map(t=>{let n=t;if(n<0)throw Error(`flatten depth must not be negative`);return e.flat(n)}):[null];case`unique`:if(Array.isArray(e)){let t=new Set,n=[];for(let r of e){let e=JSON.stringify(r);t.has(e)||(t.add(e),n.push(r))}return[n]}return[null];case`tojson`:case`tojsonstream`:{let t=r.limits.maxDepth??YZ;return zZ(e,t+1)>t?[null]:[JSON.stringify(e)]}case`fromjson`:if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`nan`)return[NaN];if(t===`inf`||t===`infinity`)return[1/0];if(t===`-inf`||t===`-infinity`)return[-1/0];try{return[$G(JSON.parse(e),{maxDepth:r.limits.maxDepth,maxElements:r.limits.maxArrayElements})]}catch(t){throw t instanceof H?t:Error(`Invalid JSON: ${e}`)}}return[e];case`tostring`:return typeof e==`string`?[e]:[JSON.stringify(e)];case`tonumber`:if(typeof e==`number`)return[e];if(typeof e==`string`){let t=Number(e);if(Number.isNaN(t))throw Error(`${JSON.stringify(e)} cannot be parsed as a number`);return[t]}throw Error(`${typeof e} cannot be parsed as a number`);case`toboolean`:{if(typeof e==`boolean`)return[e];if(typeof e==`string`){if(e===`true`)return[!0];if(e===`false`)return[!1];throw Error(`string (${JSON.stringify(e)}) cannot be parsed as a boolean`)}let t=e===null?`null`:Array.isArray(e)?`array`:typeof e,n=t===`array`||t===`object`?JSON.stringify(e):String(e);throw Error(`${t} (${n}) cannot be parsed as a boolean`)}case`tostream`:{let t=[],n=r.limits.maxDepth??YZ,i=[{value:e,path:[]}],a=new WeakSet,o=0;for(;i.length>0;){let e=i.pop();if(!e)break;if(++o>r.limits.maxIterations)throw new H(`query iteration limit exceeded (${r.limits.maxIterations})`,`iterations`);if(e.path.length>n)throw new H(`query depth limit exceeded (${n})`,`recursion`);let s=e.value;if(typeof s!=`object`||!s)JZ(r,t.length),t.push([e.path,s]);else if(Array.isArray(s)){if(a.has(s))throw new H(`cyclic value cannot be converted to a stream`,`recursion`);if(a.add(s),s.length===0)JZ(r,t.length),t.push([e.path,[]]);else{if(i.length>qZ(r)-s.length)throw new H(`query traversal queue limit exceeded (${qZ(r)})`,`array_elements`);for(let t=s.length-1;t>=0;t--)i.push({value:s[t],path:[...e.path,t]})}}else{if(a.has(s))throw new H(`cyclic value cannot be converted to a stream`,`recursion`);a.add(s);let n=Object.keys(s);if(n.length===0)JZ(r,t.length),t.push([e.path,Object.create(null)]);else{if(i.length>qZ(r)-n.length)throw new H(`query traversal queue limit exceeded (${qZ(r)})`,`array_elements`);for(let t=n.length-1;t>=0;t--){let r=n[t];i.push({value:s[r],path:[...e.path,r]})}}}}return JZ(r,t.length),t.push([[]]),t}case`fromstream`:{if(n.length===0)return[e];let t=i(e,n[0],r);if(t.length>qZ(r))throw new H(`query stream item limit exceeded (${qZ(r)})`,`array_elements`);let a=null,o=0;for(let e of t){if(!Array.isArray(e)||e.length===1&&Array.isArray(e[0])&&e[0].length===0||e.length!==2)continue;let[t,n]=e;if(!Array.isArray(t))continue;if(oTe(t,r),t.length===0){a=n;continue}a===null&&(a=typeof t[0]==`number`?[]:Object.create(null));let i=a;for(let e=0;er.limits.maxIterations-o)throw new H(`query iteration limit exceeded (${r.limits.maxIterations})`,`iterations`);for(o+=Math.max(0,e);i.length<=n;)i.push(null);i[n]===null&&(i[n]=typeof a==`number`?[]:Object.create(null)),i=i[n]}else{let e=eK(i);if(e){let t=String(n);if(!XG(t))continue;(e[t]===null||e[t]===void 0)&&ZG(e,t,typeof a==`number`?[]:Object.create(null)),i=e[t]}}}let s=t[t.length-1];if(Array.isArray(i)&&typeof s==`number`){let e=s+1-i.length;if(e>r.limits.maxIterations-o)throw new H(`query iteration limit exceeded (${r.limits.maxIterations})`,`iterations`);for(o+=Math.max(0,e);i.length<=s;)i.push(null);i[s]=n}else{let e=eK(i);if(e){let t=String(s);XG(t)&&ZG(e,t,n)}}}return[a]}case`truncate_stream`:{let t=typeof e==`number`?Math.floor(e):0;if(n.length===0)return[];let a=[],o=i(e,n[0],r);for(let e of o)if(Array.isArray(e)){if(e.length===1&&Array.isArray(e[0])){let n=e[0];n.length>t&&a.push([n.slice(t)]);continue}if(e.length===2&&Array.isArray(e[0])){let n=e[0],r=e[1];n.length>t&&a.push([n.slice(t),r])}}return a}default:return null}}var YZ,cTe=B(()=>{kB(),U(),iK(),HZ(),YZ=2e3});function XZ(e,t){if(!Array.isArray(e))throw Error(`path must be an array`);let n=t.limits.maxDepth;if(e.length>n)throw new H(`query depth limit exceeded (${n})`,`recursion`);let r=t.limits.maxArrayElements,i=0;for(let t of e)if(typeof t==`number`){if(!Number.isSafeInteger(t)||t<0||t>=r)throw new H(`query array index limit exceeded (${r})`,`array_elements`);let e=t+1;if(i>r-e)throw new H(`query cumulative array allocation limit exceeded (${r})`,`array_elements`);i+=e}else if(typeof t!=`string`)throw Error(`path components must be strings or integers`);return iQ(t,i+e.length),e}function ZZ(e,t,n){let r=[],i=[{value:e,path:[],isRoot:!0}];for(;i.length>0;){let e=i.pop();if(!e)break;if(iQ(t),e.path.length>t.limits.maxDepth)throw new H(`query depth limit exceeded (${t.limits.maxDepth})`,`recursion`);if(e.value===null||typeof e.value!=`object`){(n||!e.isRoot)&&(aQ(t,r.length),r.push(e.path));continue}!n&&!e.isRoot&&(aQ(t,r.length),r.push(e.path));let a=Array.isArray(e.value)?e.value.map((e,t)=>[t,e]):Object.keys(e.value).map(t=>[t,e.value[t]]);aQ(t,r.length,i.length+a.length);for(let t=a.length-1;t>=0;t--){let[n,r]=a[t],o=[...e.path,n];i.push({value:r,path:o,isRoot:!1})}}return r}function lTe(e,t,n,r,i,a,o,s,c,l){switch(t){case`getpath`:{if(n.length===0)return[null];let t=i(e,n[0],r),a=[];for(let n of t){let t=n,r=e;for(let e of t){if(r==null){r=null;break}if(Array.isArray(r)&&typeof e==`number`)r=r[e];else if(typeof e==`string`){let t=eK(r);if(!t||!Object.hasOwn(t,e)){r=null;break}r=t[e]}else{r=null;break}}a.push(r)}return a}case`setpath`:{if(n.length<2)return[null];let t=XZ(i(e,n[0],r)[0],r),a=i(e,n[1],r)[0];return[o(e,t,a)]}case`delpaths`:{if(n.length===0)return[e];let t=i(e,n[0],r)[0],a=e;for(let e of t.sort((e,t)=>t.length-e.length))a=s(a,e);return[a]}case`path`:{if(n.length===0)return[[]];let t=[];return l(e,n[0],r,[],t),t}case`del`:return n.length===0?[e]:[c(e,n[0],r)];case`pick`:{if(n.length===0)return[null];let t=[];for(let i of n)l(e,i,r,[],t);let i=null;for(let n of t){for(let e of n)if(typeof e==`number`&&e<0)throw Error(`Out of bounds negative array index`);XZ(n,r);let t=e;for(let e of n){if(t==null)break;if(Array.isArray(t)&&typeof e==`number`)t=t[e];else if(typeof e==`string`){let n=eK(t);if(!n||!Object.hasOwn(n,e)){t=null;break}t=n[e]}else{t=null;break}}i=o(i,n,t)}return[i]}case`paths`:{let t=ZZ(e,r,!1);return n.length>0?t.filter(t=>{let o=e;for(let e of t)if(Array.isArray(o)&&typeof e==`number`)o=o[e];else if(typeof e==`string`){let t=eK(o);if(!t||!Object.hasOwn(t,e))return!1;o=t[e]}else return!1;return i(o,n[0],r).some(a)}):t}case`leaf_paths`:return ZZ(e,r,!0);default:return null}}var uTe=B(()=>{U(),SQ(),iK()});function dTe(e,t,n,r,i,a){switch(t){case`IN`:{if(n.length===0)return[!1];if(n.length===1){let t=i(e,n[0],r);for(let n of t)if(a(e,n))return[!0];return[!1]}let t=i(e,n[0],r),o=i(e,n[1],r),s=new Set(o.map(e=>JSON.stringify(e)));for(let e of t)if(s.has(JSON.stringify(e)))return[!0];return[!1]}case`INDEX`:{if(n.length===0)return[Object.create(null)];if(n.length===1){let t=i(e,n[0],r),a=Object.create(null);for(let e of t){let t=String(e);XG(t)&&ZG(a,t,e)}return[a]}if(n.length===2){let t=i(e,n[0],r),a=Object.create(null);for(let e of t){let t=i(e,n[1],r);if(t.length>0){let n=String(t[0]);XG(n)&&ZG(a,n,e)}}return[a]}let t=i(e,n[0],r),a=Object.create(null);for(let e of t){let t=i(e,n[1],r),o=i(e,n[2],r);if(t.length>0&&o.length>0){let e=String(t[0]);XG(e)&&ZG(a,e,o[0])}}return[a]}case`JOIN`:{if(n.length<2)return[null];let t=eK(i(e,n[0],r)[0]);if(!t||!Array.isArray(e))return[null];let a=[];for(let o of e){let e=i(o,n[1],r),s=e.length>0?String(e[0]):``,c=QG(t,s)?t[s]:null;a.push([o,c])}return[a]}default:return null}}var fTe=B(()=>{iK()});function QZ(e){return e.limits.maxArrayElements}function $Z(e){return Math.min(e.limits.maxStringLength,e.limits.maxOutputSize)}function eQ(e,t){let n=QZ(e);if(!Number.isSafeInteger(t)||t<0||t>n)throw new H(`query result element limit exceeded (${n})`,`array_elements`)}function pTe(e,t,n){if(e===``)return t===``?0:1;if(t===``)return e.length;let r=1,i=0;for(;;){let a=e.indexOf(t,i);if(a<0||(r++,r>n))return r;i=a+t.length}}function mTe(e,t,n,r,i){switch(t){case`join`:{if(!Array.isArray(e))return[null];let t=n.length>0?i(e,n[0],r):[``];for(let t of e)if(Array.isArray(t)||typeof t==`object`&&t)throw Error(`cannot join: contains arrays or objects`);return eQ(r,t.length),t.map(t=>{let n=String(t),i=0;for(let t=0;t0&&(i+=V(n)),i>$Z(r))throw new H(`query string size limit exceeded (${$Z(r)} bytes)`,`string_length`)}return e.map(e=>e===null?``:typeof e==`string`?e:String(e)).join(n)})}case`split`:{if(typeof e!=`string`||n.length===0)return[null];let t=i(e,n[0],r),a=String(t[0]);return eQ(r,pTe(e,a,QZ(r))),[e.split(a)]}case`splits`:{if(typeof e!=`string`||n.length===0)return[];let t=i(e,n[0],r),a=String(t[0]);try{let t=n.length>1?String(i(e,n[1],r)[0]):`g`,o=mG(a,t.includes(`g`)?t:`${t}g`),s=1;for(let t of o.matchAll(e))s+=Math.max(1,t.length),eQ(r,s);let c=o.split(e);return eQ(r,c.length),c}catch(e){if(e instanceof H)throw e;return[]}}case`scan`:{if(typeof e!=`string`||n.length===0)return[];let t=i(e,n[0],r),a=String(t[0]);try{let t=n.length>1?String(i(e,n[1],r)[0]):``,o=mG(a,t.includes(`g`)?t:`${t}g`),s=[];for(let t of o.matchAll(e))eQ(r,s.length+1),t.length>1?(eQ(r,t.length-1),s.push(t.slice(1))):s.push(t[0]);return s}catch(e){if(e instanceof H)throw e;return[]}}case`test`:{if(typeof e!=`string`||n.length===0)return[!1];let t=i(e,n[0],r),a=String(t[0]);try{return[mG(a,n.length>1?String(i(e,n[1],r)[0]):``).test(e)]}catch{return[!1]}}case`match`:{if(typeof e!=`string`||n.length===0)return[null];let t=i(e,n[0],r),a=String(t[0]);try{let t=mG(a,`${n.length>1?String(i(e,n[1],r)[0]):``}d`).exec(e);if(!t)return[];let o=t.indices;return[{offset:t.index,length:t[0].length,string:t[0],captures:t.slice(1).map((e,t)=>({offset:o?.[t+1]?.[0]??null,length:e?.length??0,string:e??``,name:null}))}]}catch{return[null]}}case`capture`:{if(typeof e!=`string`||n.length===0)return[null];let t=i(e,n[0],r),a=String(t[0]);try{let t=mG(a,n.length>1?String(i(e,n[1],r)[0]):``).match(e);return!t||!t.groups?[Object.create(null)]:[t.groups]}catch{return[null]}}case`sub`:{if(typeof e!=`string`||n.length<2)return[null];let t=i(e,n[0],r),a=i(e,n[1],r),o=String(t[0]),s=String(a[0]);try{return[mG(o,n.length>2?String(i(e,n[2],r)[0]):``).replace(e,s)]}catch{return[e]}}case`gsub`:{if(typeof e!=`string`||n.length<2)return[null];let t=i(e,n[0],r),a=i(e,n[1],r),o=String(t[0]),s=String(a[0]);try{let t=n.length>2?String(i(e,n[2],r)[0]):`g`;return[mG(o,t.includes(`g`)?t:`${t}g`).replace(e,s)]}catch{return[e]}}case`ascii_downcase`:return typeof e==`string`?[e.replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))]:[null];case`ascii_upcase`:return typeof e==`string`?[e.replace(/[a-z]/g,e=>String.fromCharCode(e.charCodeAt(0)-32))]:[null];case`ltrimstr`:{if(typeof e!=`string`||n.length===0)return[e];let t=i(e,n[0],r),a=String(t[0]);return[e.startsWith(a)?e.slice(a.length):e]}case`rtrimstr`:{if(typeof e!=`string`||n.length===0)return[e];let t=i(e,n[0],r),a=String(t[0]);return a===``?[e]:[e.endsWith(a)?e.slice(0,-a.length):e]}case`trimstr`:{if(typeof e!=`string`||n.length===0)return[e];let t=i(e,n[0],r),a=String(t[0]);if(a===``)return[e];let o=e;return o.startsWith(a)&&(o=o.slice(a.length)),o.endsWith(a)&&(o=o.slice(0,-a.length)),[o]}case`trim`:if(typeof e==`string`)return[e.trim()];throw Error(`trim input must be a string`);case`ltrim`:if(typeof e==`string`)return[e.trimStart()];throw Error(`trim input must be a string`);case`rtrim`:if(typeof e==`string`)return[e.trimEnd()];throw Error(`trim input must be a string`);case`startswith`:{if(typeof e!=`string`||n.length===0)return[!1];let t=i(e,n[0],r);return[e.startsWith(String(t[0]))]}case`endswith`:{if(typeof e!=`string`||n.length===0)return[!1];let t=i(e,n[0],r);return[e.endsWith(String(t[0]))]}case`ascii`:return typeof e==`string`&&e.length>0?[e.charCodeAt(0)]:[null];case`explode`:if(typeof e==`string`){let t=0;for(let n of e)t++,eQ(r,t);return[Array.from(e).map(e=>e.codePointAt(0))]}return[null];case`implode`:if(!Array.isArray(e))throw Error(`implode input must be an array`);return[e.map(e=>{if(typeof e==`string`)throw Error(`string (${JSON.stringify(e)}) can't be imploded, unicode codepoint needs to be numeric`);if(typeof e!=`number`||Number.isNaN(e))throw Error(`number (null) can't be imploded, unicode codepoint needs to be numeric`);let t=Math.trunc(e);return t<0||t>1114111||t>=55296&&t<=57343?String.fromCodePoint(65533):String.fromCodePoint(t)}).join(``)];default:return null}}var hTe=B(()=>{U(),yG(),XB()});function gTe(e,t){switch(t){case`type`:return e===null?[`null`]:Array.isArray(e)?[`array`]:typeof e==`boolean`?[`boolean`]:typeof e==`number`?[`number`]:typeof e==`string`?[`string`]:typeof e==`object`?[`object`]:[`null`];case`infinite`:return[1/0];case`nan`:return[NaN];case`isinfinite`:return[typeof e==`number`&&!Number.isFinite(e)];case`isnan`:return[typeof e==`number`&&Number.isNaN(e)];case`isnormal`:return[typeof e==`number`&&Number.isFinite(e)&&e!==0];case`isfinite`:return[typeof e==`number`&&Number.isFinite(e)];case`numbers`:return typeof e==`number`?[e]:[];case`strings`:return typeof e==`string`?[e]:[];case`booleans`:return typeof e==`boolean`?[e]:[];case`nulls`:return e===null?[e]:[];case`arrays`:return Array.isArray(e)?[e]:[];case`objects`:return e&&typeof e==`object`&&!Array.isArray(e)?[e]:[];case`iterables`:return Array.isArray(e)||e&&typeof e==`object`&&!Array.isArray(e)?[e]:[];case`scalars`:return!Array.isArray(e)&&!(e&&typeof e==`object`)?[e]:[];case`values`:return e===null?[]:[e];case`not`:return e===!1||e===null?[!0]:[!1];case`null`:return[null];case`true`:return[!0];case`false`:return[!1];case`empty`:return[];default:return null}}var _Te=B(()=>{}),vTe=B(()=>{Wwe(),Kwe(),Jwe(),$we(),tTe(),rTe(),aTe(),cTe(),uTe(),fTe(),hTe(),_Te()});function tQ(e,t,n){if(t.length===0)return n;let[r,...i]=t;if(typeof r==`number`){if(e&&typeof e==`object`&&!Array.isArray(e))throw Error(`Cannot index object with number`);if(r>536870911)throw Error(`Array index too large`);if(r<0)throw Error(`Out of bounds negative array index`);let t=Array.isArray(e)?[...e]:[];for(;t.length<=r;)t.push(null);return t[r]=tQ(t[r],i,n),t}if(Array.isArray(e))throw Error(`Cannot index array with string`);if(!XG(r))return e??Object.create(null);let a=eK(e),o=a?tK(a):Object.create(null);return ZG(o,r,tQ(Object.hasOwn(o,r)?o[r]:void 0,i,n)),o}function nQ(e,t){if(t.length===0)return null;if(t.length===1){let n=t[0];if(Array.isArray(e)&&typeof n==`number`){let t=[...e];return t.splice(n,1),t}if(e&&typeof e==`object`&&!Array.isArray(e)){let t=String(n);if(!XG(t))return e;let r=tK(e);return delete r[t],r}return e}let[n,...r]=t;if(Array.isArray(e)&&typeof n==`number`){let t=[...e];return t[n]=nQ(t[n],r),t}if(e&&typeof e==`object`&&!Array.isArray(e)){let t=String(n);if(!XG(t))return e;let i=tK(e);return Object.hasOwn(i,t)&&ZG(i,t,nQ(i[t],r)),i}return e}var yTe=B(()=>{iK()});function rQ(e,t){return new H(e,t)}function iQ(e,t=1){if(!Number.isSafeInteger(t)||t<0||e.budget.operations>e.limits.maxIterations-t)throw rQ(`query evaluation: too many iterations (${e.limits.maxIterations})`,`iterations`);e.budget.operations+=t}function aQ(e,t,n=1){let r=e.limits.maxArrayElements;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<0||n<0||t>r-n)throw rQ(`query result element limit exceeded (${r})`,`array_elements`)}function oQ(e,t,n){aQ(e,t.length,n.length);for(let e of n)t.push(e)}function sQ(e,t,n){let r=[];for(let i of t)iQ(e),oQ(e,r,n(i));return r}function bTe(e){let t=new Map;if(e?.namedArgs)for(let[n,r]of e.namedArgs)t.set(`$${n}`,r);return{vars:t,limits:{maxIterations:e?.limits?.maxIterations??vQ,maxDepth:e?.limits?.maxDepth??bQ,maxStringLength:e?.limits?.maxStringLength??yQ,maxOutputSize:e?.limits?.maxOutputSize??yQ,maxArrayElements:e?.limits?.maxArrayElements??1e5},env:e?.env,namedArgs:e?.namedArgs,positionalArgs:e?.positionalArgs,coverage:e?.coverage,requireDefenseContext:e?.requireDefenseContext,defenseContextChecked:!1,budget:e?.budget??{operations:0,callDepth:0}}}function cQ(e,t,n){let r=new Map(e.vars);return r.set(t,n),{vars:r,limits:e.limits,env:e.env,namedArgs:e.namedArgs,positionalArgs:e.positionalArgs,requireDefenseContext:e.requireDefenseContext,defenseContextChecked:e.defenseContextChecked,root:e.root,currentPath:e.currentPath,funcs:e.funcs,labels:e.labels,coverage:e.coverage,budget:e.budget}}function lQ(e,t,n){switch(t.type){case`var`:return cQ(e,t.name,n);case`array`:{if(!Array.isArray(n))return null;let r=e;for(let e=0;e0&&t.args[0].type===`Literal`){let e=t.args[0].value;typeof e==`number`&&(n=e)}if(n>=0)return e.slice(0,Math.max(0,e.length-n));{let t=-n-1;return e.slice(0,Math.min(t,e.length))}}if(t.name===`root`)return[]}if(t.type===`Field`){let n=uQ(t);if(n!==null)return[...e,...n]}if(t.type===`Index`&&t.index.type===`Literal`){let n=uQ(t);if(n!==null)return[...e,...n]}if(t.type===`Pipe`){let n=dQ(e,t.left);return n===null?null:dQ(n,t.right)}return t.type===`Identity`?e:null}function fQ(e,t,n){if(t.type===`Comma`){let r=[];try{oQ(n,r,Y(e,t.left,n))}catch(e){if(e instanceof H)throw e;if(r.length>0)return r;throw Error(`evaluation failed`)}try{oQ(n,r,Y(e,t.right,n))}catch(e){if(e instanceof H)throw e;return r}return r}return Y(e,t,n)}function Y(e,t,n){let r=n&&`vars`in n?n:bTe(n);if(r.defenseContextChecked||(OK(r.requireDefenseContext,`query-engine`,`evaluation`),r={...r,defenseContextChecked:!0}),r.root===void 0&&(r={...r,root:e,currentPath:[]}),iQ(r),r.budget.callDepth++,r.budget.callDepth>r.limits.maxDepth)throw r.budget.callDepth--,rQ(`query depth limit exceeded (${r.limits.maxDepth})`,`recursion`);try{let n=STe(e,t,r);return aQ(r,0,n.length),n}finally{r.budget.callDepth--}}function STe(e,t,n){switch(n.coverage?.hit(`jq:node:${t.type}`),t.type){case`Identity`:return[e];case`Field`:return sQ(n,t.base?Y(e,t.base,n):[e],e=>{let n=eK(e);if(n){if(!Object.hasOwn(n,t.name))return[null];let e=n[t.name];return[e===void 0?null:e]}if(e===null)return[null];throw Error(`Cannot index ${Array.isArray(e)?`array`:typeof e} with string "${t.name}"`)});case`Index`:return sQ(n,t.base?Y(e,t.base,n):[e],e=>sQ(n,Y(e,t.index,n),t=>{if(typeof t==`number`&&Array.isArray(e)){if(Number.isNaN(t))return[null];let n=Math.trunc(t),r=n<0?e.length+n:n;return r>=0&&r{if(r===null)return[null];if(!Array.isArray(r)&&typeof r!=`string`)throw Error(`Cannot slice ${typeof r} (${JSON.stringify(r)})`);let i=r.length,a=t.start?Y(e,t.start,n):[0],o=t.end?Y(e,t.end,n):[i];return aQ(n,0,a.length*o.length),sQ(n,a,e=>o.map(t=>{let n=e,a=t,o=Number.isNaN(n)?0:Number.isInteger(n)?n:Math.floor(n),s=Number.isNaN(a)?i:Number.isInteger(a)?a:Math.ceil(a),c=pQ(o,i),l=pQ(s,i);return r.slice(c,l)}))});case`Iterate`:return sQ(n,t.base?Y(e,t.base,n):[e],e=>Array.isArray(e)?e:e&&typeof e==`object`?Object.values(e):[]);case`Pipe`:{let r=Y(e,t.left,n),i=uQ(t.left),a=[];for(let e of r)try{if(i!==null){let r={...n,currentPath:[...n.currentPath??[],...i]};oQ(n,a,Y(e,t.right,r))}else oQ(n,a,Y(e,t.right,n))}catch(e){throw e instanceof gQ?e.withPrependedResults(a):e}return a}case`Comma`:{let r=Y(e,t.left,n),i=Y(e,t.right,n);return aQ(n,r.length,i.length),[...r,...i]}case`Literal`:return[t.value];case`Array`:return t.elements?[Y(e,t.elements,n)]:[[]];case`Object`:{let r=[Object.create(null)];for(let i of t.entries){let t=typeof i.key==`string`?[i.key]:Y(e,i.key,n),a=Y(e,i.value,n),o=[],s=t.filter(e=>typeof e==`string`&&XG(e)).length,c=s+(t.length-s);aQ(n,0,r.length*c*a.length);for(let e of r)for(let n of t){if(typeof n!=`string`)throw Error(`Cannot use ${n===null?`null`:Array.isArray(n)?`array`:typeof n} (${JSON.stringify(n)}) as object key`);if(!XG(n)){for(let t of a)o.push(tK(e));continue}for(let t of a){let r=tK(e);ZG(r,n,t),o.push(r)}}r.length=0,oQ(n,r,o)}return r}case`Paren`:return Y(e,t.expr,n);case`BinaryOp`:return TTe(e,t.op,t.left,t.right,n);case`UnaryOp`:return Y(e,t.operand,n).map(e=>{if(t.op===`-`){if(typeof e==`number`)return-e;if(typeof e==`string`)throw Error(`string (${(e=>e.length>5?`"${e.slice(0,3)}...`:JSON.stringify(e))(e)}) cannot be negated`);return null}return t.op===`not`?!IZ(e):null});case`Cond`:return sQ(n,Y(e,t.cond,n),r=>{if(IZ(r))return Y(e,t.then,n);for(let r of t.elifs)if(Y(e,r.cond,n).some(IZ))return Y(e,r.then,n);return t.else?Y(e,t.else,n):[e]});case`Try`:try{return Y(e,t.body,n)}catch(e){if(e instanceof H)throw e;return t.catch?Y(e instanceof _Q?e.value:e instanceof Error?e.message:String(e),t.catch,n):[]}case`Call`:return mQ(e,t.name,t.args,n);case`VarBind`:return sQ(n,Y(e,t.value,n),r=>{let i=null,a=[];if(t.pattern?a.push(t.pattern):t.name&&a.push({type:`var`,name:t.name}),t.alternatives)for(let e of t.alternatives)a.push(e);for(let e of a)if(i=lQ(n,e,r),i!==null)break;return i===null?[]:Y(e,t.body,i)});case`VarRef`:{if(t.name===`$ENV`)return[n.env?QK(n.env):Object.create(null)];if(t.name===`$ARGS`){let e=Object.create(null);if(n.namedArgs)for(let[t,r]of n.namedArgs)Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0});let t=Object.create(null);return t.positional=n.positionalArgs?[...n.positionalArgs]:[],t.named=e,[t]}let e=n.vars.get(t.name);return e===void 0?[null]:[e]}case`Recurse`:{let t=[],r=new WeakSet,i=[{val:e,depth:0}];for(;i.length>0;){let e=i.pop();if(!e)break;let{val:a,depth:o}=e;if(iQ(n),o>n.limits.maxDepth)throw rQ(`query depth limit exceeded (${n.limits.maxDepth})`,`recursion`);if(a&&typeof a==`object`){if(r.has(a))continue;r.add(a)}if(aQ(n,t.length),t.push(a),Array.isArray(a))for(let e=a.length-1;e>=0;e--)i.push({val:a[e],depth:o+1});else if(a&&typeof a==`object`){let e=Object.keys(a);for(let t=e.length-1;t>=0;t--)i.push({val:a[e[t]],depth:o+1})}}return t}case`Optional`:try{return Y(e,t.expr,n)}catch(e){if(e instanceof H)throw e;return[]}case`StringInterp`:{let r=new oH(n.limits.maxStringLength,`query string interpolation`,()=>new H(`string size limit exceeded (${n.limits.maxStringLength} bytes)`,`string_length`));for(let i of t.parts){if(typeof i==`string`){r.append(i);continue}let t=Y(e,i,n);for(let e of t){if(iQ(n),zZ(e,n.limits.maxDepth+1)>n.limits.maxDepth)throw rQ(`query depth limit exceeded (${n.limits.maxDepth})`,`recursion`);r.append(typeof e==`string`?e:JSON.stringify(e))}}return[r.build()]}case`UpdateOp`:return[CTe(e,t.path,t.op,t.value,n)];case`Reduce`:{let r=Y(e,t.expr,n),i=Y(e,t.init,n)[0],a=n.limits.maxDepth??bQ;for(let e of r){let r;if(t.pattern){if(r=lQ(n,t.pattern,e),r===null)continue}else r=cQ(n,t.varName,e);if(i=Y(i,t.update,r)[0],zZ(i,a+1)>a)return[null]}return[i]}case`Foreach`:{let r=Y(e,t.expr,n),i=Y(e,t.init,n)[0],a=[];for(let e of r)try{let r;if(t.pattern){if(r=lQ(n,t.pattern,e),r===null)continue}else r=cQ(n,t.varName,e);i=Y(i,t.update,r)[0],t.extract?oQ(n,a,Y(i,t.extract,r)):(aQ(n,a.length),a.push(i))}catch(e){throw e instanceof gQ?e.withPrependedResults(a):e}return a}case`Label`:try{return Y(e,t.body,{...n,labels:new Set([...n.labels??[],t.name])})}catch(e){if(e instanceof gQ&&e.label===t.name)return e.partialResults;throw e}case`Break`:throw new gQ(t.name);case`Def`:{let r=new Map(n.funcs??[]),i=`${t.name}/${t.params.length}`;r.set(i,{params:t.params,body:t.funcBody,closure:new Map(n.funcs??[])});let a={...n,funcs:r};return Y(e,t.body,a)}default:throw Error(`Unknown AST node type: ${t.type}`)}}function pQ(e,t){return e<0?Math.max(0,t+e):Math.min(e,t)}function CTe(e,t,n,r,i){function a(e,t){switch(n){case`=`:return t;case`|=`:return Y(e,r,i)[0]??null;case`+=`:return typeof e==`number`&&typeof t==`number`||typeof e==`string`&&typeof t==`string`?e+t:Array.isArray(e)&&Array.isArray(t)?(aQ(i,e.length,t.length),[...e,...t]):e&&t&&typeof e==`object`&&typeof t==`object`?nK(e,t):t;case`-=`:return typeof e==`number`&&typeof t==`number`?e-t:e;case`*=`:return typeof e==`number`&&typeof t==`number`?e*t:e;case`/=`:return typeof e==`number`&&typeof t==`number`?e/t:e;case`%=`:return typeof e==`number`&&typeof t==`number`?e%t:e;case`//=`:return e===null||e===!1?t:e;default:return t}}function o(t,n,r){switch(n.type){case`Identity`:return r(t);case`Field`:if(!XG(n.name))return t;if(n.base)return o(t,n.base,e=>{if(e&&typeof e==`object`&&!Array.isArray(e)){let t=tK(e),i=Object.hasOwn(t,n.name)?t[n.name]:void 0;return ZG(t,n.name,r(i)),t}return e});if(t&&typeof t==`object`&&!Array.isArray(t)){let e=tK(t),i=Object.hasOwn(e,n.name)?e[n.name]:void 0;return ZG(e,n.name,r(i)),e}return t;case`Index`:{let a=Y(e,n.index,i)[0];if(typeof a==`number`&&Number.isNaN(a))throw Error(`Cannot set array element at NaN index`);if(typeof a==`number`&&!Number.isFinite(a))throw Error(`array index must be finite`);if(typeof a==`number`&&!Number.isInteger(a)&&(a=Math.trunc(a)),n.base)return o(t,n.base,e=>{if(typeof a==`number`&&Array.isArray(e)){let t=[...e],n=a<0?t.length+a:a;if(n>=0){aQ(i,0,n+1),t.length<=n&&(t.length=n+1);for(let r=e.length;r536870911)throw Error(`Array index too large`);if(a<0&&(!t||!Array.isArray(t)))throw Error(`Out of bounds negative array index`);if(Array.isArray(t)){let e=[...t],n=a<0?e.length+a:a;if(n>=0){aQ(i,0,n+1),e.length<=n&&(e.length=n+1);for(let r=t.length;r{if(Array.isArray(e)){aQ(i,0,e.length);let t=[];for(let n of e)iQ(i),t.push(r(n));return t}if(e&&typeof e==`object`){let t=Object.create(null);for(let[n,i]of Object.entries(e))XG(n)&&ZG(t,n,r(i));return t}return e};return n.base?o(t,n.base,e):e(t)}case`Pipe`:return o(o(t,n.left,e=>e),n.right,r);default:return r(t)}}return o(e,t,t=>n===`|=`?a(t,t):a(t,Y(e,r,i)[0]??null))}function wTe(e,t,n){function r(t,i,a){switch(i.type){case`Identity`:return a;case`Field`:if(!XG(i.name))return t;if(i.base){let e=Y(t,i.base,n)[0],o=r(e,{type:`Field`,name:i.name},a);return r(t,i.base,o)}if(t&&typeof t==`object`&&!Array.isArray(t)){let e=tK(t);return ZG(e,i.name,a),e}return t;case`Index`:{if(i.base){let e=Y(t,i.base,n)[0],o=r(e,{type:`Index`,index:i.index},a);return r(t,i.base,o)}let o=Y(e,i.index,n)[0];if(typeof o==`number`&&Array.isArray(t)){let e=[...t],n=o<0?e.length+o:o;return n>=0&&n=0&&n=0&&nIZ(t)?sQ(i,Y(e,r,i),e=>[IZ(e)]):[!1]);if(t===`or`)return sQ(i,Y(e,n,i),t=>IZ(t)?[!0]:sQ(i,Y(e,r,i),e=>[IZ(e)]));if(t===`//`){let t=Y(e,n,i).filter(e=>e!=null&&e!==!1);return t.length>0?t:Y(e,r,i)}let a=Y(e,n,i),o=Y(e,r,i),s=a.length*o.length;return aQ(i,0,s),iQ(i,s),a.flatMap(e=>o.map(n=>{switch(t){case`+`:if(e===null)return n;if(n===null)return e;if(typeof e==`number`&&typeof n==`number`)return e+n;if(typeof e==`string`&&typeof n==`string`){let t=i.limits.maxStringLength;if(V(e)+V(n)>t)throw new H(`string size limit exceeded (${t} bytes)`,`string_length`);return e+n}return Array.isArray(e)&&Array.isArray(n)?(aQ(i,e.length,n.length),[...e,...n]):e&&n&&typeof e==`object`&&typeof n==`object`&&!Array.isArray(e)&&!Array.isArray(n)?nK(e,n):null;case`-`:if(typeof e==`number`&&typeof n==`number`)return e-n;if(Array.isArray(e)&&Array.isArray(n)){let t=new Set(n.map(e=>JSON.stringify(e)));return e.filter(e=>!t.has(JSON.stringify(e)))}if(typeof e==`string`&&typeof n==`string`){let t=e=>e.length>10?`"${e.slice(0,10)}...`:JSON.stringify(e);throw Error(`string (${t(e)}) and string (${t(n)}) cannot be subtracted`)}return null;case`*`:if(typeof e==`number`&&typeof n==`number`)return e*n;if(typeof e==`string`&&typeof n==`number`){if(!Number.isFinite(n))throw Error(`invalid string repetition count: ${n}`);let t=Math.trunc(n);if(t<0)return null;let r=V(e),a=i.limits.maxStringLength;if(r>0&&t>Math.floor(a/r))throw new H(`string size limit exceeded (${a} bytes)`,`string_length`);return e.repeat(t)}{let t=eK(e),r=eK(n);if(t&&r)return Ywe(t,r,{maxDepth:i.limits.maxDepth,visit:()=>iQ(i)})}return null;case`/`:if(typeof e==`number`&&typeof n==`number`){if(n===0)throw Error(`number (${e}) and number (${n}) cannot be divided because the divisor is zero`);return e/n}return typeof e==`string`&&typeof n==`string`?e.split(n):null;case`%`:if(typeof e==`number`&&typeof n==`number`){if(n===0)throw Error(`number (${e}) and number (${n}) cannot be divided (remainder) because the divisor is zero`);return!Number.isFinite(e)&&!Number.isNaN(e)?!Number.isFinite(n)&&!Number.isNaN(n)&&e<0&&n>0?-1:0:e%n}return null;case`==`:return LZ(e,n);case`!=`:return!LZ(e,n);case`<`:return RZ(e,n)<0;case`<=`:return RZ(e,n)<=0;case`>`:return RZ(e,n)>0;case`>=`:return RZ(e,n)>=0;default:return null}}))}function mQ(e,t,n,r){let i=xQ.get(t);if(i)return typeof e==`number`?[i(e)]:[null];let a=nTe(e,t,n,r,Y);if(a!==null)return a;let o=mTe(e,t,n,r,Y);if(o!==null)return o;let s=qwe(e,t,n,r,Y);if(s!==null)return s;let c=Qwe(e,t,r.limits.maxDepth);if(c!==null)return c;let l=gTe(e,t);if(l!==null)return l;let u=sTe(e,t,n,r,Y);if(u!==null)return u;let d=Uwe(e,t,n,r,Y,fQ,BZ,IZ,VZ,H);if(d!==null)return d;let f=lTe(e,t,n,r,Y,IZ,tQ,nQ,wTe,hQ);if(f!==null)return f;let p=eTe(e,t,n,r,Y,LZ);if(p!==null)return p;let m=Gwe(e,t,n,r,Y,fQ,IZ,H);if(m!==null)return m;let h=iTe(e,t,n,r,Y,IZ,xTe,mQ);if(h!==null)return h;let g=dTe(e,t,n,r,Y,LZ);if(g!==null)return g;switch(t){case`builtins`:return[`add/0.all/0.all/1.all/2.any/0.any/1.any/2.arrays/0.ascii/0.ascii_downcase/0.ascii_upcase/0.booleans/0.bsearch/1.builtins/0.combinations/0.combinations/1.contains/1.debug/0.del/1.delpaths/1.empty/0.env/0.error/0.error/1.explode/0.first/0.first/1.flatten/0.flatten/1.floor/0.from_entries/0.fromdate/0.fromjson/0.getpath/1.gmtime/0.group_by/1.gsub/2.gsub/3.has/1.implode/0.IN/1.IN/2.INDEX/1.INDEX/2.index/1.indices/1.infinite/0.inside/1.isempty/1.isnan/0.isnormal/0.isvalid/1.iterables/0.join/1.keys/0.keys_unsorted/0.last/0.last/1.length/0.limit/2.ltrimstr/1.map/1.map_values/1.match/1.match/2.max/0.max_by/1.min/0.min_by/1.mktime/0.modulemeta/1.nan/0.not/0.nth/1.nth/2.null/0.nulls/0.numbers/0.objects/0.path/1.paths/0.paths/1.pick/1.range/1.range/2.range/3.recurse/0.recurse/1.recurse_down/0.repeat/1.reverse/0.rindex/1.rtrimstr/1.scalars/0.scan/1.scan/2.select/1.setpath/2.skip/2.sort/0.sort_by/1.split/1.splits/1.splits/2.sqrt/0.startswith/1.strftime/1.strings/0.strptime/1.sub/2.sub/3.test/1.test/2.to_entries/0.toboolean/0.todate/0.tojson/0.tostream/0.fromstream/1.truncate_stream/1.tonumber/0.tostring/0.transpose/0.trim/0.ltrim/0.rtrim/0.type/0.unique/0.unique_by/1.until/2.utf8bytelength/0.values/0.walk/1.while/2.with_entries/1`.split(`.`)];case`error`:{let t=n.length>0?Y(e,n[0],r)[0]:e;throw new _Q(t)}case`env`:return[r.env?QK(r.env):Object.create(null)];case`debug`:return[e];case`input_line_number`:return[1];default:{let i=`${t}/${n.length}`,a=r.funcs?.get(i);if(a){let t=a.closure??r.funcs??new Map,o=new Map(t);o.set(i,a);for(let t=0;t=0;e--)n={type:`Comma`,left:{type:`Literal`,value:t[e]},right:n}}o.set(`${i}/0`,{params:[],body:n})}}let s={...r,funcs:o};return Y(e,a.body,s)}throw Error(`Unknown function: ${t}`)}}}function hQ(e,t,n,r,i){if(iQ(n),r.length>n.limits.maxDepth)throw rQ(`query depth limit exceeded (${n.limits.maxDepth})`,`recursion`);let a=e=>{if(e.length>n.limits.maxDepth)throw rQ(`query depth limit exceeded (${n.limits.maxDepth})`,`recursion`);aQ(n,i.length),i.push(e)};if(t.type===`Comma`){let a=t;hQ(e,a.left,n,r,i),hQ(e,a.right,n,r,i);return}let o=uQ(t);if(o!==null){a([...r,...o]);return}if(t.type===`Iterate`){if(Array.isArray(e))for(let t=0;t0;){let e=t.pop();if(!e)break;if(iQ(n),a([...r,...e.path]),e.value&&typeof e.value==`object`){let r=Array.isArray(e.value)?e.value.map((e,t)=>[t,e]):Object.keys(e.value).map(t=>[t,e.value[t]]);aQ(n,0,t.length+r.length);for(let n=r.length-1;n>=0;n--){let[i,a]=r[n];t.push({value:a,path:[...e.path,i]})}}}return}if(t.type===`Pipe`){let a=uQ(t.left);if(a!==null){let o=Y(e,t.left,n);for(let e of o)hQ(e,t.right,n,[...r,...a],i);return}}Y(e,t,n).length>0&&a(r)}var gQ,_Q,vQ,yQ,bQ,xQ,SQ=B(()=>{sH(),tq(),U(),AK(),XB(),vTe(),yTe(),iK(),HZ(),gQ=class e extends Error{label;partialResults;constructor(e,t=[]){super(`break ${e}`),this.label=e,this.partialResults=t,this.name=`BreakError`}withPrependedResults(t){return new e(this.label,[...t,...this.partialResults])}},_Q=class extends Error{value;constructor(e){super(typeof e==`string`?e:JSON.stringify(e)),this.value=e,this.name=`JqError`}},vQ=1e4,yQ=10485760,bQ=2e3,xQ=new Map([[`floor`,Math.floor],[`ceil`,Math.ceil],[`round`,Math.round],[`sqrt`,Math.sqrt],[`log`,Math.log],[`log10`,Math.log10],[`log2`,Math.log2],[`exp`,Math.exp],[`sin`,Math.sin],[`cos`,Math.cos],[`tan`,Math.tan],[`asin`,Math.asin],[`acos`,Math.acos],[`atan`,Math.atan],[`sinh`,Math.sinh],[`cosh`,Math.cosh],[`tanh`,Math.tanh],[`asinh`,Math.asinh],[`acosh`,Math.acosh],[`atanh`,Math.atanh],[`cbrt`,Math.cbrt],[`expm1`,Math.expm1],[`log1p`,Math.log1p],[`trunc`,Math.trunc]])});function CQ(e){let t=[],n=0,r=(t=0)=>e[n+t],i=()=>e[n++],a=()=>n>=e.length,o=e=>e>=`0`&&e<=`9`,s=e=>e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`_`,c=e=>s(e)||o(e);for(;!a();){let l=n,u=i();if(u!==` `&&u!==` `&&u!==` +`&&u!==`\r`){if(u===`#`){for(;!a()&&r()!==` +`;)i();continue}if(u===`.`&&r()===`.`){i(),t.push({type:`DOTDOT`,pos:l});continue}if(u===`=`&&r()===`=`){i(),t.push({type:`EQ`,pos:l});continue}if(u===`!`&&r()===`=`){i(),t.push({type:`NE`,pos:l});continue}if(u===`<`&&r()===`=`){i(),t.push({type:`LE`,pos:l});continue}if(u===`>`&&r()===`=`){i(),t.push({type:`GE`,pos:l});continue}if(u===`/`&&r()===`/`){i(),r()===`=`?(i(),t.push({type:`UPDATE_ALT`,pos:l})):t.push({type:`ALT`,pos:l});continue}if(u===`+`&&r()===`=`){i(),t.push({type:`UPDATE_ADD`,pos:l});continue}if(u===`-`&&r()===`=`){i(),t.push({type:`UPDATE_SUB`,pos:l});continue}if(u===`*`&&r()===`=`){i(),t.push({type:`UPDATE_MUL`,pos:l});continue}if(u===`/`&&r()===`=`){i(),t.push({type:`UPDATE_DIV`,pos:l});continue}if(u===`%`&&r()===`=`){i(),t.push({type:`UPDATE_MOD`,pos:l});continue}if(u===`=`&&r()!==`=`){t.push({type:`ASSIGN`,pos:l});continue}if(u===`.`){t.push({type:`DOT`,pos:l});continue}if(u===`|`){r()===`=`?(i(),t.push({type:`UPDATE_PIPE`,pos:l})):t.push({type:`PIPE`,pos:l});continue}if(u===`,`){t.push({type:`COMMA`,pos:l});continue}if(u===`:`){t.push({type:`COLON`,pos:l});continue}if(u===`;`){t.push({type:`SEMICOLON`,pos:l});continue}if(u===`(`){t.push({type:`LPAREN`,pos:l});continue}if(u===`)`){t.push({type:`RPAREN`,pos:l});continue}if(u===`[`){t.push({type:`LBRACKET`,pos:l});continue}if(u===`]`){t.push({type:`RBRACKET`,pos:l});continue}if(u===`{`){t.push({type:`LBRACE`,pos:l});continue}if(u===`}`){t.push({type:`RBRACE`,pos:l});continue}if(u===`?`){t.push({type:`QUESTION`,pos:l});continue}if(u===`+`){t.push({type:`PLUS`,pos:l});continue}if(u===`-`){t.push({type:`MINUS`,pos:l});continue}if(u===`*`){t.push({type:`STAR`,pos:l});continue}if(u===`/`){t.push({type:`SLASH`,pos:l});continue}if(u===`%`){t.push({type:`PERCENT`,pos:l});continue}if(u===`<`){t.push({type:`LT`,pos:l});continue}if(u===`>`){t.push({type:`GT`,pos:l});continue}if(o(u)){let s=u;for(;!a()&&(o(r())||r()===`.`||r()===`e`||r()===`E`);)(r()===`e`||r()===`E`)&&(e[n+1]===`+`||e[n+1]===`-`)&&(s+=i()),s+=i();t.push({type:`NUMBER`,value:Number(s),pos:l});continue}if(u===`"`){let e=``,n=0;for(;!a();){let t=r();if(n===0&&t===`"`)break;if(n===0&&t===`\\`){if(i(),a())break;let t=i();switch(t){case`n`:e+=` +`;break;case`r`:e+=`\r`;break;case`t`:e+=` `;break;case`\\`:e+=`\\`;break;case`"`:e+=`"`;break;case`(`:e+=`\\(`,n=1;break;default:e+=t}continue}if(n>0){if(t===`"`){for(e+=i();!a();){let t=r();if(t===`\\`){e+=i(),a()||(e+=i());continue}if(e+=i(),t===`"`)break}continue}t===`(`?n++:t===`)`&&n--,e+=i();continue}e+=i()}a()||i(),t.push({type:`STRING`,value:e,pos:l});continue}if(s(u)||u===`$`||u===`@`){let e=u;for(;!a()&&c(r());)e+=i();let n=wQ.get(e);n?t.push({type:n,value:e,pos:l}):t.push({type:`IDENT`,value:e,pos:l});continue}throw Error(`Unexpected character '${u}' at position ${l}`)}}return t.push({type:`EOF`,pos:n}),t}function ETe(e,t={}){let n=t.maxDepth??256,r=t.maxTokens??1e5,i=t.maxSourceLength??1048576;if(e.length>i)throw Error(`query source length limit exceeded (${i} characters)`);if(e.length+1>r)throw Error(`query token limit exceeded (${r})`);let a=CQ(e);return new EQ(a,n).parse()}var wQ,TQ,EQ,DTe=B(()=>{wQ=new Map([[`and`,`AND`],[`or`,`OR`],[`not`,`NOT`],[`if`,`IF`],[`then`,`THEN`],[`elif`,`ELIF`],[`else`,`ELSE`],[`end`,`END`],[`as`,`AS`],[`try`,`TRY`],[`catch`,`CATCH`],[`true`,`TRUE`],[`false`,`FALSE`],[`null`,`NULL`],[`reduce`,`REDUCE`],[`foreach`,`FOREACH`],[`label`,`LABEL`],[`break`,`BREAK`],[`def`,`DEF`]]),TQ=new Set(wQ.values()),EQ=class e{maxDepth;tokens;pos=0;depth;constructor(e,t,n=0){this.maxDepth=t,this.tokens=e,this.depth=n}peek(e=0){return this.tokens[this.pos+e]??{type:`EOF`,pos:-1}}advance(){return this.tokens[this.pos++]}check(e){return this.peek().type===e}match(...e){for(let t of e)if(this.check(t))return this.advance();return null}expect(e,t){if(!this.check(e))throw Error(`${t} at position ${this.peek().pos}, got ${this.peek().type}`);return this.advance()}withDepth(e){if(this.depth++,this.depth>this.maxDepth)throw this.depth--,Error(`query parse depth limit exceeded (${this.maxDepth})`);try{return e()}finally{this.depth--}}isFieldNameAfterDot(e=0){let t=this.peek(e),n=this.peek(e+1);return n.type===`STRING`?!0:n.type===`IDENT`||TQ.has(n.type)?n.pos===t.pos+1:!1}isIdentLike(){let e=this.peek().type;return e===`IDENT`||TQ.has(e)}consumeFieldNameAfterDot(e){let t=this.peek();return t.type===`STRING`||(t.type===`IDENT`||TQ.has(t.type))&&t.pos===e.pos+1?this.advance().value:null}parse(){let e=this.parseExpr();if(!this.check(`EOF`))throw Error(`Unexpected token ${this.peek().type} at position ${this.peek().pos}`);return e}parseExpr(){if(this.depth++,this.depth>this.maxDepth)throw this.depth--,Error(`query parse depth limit exceeded (${this.maxDepth})`);try{return this.parsePipe()}finally{this.depth--}}parsePattern(){if(this.depth++,this.depth>this.maxDepth)throw this.depth--,Error(`query parse depth limit exceeded (${this.maxDepth})`);try{return this.parsePatternInner()}finally{this.depth--}}parsePatternInner(){if(this.match(`LBRACKET`)){let e=[];if(!this.check(`RBRACKET`))for(e.push(this.parsePattern());this.match(`COMMA`)&&!this.check(`RBRACKET`);)e.push(this.parsePattern());return this.expect(`RBRACKET`,`Expected ']' after array pattern`),{type:`array`,elements:e}}if(this.match(`LBRACE`)){let e=[];if(!this.check(`RBRACE`))for(e.push(this.parsePatternField());this.match(`COMMA`)&&!this.check(`RBRACE`);)e.push(this.parsePatternField());return this.expect(`RBRACE`,`Expected '}' after object pattern`),{type:`object`,fields:e}}let e=this.expect(`IDENT`,`Expected variable name in pattern`),t=e.value;if(!t.startsWith(`$`))throw Error(`Variable name must start with $ at position ${e.pos}`);return{type:`var`,name:t}}parsePatternField(){if(this.match(`LPAREN`)){let e=this.parseExpr();return this.expect(`RPAREN`,`Expected ')' after computed key`),this.expect(`COLON`,`Expected ':' after computed key`),{key:e,pattern:this.parsePattern()}}let e=this.peek();if(e.type===`IDENT`||TQ.has(e.type)){let t=e.value;if(t.startsWith(`$`)){if(this.advance(),this.match(`COLON`)){let e=this.parsePattern();return{key:t.slice(1),pattern:e,keyVar:t}}return{key:t.slice(1),pattern:{type:`var`,name:t}}}return this.advance(),this.match(`COLON`)?{key:t,pattern:this.parsePattern()}:{key:t,pattern:{type:`var`,name:`$${t}`}}}throw Error(`Expected field name in object pattern at position ${e.pos}`)}parsePipe(){let e=this.parseComma();for(;this.match(`PIPE`);){let t=this.parseComma();e={type:`Pipe`,left:e,right:t}}return e}parseComma(){let e=this.parseVarBind();for(;this.match(`COMMA`);){let t=this.parseVarBind();e={type:`Comma`,left:e,right:t}}return e}parseVarBind(){let e=this.parseUpdate();if(this.match(`AS`)){let t=this.parsePattern(),n=[];for(;this.check(`QUESTION`)&&this.peekAhead(1)?.type===`ALT`;)this.advance(),this.advance(),n.push(this.parsePattern());this.expect(`PIPE`,`Expected '|' after variable binding`);let r=this.parseExpr();return t.type===`var`&&n.length===0?{type:`VarBind`,name:t.name,value:e,body:r}:{type:`VarBind`,name:t.type===`var`?t.name:``,value:e,body:r,pattern:t.type===`var`?void 0:t,alternatives:n.length>0?n:void 0}}return e}peekAhead(e){let t=this.pos+e;return tthis.parseVarBind()),i=t.get(n.type);if(i)return{type:`UpdateOp`,op:i,path:e,value:r}}return e}parseAlt(){let e=this.parseOr();for(;this.match(`ALT`);){let t=this.parseOr();e={type:`BinaryOp`,op:`//`,left:e,right:t}}return e}parseOr(){let e=this.parseAnd();for(;this.match(`OR`);){let t=this.parseAnd();e={type:`BinaryOp`,op:`or`,left:e,right:t}}return e}parseAnd(){let e=this.parseNot();for(;this.match(`AND`);){let t=this.parseNot();e={type:`BinaryOp`,op:`and`,left:e,right:t}}return e}parseNot(){return this.parseComparison()}parseComparison(){let e=this.parseAddSub(),t=new Map([[`EQ`,`==`],[`NE`,`!=`],[`LT`,`<`],[`LE`,`<=`],[`GT`,`>`],[`GE`,`>=`]]),n=this.match(`EQ`,`NE`,`LT`,`LE`,`GT`,`GE`);if(n){let r=t.get(n.type);if(r){let t=this.parseAddSub();e={type:`BinaryOp`,op:r,left:e,right:t}}}return e}parseAddSub(){let e=this.parseMulDiv();for(;;)if(this.match(`PLUS`)){let t=this.parseMulDiv();e={type:`BinaryOp`,op:`+`,left:e,right:t}}else if(this.match(`MINUS`)){let t=this.parseMulDiv();e={type:`BinaryOp`,op:`-`,left:e,right:t}}else break;return e}parseMulDiv(){let e=this.parseUnary();for(;;)if(this.match(`STAR`)){let t=this.parseUnary();e={type:`BinaryOp`,op:`*`,left:e,right:t}}else if(this.match(`SLASH`)){let t=this.parseUnary();e={type:`BinaryOp`,op:`/`,left:e,right:t}}else if(this.match(`PERCENT`)){let t=this.parseUnary();e={type:`BinaryOp`,op:`%`,left:e,right:t}}else break;return e}parseUnary(){let e=0;for(;this.match(`MINUS`);)if(e++,this.depth+e>this.maxDepth)throw Error(`query parse depth limit exceeded (${this.maxDepth})`);let t=this.parsePostfix();for(;e-->0;)t={type:`UnaryOp`,op:`-`,operand:t};return t}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.match(`QUESTION`))e={type:`Optional`,expr:e};else if(this.check(`DOT`)&&this.isFieldNameAfterDot())this.advance(),e={type:`Field`,name:this.advance().value,base:e};else if(this.check(`LBRACKET`)){if(this.advance(),this.match(`RBRACKET`))e={type:`Iterate`,base:e};else if(this.check(`COLON`)){this.advance();let t=this.check(`RBRACKET`)?void 0:this.parseExpr();this.expect(`RBRACKET`,`Expected ']'`),e={type:`Slice`,end:t,base:e}}else{let t=this.parseExpr();if(this.match(`COLON`)){let n=this.check(`RBRACKET`)?void 0:this.parseExpr();this.expect(`RBRACKET`,`Expected ']'`),e={type:`Slice`,start:t,end:n,base:e}}else this.expect(`RBRACKET`,`Expected ']'`),e={type:`Index`,index:t,base:e}}}else break;return e}parsePrimary(){if(this.match(`DOTDOT`))return{type:`Recurse`};if(this.check(`DOT`)){let e=this.advance();if(this.check(`LBRACKET`)){if(this.advance(),this.match(`RBRACKET`))return{type:`Iterate`};if(this.check(`COLON`)){this.advance();let e=this.check(`RBRACKET`)?void 0:this.parseExpr();return this.expect(`RBRACKET`,`Expected ']'`),{type:`Slice`,end:e}}let e=this.parseExpr();if(this.match(`COLON`)){let t=this.check(`RBRACKET`)?void 0:this.parseExpr();return this.expect(`RBRACKET`,`Expected ']'`),{type:`Slice`,start:e,end:t}}return this.expect(`RBRACKET`,`Expected ']'`),{type:`Index`,index:e}}let t=this.consumeFieldNameAfterDot(e);return t===null?{type:`Identity`}:{type:`Field`,name:t}}if(this.match(`TRUE`))return{type:`Literal`,value:!0};if(this.match(`FALSE`))return{type:`Literal`,value:!1};if(this.match(`NULL`))return{type:`Literal`,value:null};if(this.check(`NUMBER`))return{type:`Literal`,value:this.advance().value};if(this.check(`STRING`)){let e=this.advance().value;return e.includes(`\\(`)?this.parseStringInterpolation(e):{type:`Literal`,value:e}}if(this.match(`LBRACKET`)){if(this.match(`RBRACKET`))return{type:`Array`};let e=this.parseExpr();return this.expect(`RBRACKET`,`Expected ']'`),{type:`Array`,elements:e}}if(this.match(`LBRACE`))return this.parseObjectConstruction();if(this.match(`LPAREN`)){let e=this.parseExpr();return this.expect(`RPAREN`,`Expected ')'`),{type:`Paren`,expr:e}}if(this.match(`IF`))return this.parseIf();if(this.match(`TRY`)){let e=this.withDepth(()=>this.parsePostfix()),t;return this.match(`CATCH`)&&(t=this.withDepth(()=>this.parsePostfix())),{type:`Try`,body:e,catch:t}}if(this.match(`REDUCE`)){let e=this.parseAddSub();this.expect(`AS`,`Expected 'as' after reduce expression`);let t=this.parsePattern();this.expect(`LPAREN`,`Expected '(' after variable`);let n=this.parseExpr();this.expect(`SEMICOLON`,`Expected ';' after init expression`);let r=this.parseExpr();return this.expect(`RPAREN`,`Expected ')' after update expression`),{type:`Reduce`,expr:e,varName:t.type===`var`?t.name:``,init:n,update:r,pattern:t.type===`var`?void 0:t}}if(this.match(`FOREACH`)){let e=this.parseAddSub();this.expect(`AS`,`Expected 'as' after foreach expression`);let t=this.parsePattern();this.expect(`LPAREN`,`Expected '(' after variable`);let n=this.parseExpr();this.expect(`SEMICOLON`,`Expected ';' after init expression`);let r=this.parseExpr(),i;return this.match(`SEMICOLON`)&&(i=this.parseExpr()),this.expect(`RPAREN`,`Expected ')' after expressions`),{type:`Foreach`,expr:e,varName:t.type===`var`?t.name:``,init:n,update:r,extract:i,pattern:t.type===`var`?void 0:t}}if(this.match(`LABEL`)){let e=this.expect(`IDENT`,`Expected label name (e.g., $out)`),t=e.value;if(!t.startsWith(`$`))throw Error(`Label name must start with $ at position ${e.pos}`);return this.expect(`PIPE`,`Expected '|' after label name`),{type:`Label`,name:t,body:this.parseExpr()}}if(this.match(`BREAK`)){let e=this.expect(`IDENT`,`Expected label name to break to`),t=e.value;if(!t.startsWith(`$`))throw Error(`Break label must start with $ at position ${e.pos}`);return{type:`Break`,name:t}}if(this.match(`DEF`)){let e=this.expect(`IDENT`,`Expected function name after def`).value,t=[];if(this.match(`LPAREN`)){if(!this.check(`RPAREN`)){let e=this.expect(`IDENT`,`Expected parameter name`);for(t.push(e.value);this.match(`SEMICOLON`);){let e=this.expect(`IDENT`,`Expected parameter name`);t.push(e.value)}}this.expect(`RPAREN`,`Expected ')' after parameters`)}this.expect(`COLON`,`Expected ':' after function name`);let n=this.parseExpr();return this.expect(`SEMICOLON`,`Expected ';' after function body`),{type:`Def`,name:e,params:t,funcBody:n,body:this.parseExpr()}}if(this.match(`NOT`))return{type:`Call`,name:`not`,args:[]};if(this.check(`IDENT`)){let e=this.advance().value;if(e.startsWith(`$`))return{type:`VarRef`,name:e};if(this.match(`LPAREN`)){let t=[];if(!this.check(`RPAREN`))for(t.push(this.parseExpr());this.match(`SEMICOLON`);)t.push(this.parseExpr());return this.expect(`RPAREN`,`Expected ')'`),{type:`Call`,name:e,args:t}}return{type:`Call`,name:e,args:[]}}throw Error(`Unexpected token ${this.peek().type} at position ${this.peek().pos}`)}parseObjectConstruction(){if(this.depth++,this.depth>this.maxDepth)throw this.depth--,Error(`query parse depth limit exceeded (${this.maxDepth})`);try{return this.parseObjectConstructionInner()}finally{this.depth--}}parseObjectConstructionInner(){let e=[];if(!this.check(`RBRACE`))do{let t,n;if(this.match(`LPAREN`))t=this.parseExpr(),this.expect(`RPAREN`,`Expected ')'`),this.expect(`COLON`,`Expected ':'`),n=this.parseObjectValue();else if(this.isIdentLike()){let e=this.advance().value;this.match(`COLON`)?(t=e,n=this.parseObjectValue()):(t=e,n={type:`Field`,name:e})}else if(this.check(`STRING`))t=this.advance().value,this.expect(`COLON`,`Expected ':'`),n=this.parseObjectValue();else throw Error(`Expected object key at position ${this.peek().pos}`);e.push({key:t,value:n})}while(this.match(`COMMA`));return this.expect(`RBRACE`,`Expected '}'`),{type:`Object`,entries:e}}parseObjectValue(){let e=this.parseVarBind();for(;this.match(`PIPE`);){let t=this.parseVarBind();e={type:`Pipe`,left:e,right:t}}return e}parseIf(){let e=this.parseExpr();this.expect(`THEN`,`Expected 'then'`);let t=this.parseExpr(),n=[];for(;this.match(`ELIF`);){let e=this.parseExpr();this.expect(`THEN`,`Expected 'then' after elif`);let t=this.parseExpr();n.push({cond:e,then:t})}let r;return this.match(`ELSE`)&&(r=this.parseExpr()),this.expect(`END`,`Expected 'end'`),{type:`Cond`,cond:e,then:t,elifs:n,else:r}}parseStringInterpolation(t){let n=[],r=``,i=0;for(;i0;){let e=t[i];if(e===`"`){for(o+=e,i++;i0&&(o+=e),i++}let s=CQ(o),c=new e(s,this.maxDepth,this.depth);n.push(c.parse())}else r+=t[i],i++;return r&&n.push(r),{type:`StringInterp`,parts:n}}}}),OTe=B(()=>{SQ(),DTe()});function kTe(e,t,n={}){let r=new oH(t,`query JSON output`,()=>new H(`output size limit exceeded (${t} bytes)`,n.limitKind??`output_size`));return DQ(r,e,n,0),r.build()}function DQ(e,t,n,r){if(t==null){e.append(`null`);return}if(typeof t==`boolean`){e.append(String(t));return}if(typeof t==`number`){e.append(Number.isFinite(t)?String(t):`null`);return}if(typeof t==`string`){n.raw&&r===0?e.append(t):OQ(e,t);return}let i=n.compact??!1,a=n.indent??2,o=n.useTab?` `:` `.repeat(a);if(Array.isArray(t)){e.append(`[`);for(let a=0;a0&&e.append(` +`).repeat(o,r),e.append(`]`);return}let s=Object.keys(t);n.sortKeys&&(s=s.sort()),e.append(`{`);for(let a=0;a0&&e.append(` +`).repeat(o,r),e.append(`}`)}function OQ(e,t){e.append(`"`);let n=0;for(let r=0;r{sH(),U()}),kQ={};wz(kQ,{flagsForFuzzing:()=>FQ,jqCommand:()=>PQ});function jTe(e){switch(e){case`\b`:return`\\b`;case`\f`:return`\\f`;case` +`:return`\\n`;case`\r`:return`\\r`;case` `:return`\\t`;default:return`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`}}function MTe(e){let t=``,n=!1,r=!1;for(let i=0;i{if(n.length>=t.maxElements)throw new H(`query result element limit exceeded (${t.maxElements})`,`array_elements`);n.push(e)},i=0,a=e.length;for(;i=a)break;let n=i,o=e[i];if(o===`{`||o===`[`){let s=[o===`{`?`}`:`]`],c=!1,l=!1;for(i++;i0;){let n=e[i];if(l)l=!1;else if(n===`\\`)l=!0;else if(n===`"`)c=!c;else if(!c){if(n===`{`||n===`[`){if(s.push(n===`{`?`}`:`]`),s.length>t.maxDepth)throw new H(`query depth limit exceeded (${t.maxDepth})`,`recursion`)}else if((n===`}`||n===`]`)&&s.pop()!==n)throw Error(`Mismatched JSON delimiter at position ${i}`)}i++}if(s.length!==0)throw Error(`Unexpected end of JSON input at position ${i} (unclosed ${o})`);r($G(AQ(e,n,i),{maxDepth:t.maxDepth,maxElements:t.maxElements}))}else if(o===`"`){let o=!1;for(i++;i=`0`&&o<=`9`){for(;i{kB(),vH(),U(),AK(),aB(),mV(),sV(),XB(),OTe(),ATe(),iK(),HZ(),NQ={name:`jq`,summary:`command-line JSON processor`,usage:`jq [OPTIONS] FILTER [FILE...]`,options:[`-R, --raw-input read each line as string instead of JSON`,`-r, --raw-output output strings without quotes`,`-c, --compact-output compact instead of pretty-printed output`,`-e, --exit-status set exit status based on output`,`-s, --slurp read entire input into array`,`-n, --null-input don't read any input`,`-j, --join-output don't print newlines after each output`,`-a, --ascii force ASCII output`,`-S, --sort-keys sort object keys`,`-C, --color colorize output (ignored)`,`-M, --monochrome monochrome output (ignored)`,` --tab use tabs for indentation`,` --arg NAME VALUE bind $NAME to the string VALUE`,` --argjson NAME JSON bind $NAME to the JSON-decoded value JSON`,` --rawfile NAME FILE bind $NAME to the raw contents of FILE`,` --slurpfile NAME FILE bind $NAME to the array of JSON values in FILE`,` --args remaining arguments are string positional args ($ARGS.positional)`,` --jsonargs remaining arguments are JSON positional args ($ARGS.positional)`,` --help display this help and exit`]},PQ={name:`jq`,async execute(e,t){OK(t.requireDefenseContext,`jq`,`execution entry`);let n=(e,n)=>kK(t.requireDefenseContext,`jq`,e,n);if(aV(e))return iV(NQ);let r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=!1,f=`.`,p=!1,m=`none`,h=[],g=new Map,_=[],v=[],y={maxDepth:t.limits.maxQueryDepth,maxElements:t.limits.maxQueryElements};for(let t=0;t0){let e=await n(`arg file read`,()=>fV(t,v.map(e=>e.file),{cmdName:`jq`,stopOnError:!0}));if(e.exitCode!==0)return{stdout:``,stderr:e.stderr,exitCode:2};for(let t=0;tfV(t,h,{cmdName:`jq`,stopOnError:!0}));if(e.exitCode!==0)return{stdout:``,stderr:e.stderr,exitCode:2};b=e.files.map(e=>({source:e.filename||`stdin`,content:vB(e.content)}))}}try{let e=ETe(f,{maxDepth:t.limits.maxQueryDepth,maxTokens:t.limits.maxQueryTokens,maxSourceLength:t.limits.maxStringLength}),n=[],p={limits:t.limits?{maxIterations:t.limits.maxJqIterations,maxStringLength:t.limits.maxStringLength,maxOutputSize:t.limits.maxOutputSize,maxArrayElements:t.limits.maxQueryElements,maxDepth:t.limits.maxQueryDepth}:void 0,env:t.env,namedArgs:g,positionalArgs:_,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext,budget:{operations:0,callDepth:0}},m=(e,n)=>{if(n.length>t.limits.maxQueryElements-e.length)throw new H(`query result element limit exceeded (${t.limits.maxQueryElements})`,`array_elements`);for(let t of n)e.push(t)};if(c)n=Y(null,e,p);else if(i&&s)n=Y(b.map(({content:e})=>e).join(``),e,p);else if(i){let t=``;for(let{content:r}of b){let i=t+r,a=0,o=i.indexOf(` +`,a);for(;o!==-1;)m(n,Y(i.slice(a,o),e,p)),a=o+1,o=i.indexOf(` +`,a);t=i.slice(a)}t!==``&&m(n,Y(t,e,p))}else if(s){let t=[];for(let{content:e}of b){let n=e.trim();n&&m(t,jQ(n,y))}n=Y(t,e,p)}else for(let{content:t}of b){let r=t.trim();if(!r)continue;let i=jQ(r,y);for(let t of i)m(n,Y(t,e,p))}let h=l?``:` +`,v=Math.min(t.limits.maxStringLength,t.limits.maxOutputSize),x=[],S=0;for(let e of n){let n=x.length>0?h.length:0,i=+!l,o=v-S-n-i;if(o<0)throw new H(`output size limit exceeded (${v} bytes)`,`string_length`);if(zZ(e,t.limits.maxQueryDepth+1)>t.limits.maxQueryDepth)throw new H(`query depth limit exceeded (${t.limits.maxQueryDepth})`,`recursion`);let s=kTe(e,o,{compact:a,raw:r,sortKeys:u,useTab:d,limitKind:`string_length`}),c=V(s);if(S+n+c+i>v)throw new H(`output size limit exceeded (${v} bytes)`,`string_length`);S+=n+c,x.push(s)}let C=x.join(h),w=o&&(n.length===0||n.every(e=>e==null||e===!1))?1:0;return{stdout:C?l?C:`${C} +`:``,stderr:``,exitCode:w}}catch(e){if(e instanceof eB)throw e;if(e instanceof H)return{stdout:``,stderr:`jq: ${_H(e.message)} +`,exitCode:H.EXIT_CODE};let t=_H(e.message);return t.includes(`Unknown function`)?{stdout:``,stderr:`jq: error: ${t} +`,exitCode:3}:{stdout:``,stderr:`jq: parse error: ${t} +`,exitCode:5}}}},FQ={name:`jq`,flags:[{flag:`-R`,type:`boolean`},{flag:`-r`,type:`boolean`},{flag:`-c`,type:`boolean`},{flag:`-e`,type:`boolean`},{flag:`-s`,type:`boolean`},{flag:`-n`,type:`boolean`},{flag:`-j`,type:`boolean`},{flag:`-S`,type:`boolean`},{flag:`--tab`,type:`boolean`}],stdinType:`json`,needsArgs:!0}}),IQ={};wz(IQ,{base64Command:()=>UQ,flagsForFuzzing:()=>WQ});function LQ(e,t,n,r){if(e>t)throw new H(`base64: ${n} limit exceeded (${t} bytes)`,r)}function RQ(e){let t=[];for(let n=0;ne.charCodeAt(0))};let a=[],o=0;for(let s of t){if(s===`-`){LQ(o+i.length,r,`input size`,`string_length`),a.push(Uint8Array.from(i,e=>e.charCodeAt(0))),o+=i.length;continue}try{let t=e.fs.resolvePath(e.cwd,s),i=await e.fs.stat(t);LQ(o+i.size,r,`input size`,`string_length`);let c=await e.fs.readFileBuffer(t);LQ(o+c.length,r,`input size`,`string_length`),dV(e,c.length,n),a.push(c),o+=c.length}catch(e){return nV(e),{ok:!1,error:{stdout:``,stderr:`${n}: ${s}: No such file or directory +`,exitCode:1}}}}let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.length;return{ok:!0,data:s}}var VQ,HQ,UQ,WQ,PTe=B(()=>{kB(),rV(),U(),lV(),mV(),sV(),VQ={name:`base64`,summary:`base64 encode/decode data and print to standard output`,usage:`base64 [OPTION]... [FILE]`,options:[`-d, --decode decode data`,`-w, --wrap=COLS wrap encoded lines after COLS character (default 76, 0 to disable)`,` --help display this help and exit`]},HQ={decode:{short:`d`,long:`decode`,type:`boolean`},wrap:{short:`w`,long:`wrap`,type:`number`,default:76}},UQ={name:`base64`,async execute(e,t){if(aV(e))return iV(VQ);let n=cV(`base64`,e,HQ);if(!n.ok)return n.error;let r=n.result.flags.decode,i=n.result.flags.wrap,a=n.result.positional;if(!Number.isSafeInteger(i)||i<0)return{stdout:``,stderr:`base64: invalid wrap size +`,exitCode:1};try{if(r){let e=await BQ(t,a,`base64`);if(!e.ok)return e.error;if(typeof Buffer<`u`){let n=Buffer.from(e.data).toString(`utf8`).replace(/\s/g,``),r=zQ(n);LQ(r,t.limits.maxStringLength,`decoded size`,`string_length`),LQ(r,t.limits.maxOutputSize,`output size`,`output_size`);let i=Buffer.from(n,`base64`);return LQ(i.length,t.limits.maxOutputSize,`output size`,`output_size`),{stdout:i.toString(`latin1`),stderr:``,exitCode:0,stdoutEncoding:`binary`}}let n=RQ(e.data).replace(/\s/g,``),r=zQ(n);LQ(r,t.limits.maxStringLength,`decoded size`,`string_length`),LQ(r,t.limits.maxOutputSize,`output size`,`output_size`);let i=atob(n);return LQ(i.length,t.limits.maxOutputSize,`output size`,`output_size`),{stdout:i,stderr:``,exitCode:0,stdoutEncoding:`binary`}}let e=await BQ(t,a,`base64`);if(!e.ok)return e.error;let n=Math.ceil(e.data.length/3)*4,o=i>0&&n>0?Math.ceil(n/i):0;if(o>t.limits.maxArrayElements)throw new H(`base64: wrapped line limit exceeded (${t.limits.maxArrayElements})`,`array_elements`);LQ(n,t.limits.maxStringLength,`encoded size`,`string_length`),LQ(n+o,t.limits.maxOutputSize,`output size`,`output_size`);let s;if(s=typeof Buffer<`u`?Buffer.from(e.data).toString(`base64`):btoa(RQ(e.data)),i>0){let e=[];for(let t=0;t0?` +`:``)}return{stdout:s,stderr:``,exitCode:0}}catch(e){return nV(e),{stdout:``,stderr:`base64: invalid input +`,exitCode:1}}}},WQ={name:`base64`,flags:[{flag:`-d`,type:`boolean`},{flag:`-w`,type:`value`,valueHint:`number`}],stdinType:`text`,needsFiles:!0}}),GQ={};wz(GQ,{diffCommand:()=>JQ,flagsForFuzzing:()=>YQ});var KQ,qQ,JQ,YQ,FTe=B(()=>{kB(),lV(),sV(),KQ={name:`diff`,summary:`compare files line by line`,usage:`diff [OPTION]... FILE1 FILE2`,options:[`-u, --unified output unified diff format (default)`,`-q, --brief report only whether files differ`,`-s, --report-identical-files report when files are the same`,`-i, --ignore-case ignore case differences`,` --help display this help and exit`]},qQ={unified:{short:`u`,long:`unified`,type:`boolean`},brief:{short:`q`,long:`brief`,type:`boolean`},reportSame:{short:`s`,long:`report-identical-files`,type:`boolean`},ignoreCase:{short:`i`,long:`ignore-case`,type:`boolean`}},JQ={name:`diff`,async execute(e,t){if(aV(e))return iV(KQ);let n=cV(`diff`,e,qQ);if(!n.ok)return n.error;let r=n.result.flags.brief,i=n.result.flags.reportSame,a=n.result.flags.ignoreCase,o=n.result.positional;if(n.result.flags.unified,o.length<2)return{stdout:``,stderr:`diff: missing operand +`,exitCode:2};let s,c,[l,u]=o;try{s=l===`-`?vB(t.stdin):await t.fs.readFile(t.fs.resolvePath(t.cwd,l))}catch{return{stdout:``,stderr:`diff: ${l}: No such file or directory +`,exitCode:2}}try{c=u===`-`?vB(t.stdin):await t.fs.readFile(t.fs.resolvePath(t.cwd,u))}catch{return{stdout:``,stderr:`diff: ${u}: No such file or directory +`,exitCode:2}}let d=s,f=c;return a&&(d=d.toLowerCase(),f=f.toLowerCase()),d===f?i?{stdout:`Files ${l} and ${u} are identical +`,stderr:``,exitCode:0}:{stdout:``,stderr:``,exitCode:0}:r?{stdout:`Files ${l} and ${u} differ +`,stderr:``,exitCode:1}:{stdout:wle(l,u,s,c,``,``,{context:3}),stderr:``,exitCode:1}}},YQ={name:`diff`,flags:[{flag:`-u`,type:`boolean`},{flag:`-q`,type:`boolean`},{flag:`-s`,type:`boolean`},{flag:`-i`,type:`boolean`}],needsArgs:!0,minArgs:2}}),XQ={};wz(XQ,{dateCommand:()=>QQ,flagsForFuzzing:()=>$Q});function ITe(e){try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}function LTe(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e),r=e=>n.find(t=>t.type===e)?.value??`00`,i=Number.parseInt(r(`hour`),10)%24,a=new Date(`${r(`year`)}-${r(`month`)}-${r(`day`)}T${String(i).padStart(2,`0`)}:${r(`minute`)}:${r(`second`)}Z`);return Number.isNaN(a.getTime())?null:a}function RTe(e,t){let n=e.match(/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?$/);if(!n)return null;let[,r,i,a,o=`00`,s=`00`,c=`00`]=n,l=new Date(`${r}-${i}-${a}T${o}:${s}:${c}Z`);if(Number.isNaN(l.getTime()))return null;try{let e=l;for(let n=0;n<3;n++){let n=LTe(e,t);if(n===null)return null;let r=n.getTime()-l.getTime();if(r===0)return e;e=new Date(e.getTime()-r)}return e}catch{return null}}function zTe(e,t){if(e.startsWith(`@`)){let t=e.slice(1);if(!/^-?\d+$/.test(t))return null;let n=Number(t);if(!Number.isSafeInteger(n))return null;let r=new Date(n*1e3);return Number.isNaN(r.getTime())?null:r}let n=e.toLowerCase().trim();if(n===`now`||n===`today`)return new Date;if(n===`yesterday`)return new Date(Date.now()-864e5);if(n===`tomorrow`)return new Date(Date.now()+864e5);if(t&&!/Z$/i.test(e)&&!/[+-]\d{2}:?\d{2}$/.test(e)){let n=RTe(e,t);if(n)return n}let r=new Date(e);return Number.isNaN(r.getTime())?null:r}var ZQ,QQ,$Q,BTe=B(()=>{sV(),FV(),ZQ={name:`date`,summary:`display the current time in the given FORMAT`,usage:`date [OPTION]... [+FORMAT]`,options:[`-d, --date=STRING display time described by STRING, not 'now'`,`-u, --utc print Coordinated Universal Time (UTC)`,`-I, --iso-8601 output date/time in ISO 8601 format`,`-R, --rfc-email output RFC 5322 date format`,` --help display this help and exit`]},QQ={name:`date`,async execute(e,t){if(aV(e))return iV(ZQ);let n=!1,r=null,i=null,a=!1,o=!1;for(let t=0;t{}),n$={};wz(n$,{flagsForFuzzing:()=>o$,sleepCommand:()=>a$});var r$,i$,a$,o$,VTe=B(()=>{mB(),t$(),sV(),r$={name:`sleep`,summary:`delay for a specified amount of time`,usage:`sleep NUMBER[SUFFIX]`,description:`Pause for NUMBER seconds. SUFFIX may be: + s - seconds (default) + m - minutes + h - hours + d - days + +NUMBER may be a decimal number.`,options:[` --help display this help and exit`]},i$=36e5,a$={name:`sleep`,async execute(e,t){if(aV(e))return iV(r$);if(e.length===0)return{stdout:``,stderr:`sleep: missing operand +`,exitCode:1};let n=0;for(let t of e){let e=e$(t);if(e===null)return{stdout:``,stderr:`sleep: invalid time interval '${t}' +`,exitCode:1};n+=e}if(n>i$&&(n=i$),t.signal?.aborted)return{stdout:``,stderr:``,exitCode:0};if(t.sleep){let e=Promise.resolve(t.sleep(n));if(t.signal){let n,r=new Promise(e=>{n=e,t.signal?.addEventListener(`abort`,n,{once:!0}),t.signal?.aborted&&e()});try{await Promise.race([e,r])}finally{n&&t.signal.removeEventListener(`abort`,n)}}else await e}else t.signal?await new Promise(e=>{let r=()=>{fB(i),e()},i=dB(()=>{t.signal?.removeEventListener(`abort`,r),e()},n);t.signal?.addEventListener(`abort`,r,{once:!0})}):await new Promise(e=>dB(e,n));return{stdout:``,stderr:``,exitCode:0}}},o$={name:`sleep`,flags:[],needsArgs:!0}}),s$={};wz(s$,{flagsForFuzzing:()=>u$,timeoutCommand:()=>l$});var c$,l$,u$,HTe=B(()=>{gB(),kB(),mK(),mB(),t$(),sV(),c$={name:`timeout`,summary:`run a command with a time limit`,usage:`timeout [OPTION] DURATION COMMAND [ARG]...`,description:`Start COMMAND, and kill it if still running after DURATION. + +DURATION is a number with optional suffix: + s - seconds (default) + m - minutes + h - hours + d - days`,options:[`-k, --kill-after=DURATION send KILL signal after DURATION if still running`,`-s, --signal=SIGNAL specify signal to send (default: TERM)`,` --preserve-status exit with same status as COMMAND, even on timeout`,` --foreground run command in foreground`,` --help display this help and exit`]},l$={name:`timeout`,async execute(e,t){if(aV(e))return iV(c$);let n=0;for(let t=0;t1&&r!==`--`){if(r.startsWith(`-k`))n=t+1;else if(r.startsWith(`-s`))n=t+1;else return oV(`timeout`,r)}else{n=t;break}}}let r=e.slice(n);if(r.length===0)return{stdout:``,stderr:`timeout: missing operand +`,exitCode:1};let i=r[0],a=e$(i);if(a===null)return{stdout:``,stderr:`timeout: invalid time interval '${i}' +`,exitCode:1};let o=r.slice(1);if(o.length===0)return{stdout:``,stderr:`timeout: missing operand +`,exitCode:1};if(!t.exec)return{stdout:``,stderr:`timeout: exec not available +`,exitCode:1};let s=new AbortController,c=hB(t.signal,s.signal),l,u;try{let e=new Promise(e=>{u=()=>e({timedOut:!0}),c.signal?.addEventListener(`abort`,u,{once:!0}),l=dB(()=>{s.abort()},a)}),n=t.exec(pK([o[0]]),{cwd:t.cwd,signal:c.signal,stdin:t.stdin,stdinKind:`bytes`,args:o.slice(1)}).then(e=>({timedOut:!1,result:e})),r=await Promise.race([e,n]);return r.timedOut?(await n.catch(()=>{}),{stdout:``,stderr:``,exitCode:124}):r.result}finally{l!==void 0&&fB(l),u&&c.signal?.removeEventListener(`abort`,u),c.cleanup()}}},u$={name:`timeout`,flags:[{flag:`-k`,type:`value`,valueHint:`string`},{flag:`-s`,type:`value`,valueHint:`string`},{flag:`--preserve-status`,type:`boolean`},{flag:`--foreground`,type:`boolean`}],needsArgs:!0,minArgs:2}}),d$,f$,p$,m$=B(()=>{globalThis.SharedArrayBuffer,globalThis.Atomics,d$=performance.now.bind(performance),f$=globalThis.Headers,p$=globalThis.Proxy}),h$={};wz(h$,{flagsForFuzzing:()=>_$,timeCommand:()=>g$});function UTe(e){let t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=e%60;return t>0?`${t}:${n.toString().padStart(2,`0`)}:${r.toFixed(2).padStart(5,`0`)}`:`${n}:${r.toFixed(2).padStart(5,`0`)}`}var g$,_$,WTe=B(()=>{kB(),vH(),tq(),mK(),m$(),g$={name:`time`,async execute(e,t){let n=`%e %M`,r=null,i=!1,a=!1,o=0;for(;o=e.length)return{stdout:``,stderr:`time: missing argument to '-f' +`,exitCode:1};n=e[o],o++}else if(t===`-o`||t===`--output`){if(o++,o>=e.length)return{stdout:``,stderr:`time: missing argument to '-o' +`,exitCode:1};r=e[o],o++}else if(t===`-a`||t===`--append`)i=!0,o++;else if(t===`-v`||t===`--verbose`)n=`Command being timed: %C +Elapsed (wall clock) time: %e seconds +Maximum resident set size (kbytes): %M`,o++;else if(t===`-p`||t===`--portability`)a=!0,o++;else if(t===`--`){o++;break}else if(t.startsWith(`-`))o++;else break}let s=e.slice(o);if(s.length===0)return{stdout:``,stderr:``,exitCode:0};let c=d$(),l=s.join(` `),u;try{if(!t.exec)return{stdout:``,stderr:`time: exec not available +`,exitCode:1};u=await t.exec(pK([s[0]]),{env:QK(t.env),cwd:t.cwd,stdin:t.stdin,stdinKind:`bytes`,signal:t.signal,args:s.slice(1)})}catch(e){u={stdout:``,stderr:`time: ${_H(e.message)} +`,exitCode:127}}let d=(d$()-c)/1e3,f;if(a?f=`real ${d.toFixed(2)} +user 0.00 +sys 0.00 +`:(f=n.replace(/%e/g,d.toFixed(2)).replace(/%E/g,UTe(d)).replace(/%M/g,`0`).replace(/%S/g,`0.00`).replace(/%U/g,`0.00`).replace(/%P/g,`0%`).replace(/%C/g,l),f.endsWith(` +`)||(f+=` +`)),r)try{let e=t.fs.resolvePath(t.cwd,r);if(i&&await t.fs.exists(e)){let n=await t.fs.readFile(e);await t.fs.writeFile(e,n+f)}else await t.fs.writeFile(e,f)}catch(e){let t=_H(e.message);return{stdout:u.stdout,stderr:u.stderr+`time: cannot write to '${r}': ${t} +`,exitCode:u.exitCode}}else u={...u,stderr:u.stderr+f};return u}},_$={name:`time`,flags:[{flag:`-p`,type:`boolean`}],needsArgs:!0}}),v$={};wz(v$,{flagsForFuzzing:()=>b$,seqCommand:()=>y$});var y$,b$,GTe=B(()=>{sH(),kB(),U(),y$={name:`seq`,async execute(e,t){let n=` +`,r=!1,i=[],a=0;for(;a2){n=t.slice(2),a++;continue}if((t===`-ws`||t===`-sw`)&&(r=!0,a+1!Number.isFinite(parseFloat(e)))}' +`,exitCode:1};if(s===0)return{stdout:``,stderr:`seq: invalid Zero increment value: '0' +`,exitCode:1};let l=[],u=e=>{let t=String(e),n=t.indexOf(`.`);return n===-1?0:t.length-n-1},d=Math.max(u(o),u(s),u(c)),f=Math.min(t.limits.maxLoopIterations,t.limits.maxArrayElements),p=Math.min(t.limits.maxOutputSize,t.limits.maxStringLength),m=V(n),h=0,g=0,_=e=>{if(g>=f)throw new H(`seq: iteration limit exceeded (${f})`,`iterations`);let t=rH(rH(h,l.length>0?m:0,`seq`),rH(V(e),1,`seq`),`seq`);if(t>p)throw new H(`seq: output size limit exceeded (${p} bytes)`,`output_size`);h=t-1,l.push(e),g++};if(s>0)for(let e=o;e<=c+1e-10;e+=s)_(d>0?e.toFixed(d):String(Math.round(e)));else for(let e=o;e>=c-1e-10;e+=s)_(d>0?e.toFixed(d):String(Math.round(e)));if(r&&l.length>0){let e=0;for(let t of l)e=Math.max(e,t.startsWith(`-`)?t.length-1:t.length);if(rH(rH(l.reduce((t,n)=>rH(t,e+ +!!n.startsWith(`-`),`seq`),0),iH(m,Math.max(0,l.length-1),`seq`),`seq`),1,`seq`)>p)throw new H(`seq: output size limit exceeded (${p} bytes)`,`output_size`);for(let t=0;tS$,flagsForFuzzing:()=>C$});function KTe(e,t){if(e.length===1)return e[0];let n=0;function r(){let t=i();for(;n`,`<=`,`>=`].includes(r)){n++;let e=o(),i=parseInt(t,10),a=parseInt(e,10),s=!Number.isNaN(i)&&!Number.isNaN(a),c;c=r===`=`?s?i===a:t===e:r===`!=`?s?i!==a:t!==e:r===`<`?s?i`?s?i>a:t>e:r===`<=`?s?i<=a:t<=e:s?i>=a:t>=e,t=c?`1`:`0`}else break}return t}function o(){let t=s();for(;n=e.length)throw Error(`syntax error`);let i=e[n];if(i===`match`){n++;let e=l(),t=mG(l()).match(e);return t?t[1]===void 0?String(t[0].length):t[1]:`0`}if(i===`substr`){n++;let e=l(),t=parseInt(l(),10),r=parseInt(l(),10);if(Number.isNaN(t)||Number.isNaN(r))throw Error(`non-integer argument`);return e.substring(t-1,t-1+r)}if(i===`index`){n++;let e=l(),r=l();t(r.length+e.length);let i=new Set;for(let e=0;e=e.length||e[n]!==`)`)throw Error(`syntax error`);return n++,t}return n++,i}let u=r();if(n!==e.length)throw Error(`syntax error`);return u}var S$,C$,qTe=B(()=>{rV(),vH(),yG(),S$={name:`expr`,async execute(e,t){if(e.length===0)return{stdout:``,stderr:`expr: missing operand +`,exitCode:2};try{let n=KTe(e,e=>t.executionScope?.consumeWork(e,`expr index`)),r=+(n===`0`||n===``);return{stdout:`${n} +`,stderr:``,exitCode:r}}catch(e){return nV(e),{stdout:``,stderr:`expr: ${_H(e.message)} +`,exitCode:2}}}},C$={name:`expr`,flags:[],needsArgs:!0}});function JTe(e){function t(e,t){return e<>>32-t}let n=new Uint32Array([3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955,4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690,4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745]),r=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],i=e.length*8,a=(e.length%64<56?56:120)-e.length%64,o=new Uint8Array(e.length+a+8);o.set(e),o[e.length]=128;let s=new DataView(o.buffer);s.setUint32(o.length-8,i>>>0,!0),s.setUint32(o.length-4,Math.floor(i/4294967296),!0);let c=1732584193,l=4023233417,u=2562383102,d=271733878;for(let e=0;e>>0,a=p,p=f,f=o,o=o+t(s,r[e])>>>0}c=c+a>>>0,l=l+o>>>0,u=u+f>>>0,d=d+p>>>0}let f=new Uint8Array(16);return new DataView(f.buffer).setUint32(0,c,!0),new DataView(f.buffer).setUint32(4,l,!0),new DataView(f.buffer).setUint32(8,u,!0),new DataView(f.buffer).setUint32(12,d,!0),Array.from(f).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function w$(e,t){if(e===`md5`)return JTe(t);let n=E$.get(e);if(!n)throw Error(`Unknown algorithm: ${e}`);let r=await globalThis.crypto.subtle.digest(n,new Uint8Array(t).buffer);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function T$(e,t,n){let r={name:e,summary:n,usage:`${e} [OPTION]... [FILE]...`,options:[`-c, --check read checksums from FILEs and check them`,` --help display this help and exit`]};return{name:e,async execute(n,i){if(aV(n))return iV(r);let a=!1,o=[];for(let t of n)if(t===`-c`||t===`--check`)a=!0;else if(t!==`-b`&&t!==`-t`&&t!==`--binary`&&t!==`--text`){if(t.startsWith(`-`)&&t!==`-`)return oV(e,t);o.push(t)}o.length===0&&o.push(`-`);let s=async e=>{if(e===`-`)return Uint8Array.from(i.stdin,e=>e.charCodeAt(0));try{return await i.fs.readFileBuffer(i.fs.resolvePath(i.cwd,e))}catch{return null}};if(a){let n=0,r=``;for(let a of o){let o=a===`-`?vB(i.stdin):await i.fs.readFile(i.fs.resolvePath(i.cwd,a)).catch(()=>null);if(o===null)return{stdout:``,stderr:`${e}: ${a}: No such file or directory +`,exitCode:1};for(let e of o.split(` +`)){let i=e.match(/^([a-fA-F0-9]+)\s+[* ]?(.+)$/);if(!i)continue;let[,a,o]=i,c=await s(o);if(c===null){r+=`${o}: FAILED open or read +`,n++;continue}let l=await w$(t,c)===a.toLowerCase();r+=`${o}: ${l?`OK`:`FAILED`} +`,l||n++}}return n>0&&(r+=`${e}: WARNING: ${n} computed checksum${n>1?`s`:``} did NOT match +`),{stdout:r,stderr:``,exitCode:+(n>0)}}let c=``,l=0;for(let n of o){let r=await s(n);if(r===null){c+=`${e}: ${n}: No such file or directory +`,l=1;continue}c+=`${await w$(t,r)} ${n} +`}return{stdout:c,stderr:``,exitCode:l}}}}var E$,D$=B(()=>{kB(),sV(),E$=new Map([[`sha1`,`SHA-1`],[`sha256`,`SHA-256`]])}),O$={};wz(O$,{flagsForFuzzing:()=>A$,md5sumCommand:()=>k$});var k$,A$,YTe=B(()=>{D$(),k$=T$(`md5sum`,`md5`,`compute MD5 message digest`),A$={name:`md5sum`,flags:[{flag:`-c`,type:`boolean`}],needsFiles:!0}}),j$={};wz(j$,{flagsForFuzzing:()=>N$,sha1sumCommand:()=>M$});var M$,N$,XTe=B(()=>{D$(),M$=T$(`sha1sum`,`sha1`,`compute SHA1 message digest`),N$={name:`sha1sum`,flags:[{flag:`-c`,type:`boolean`}],needsFiles:!0}}),P$={};wz(P$,{flagsForFuzzing:()=>I$,sha256sumCommand:()=>F$});var F$,I$,ZTe=B(()=>{D$(),F$=T$(`sha256sum`,`sha256`,`compute SHA256 message digest`),I$={name:`sha256sum`,flags:[{flag:`-c`,type:`boolean`}],needsFiles:!0}}),QTe=Cz(e=>{e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else{if(a===c)return o?NaN:1/0*(p?-1:1);o+=2**r,a-=l}return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}});function $Te(){if(!(typeof globalThis.TextDecoder>`u`))return sEe??=new globalThis.TextDecoder(`utf-8`)}function eEe(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=$Te();return t?t.decode(e):nEe(e)}case`utf-16le`:return rEe(e);case`us-ascii`:case`ascii`:return iEe(e);case`latin1`:case`iso-8859-1`:return aEe(e);case`windows-1252`:return oEe(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function L$(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function R$(e,t,n){t.push(n),t.length>=V$&&L$(e,t)}function tEe(e,t,n){if(n<=65535){R$(e,t,n);return}n-=65536,R$(e,t,55296+(n>>10)),R$(e,t,56320+(n&1023))}function nEe(e){let t=[],n=[],r=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(r=3);r244){R$(t,n,H$),r++;continue}if(i<=223){if(r+1>=e.length){R$(t,n,H$),r++;continue}let a=e[r+1];if((a&192)!=128){R$(t,n,H$),r++;continue}R$(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){R$(t,n,H$),r++;continue}let a=e[r+1],o=e[r+2];if((a&192)!=128||(o&192)!=128||i===224&&a<160||i===237&&a>=160){R$(t,n,H$),r++;continue}R$(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){R$(t,n,H$),r++;continue}let a=e[r+1],o=e[r+2],s=e[r+3];if((a&192)!=128||(o&192)!=128||(s&192)!=128||i===240&&a<144||i===244&&a>143){R$(t,n,H$),r++;continue}tEe(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return L$(t,n),t.join(``)}function rEe(e){let t=[],n=[],r=e.length,i=0;for(;i+1=55296&&a<=56319){if(i+1=56320&&r<=57343?(R$(t,n,a),R$(t,n,r),i+=2):R$(t,n,H$)}else R$(t,n,H$);continue}if(a>=56320&&a<=57343){R$(t,n,H$);continue}R$(t,n,a)}return i=128&&i<=159?z$[i]:void 0;n+=a??String.fromCharCode(i),n.length>=V$&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}var z$,B$,sEe,V$,H$,cEe=B(()=>{z$={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},B$={};for(let[e,t]of Object.entries(z$))B$[t]=Number.parseInt(e,10);V$=32768,H$=65533});function U$(e){return new DataView(e.buffer,e.byteOffset)}var W$,G$,K$,q$,J$,Y$,X$,Z$,Q$=B(()=>{Ez(QTe(),1),cEe(),W$={len:1,get(e,t){return U$(e).getUint8(t)},put(e,t,n){return U$(e).setUint8(t,n),t+1}},G$={len:2,get(e,t){return U$(e).getUint16(t,!0)},put(e,t,n){return U$(e).setUint16(t,n,!0),t+2}},K$={len:2,get(e,t){return U$(e).getUint16(t)},put(e,t,n){return U$(e).setUint16(t,n),t+2}},q$={len:4,get(e,t){return U$(e).getUint32(t,!0)},put(e,t,n){return U$(e).setUint32(t,n,!0),t+4}},J$={len:4,get(e,t){return U$(e).getUint32(t)},put(e,t,n){return U$(e).setUint32(t,n),t+4}},Y$={len:4,get(e,t){return U$(e).getInt32(t)},put(e,t,n){return U$(e).setInt32(t,n),t+4}},X$={len:8,get(e,t){return U$(e).getBigUint64(t,!0)},put(e,t,n){return U$(e).setBigUint64(t,n,!0),t+8}},Z$=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return eEe(e.subarray(t,t+this.len),this.encoding)}}}),$$,e1,t1,n1=B(()=>{$$=`End-Of-Stream`,e1=class extends Error{constructor(){super($$),this.name=`EndOfStreamError`}},t1=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}}}),lEe=B(()=>{}),r1,i1=B(()=>{n1(),r1=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new e1;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i{n1(),lEe(),i1()}),a1,dEe=B(()=>{i1(),a1=class extends r1{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}}),o1,s1=B(()=>{dEe(),o1=class extends a1{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}}}),c1,l1=B(()=>{n1(),i1(),c1=class extends r1{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),this.buffer=n{s1(),l1()}),u1=B(()=>{n1(),uEe(),s1(),l1(),pEe()}),d1,f1=B(()=>{u1(),d1=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position{f1(),u1(),p1=256e3,m1=class extends d1{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof e1)return 0;throw e}if(!n.mayBeLess&&r{u1(),f1(),h1=class extends d1{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r{u1(),f1(),g1=class extends d1{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&r{if(await n.close(),i)return i()},new m1(n,r)}function vEe(e,t){return new h1(e,t)}function yEe(e,t){return new g1(e,t)}var bEe=B(()=>{u1(),mEe(),hEe(),gEe(),u1(),f1()}),xEe=Cz((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}}),SEe=Cz((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=xEe(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(typeof t>`u`?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n}),CEe=Cz((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t={}.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=SEe()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}}),_1,v1,y1,b1,x1,wEe=B(()=>{Q$(),_1={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},v1={get(e){return{signature:q$.get(e,0),compressedSize:q$.get(e,8),uncompressedSize:q$.get(e,12)}},len:16},y1={get(e){let t=G$.get(e,6);return{signature:q$.get(e,0),minVersion:G$.get(e,4),dataDescriptor:!!(t&8),compressedMethod:G$.get(e,8),compressedSize:q$.get(e,18),uncompressedSize:q$.get(e,22),filenameLength:G$.get(e,26),extraFieldLength:G$.get(e,28),filename:null}},len:30},b1={get(e){return{signature:q$.get(e,0),nrOfThisDisk:G$.get(e,4),nrOfThisDiskWithTheStart:G$.get(e,6),nrOfEntriesOnThisDisk:G$.get(e,8),nrOfEntriesOfSize:G$.get(e,10),sizeOfCd:q$.get(e,12),offsetOfStartOfCd:q$.get(e,16),zipFileCommentLength:G$.get(e,20)}},len:22},x1={get(e){let t=G$.get(e,8);return{signature:q$.get(e,0),minVersion:G$.get(e,6),dataDescriptor:!!(t&8),compressedMethod:G$.get(e,10),compressedSize:q$.get(e,20),uncompressedSize:q$.get(e,24),filenameLength:G$.get(e,28),extraFieldLength:G$.get(e,30),fileCommentLength:G$.get(e,32),relativeOffsetOfLocalHeader:q$.get(e,42),filename:null}},len:46}});function S1(e){let t=new Uint8Array(q$.len);return q$.put(t,0,e),t}function TEe(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;ae+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var C1,w1,T1,E1,D1,O1,DEe=B(()=>{Q$(),C1=Ez(CEe(),1),wEe(),w1=(0,C1.default)(`tokenizer:inflate`),T1=262144,E1=S1(_1.DataDescriptor),D1=S1(_1.EndOfCentralDirectory),O1=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(T1)}async isZip(){return await this.peekSignature()===_1.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(q$)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16384,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===D1[0]&&n[r+1]===D1[1]&&n[r+2]===D1[2]&&n[r+3]===D1[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){w1(`Cannot reading central-directory without random-read support`);return}w1(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){w1(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(b1,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}w1(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,EEe(e),r.handler)}else r.handler?(w1(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(w1(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(w1(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(v1)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-v1.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}async inflate(t,n,r){if(t.compressedMethod===0)return r(n);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return w1(`Decompress filename=${t.filename}, compressed-size=${n.length}`),r(await e.decompressDeflateRaw(n))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),n=new DecompressionStream(`deflate-raw`),r=t.pipeThrough(n);try{let e=await new Response(r).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(q$);if(e===_1.LocalFileHeader){let e=await this.tokenizer.readToken(y1);return e.filename=await this.tokenizer.readToken(new Z$(e.filenameLength,`utf-8`)),e}if(e===_1.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}}}),k1,OEe=B(()=>{k1=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),r=await e.readBuffer(n,{mayBeLess:!0});if(r===0){t.close();return}t.enqueue(n.subarray(0,r))}}).pipeThrough(new DecompressionStream(`gzip`))}}}),kEe=B(()=>{DEe(),OEe()});function A1(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}var AEe=B(()=>{new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`))});function jEe(e,t){if(t===`utf-16le`){let t=[];for(let n=0;n>8&255)}return t}if(t===`utf-16be`){let t=[];for(let n=0;n>8&255,r&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function MEe(e,t=0){let n=Number.parseInt(new Z$(6).get(e,148).replace(/\0.*$/,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n{Q$(),j1={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4}}),M1,N1,PEe=B(()=>{M1=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat`.split(`,`),N1=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/x-lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x.ms.shortcut,application/x.apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x.autodesk.fbx,application/vnd.visio,application/vnd.android.package-archive,application/vnd.google.draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data`.split(`,`)});function FEe(e){let t=e?.streamReader;if(t?.constructor?.name!==`WebStreamByobReader`)return e;let{reader:n}=t,r=async()=>{await n.cancel(),n.releaseLock()};return t.close=r,t.abort=async()=>{t.interrupted=!0,await r()},e}function P1(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new g0(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function F1(e,t,{maximumLength:n=J1,reason:r=`skip`}={}){let i=P1(t,n,r);await e.ignore(i)}async function I1(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=P1(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}async function IEe(e,{maximumLength:t=G1}={}){let n=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),r=[],i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.length,i>t)throw await n.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);r.push(a)}}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.length;return a}function LEe(e,t){if(e.length=0?0:s===i?Math.min(y0,s-1):0,u=c>=0?c:s-l;if(u===0)break;if(o+=u,o>n)throw Error(`ZIP entry compressed data exceeds ${n} bytes`);if(t){let t=new Uint8Array(u);await e.tokenizer.readBuffer(t),a.push(t)}else await e.tokenizer.ignore(u);if(c>=0)break}if(z1(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return zEe(a,o)}function VEe(e,t){return z1(e.tokenizer)?Math.max(0,J1-(e.tokenizer.position-t)):Math.max(0,G1-e.knownSizeDescriptorScannedBytes)}async function HEe(e,t,{shouldBuffer:n,maximumDescriptorLength:r=G1}={}){if(t.dataDescriptor&&t.compressedSize===0)return BEe(e,{shouldBuffer:n,maximumLength:r});if(!n){await F1(e.tokenizer,t.compressedSize,{maximumLength:z1(e.tokenizer)?G1:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=YEe(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>i)throw Error(`ZIP entry compressed data exceeds ${i} bytes`);let a=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(a),a}function UEe(e,t){let n=e.getReader(),r=0,i=!1,a=!1,o=async e=>{i||a||(a=!0,await n.cancel(e))};return new ReadableStream({async pull(e){if(r>=t){e.close(),await o();return}let{done:a,value:s}=await n.read();if(a||!s){i=!0,e.close();return}let c=t-r;if(s.length>c){e.enqueue(s.subarray(0,c)),r+=c,e.close(),await o();return}e.enqueue(s),r+=s.length},async cancel(e){await o(e)}})}async function WEe(e,t){return new b0(t).fromBuffer(e)}function L1(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`}}}function R1(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}function GEe(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):U1}function KEe(e,t,n){return n===void 0?e.read(t):(n.throwIfAborted(),new Promise((r,i)=>{let a=()=>{n.removeEventListener(`abort`,o)},o=()=>{let t=n.reason;a(),(async()=>{try{await e.cancel(t)}catch{}})(),i(t)};n.addEventListener(`abort`,o,{once:!0}),(async()=>{try{let n=await e.read(t);a(),r(n)}catch(e){a(),i(e)}})()}))}function qEe(e){return Number.isFinite(e)?Math.max(0,Math.min(W1,Math.trunc(e))):0}function JEe(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function z1(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function B1(e,t,n){return z1(e)&&e.position-t>n}function YEe(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,q1)}function XEe(e){if(e instanceof e1||e instanceof g0)return!0;if(!(e instanceof Error))return!1;if(p0.has(e.message)||h0.has(e.code))return!0;for(let t of m0)if(e.message.startsWith(t))return!0;return!1}function V1(e,t=G1){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function ZEe(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function QEe(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function H1(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry)){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}}function $Ee(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let n=e.slice(0,t),r=n.lastIndexOf(`"`);return n.slice(r+1)}var U1,W1,G1,K1,q1,J1,Y1,X1,Z1,Q1,$1,e0,t0,n0,r0,i0,a0,o0,s0,c0,l0,u0,d0,f0,p0,m0,h0,g0,_0,v0,y0,b0,eDe=B(()=>{Q$(),bEe(),kEe(),AEe(),NEe(),PEe(),U1=4100,W1=U1-2,G1=1048576,K1=1024,q1=2**31-1,J1=16777216,Y1=G1,X1=G1,Z1=J1,Q1=1,$1=100,e0=J1,t0=64,n0=Y1,r0=256,i0=512,a0=J1,o0=512,s0=512,c0=256,l0=Y1,u0=Y1,d0=Y1,f0=J1,p0=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),m0=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],h0=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]),g0=class extends Error{},_0=134695760,v0=16,y0=v0-1,O1.prototype.inflate=async function(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return n(await IEe(t,{maximumLength:G1}))},O1.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(B1(this.tokenizer,r,J1))throw new g0(`ZIP stream probing exceeds ${J1} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>K1)throw Error(`ZIP entry count exceeds ${K1}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await HEe(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(G1,VEe(this,r))});if(a.handler&&await this.inflate(i,o,a.handler),i.dataDescriptor){let e=new Uint8Array(v0);if(await this.tokenizer.readBuffer(e),q$.get(e,0)!==_0)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(B1(this.tokenizer,r,J1))throw new g0(`ZIP stream probing exceeds ${J1} bytes`)}while(!t)},b0=class e{constructor(e){let t=qEe(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return FEe(_Ee(e,this.getTokenizerOptions()))}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let t of this.detectors){let r;try{r=await t.detect(e)}catch(e){if(e instanceof e1||e instanceof g0)return;throw e}if(r)return r;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(vEe(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=yEe(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async toDetectionStream(e,t){let n=GEe(t?.sampleSize??U1),r,i,a=e.getReader({mode:`byob`});try{let{value:e,done:t}=await KEe(a,new Uint8Array(n),this.options.signal);if(i=e,!t&&e)try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof e1))throw e;r=void 0}i=e}finally{a.releaseLock()}let o=new TransformStream({async start(e){e.enqueue(i)},transform(e,t){t.enqueue(e)}}),s=e.pipeThrough(o);return s.fileType=r,s}async detectGzip(t){if(this.gzipProbeDepth>=Q1)return{ext:`gz`,mime:`application/gzip`};let n=UEe(new k1(t).inflate(),Z1),r=z1(t),i,a,o,s;if(r){let t=new AbortController;i=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${$1} ms`,`TimeoutError`))},$1),a=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),o=new e({...this.options,signal:a}),o.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{s=await(o??this).fromStream(n)}catch(e){if(e?.name===`AbortError`&&a?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(i),r||this.gzipProbeDepth--}return s?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return R1(this.buffer,e,t)}checkString(e,t){return this.check(jEe(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(U1),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,z1(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=c0?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await F1(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(j1),n=z1(e);if(!Number.isFinite(t)||t<0||n&&(t>e0||e.position+t>e0))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await F1(e,t,{maximumLength:n?e0:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof e1)return;throw e}return this.detectionReentryCount>=c0?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4])){let t,n=ZEe();try{await new O1(e).unzip(e=>{QEe(n,e.filename);let r=e.filename===`[Content_Types].xml`,i=H1(n);if(!r&&i)return t=i,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return V1(e,X1)?{async handler(e){t=L1(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,V1(e,X1)?(n.isParsingContentTypes=!0,{async handler(e){let r=$Ee(new TextDecoder(`utf-8`).decode(e));r&&(t=L1(r)),n.hasParsedContentTypesEntry=!0,n.isParsingContentTypes=!1},stop:!0}):(n.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!XEe(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0)}return t??H1(n)??{ext:`zip`,mime:`application/zip`}}if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),R1(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:R1(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:R1(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:R1(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:R1(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:R1(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/x-lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163])){async function t(){let t=await e.peekNumber(W$),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await I1(e,i,void 0,{maximumLength:i.length,reason:`EBML field`}),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:A1(i),len:A1(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>r0||B1(e,a,J1))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>t0)return;let t=P1(o.len,t0,`EBML DocType`);return(await e.readToken(new Z$(t))).replaceAll(/\00.*$/g,``)}if(z1(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>n0)||(await F1(e,o.len,{maximumLength:z1(e)?n0:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=i))return}}let i=await n(),a=e.position;switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:return}}if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(`{\\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=J$.get(this.buffer,4),t=K$.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/vnd.google.draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!`))return await e.ignore(8),await e.readToken(new Z$(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[` +`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10])){let t={ext:`png`,mime:`image/png`},n={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function r(){return{length:await e.readToken(Y$),type:await e.readToken(new Z$(4,`latin1`))}}let i=z1(e),a=e.position,o=0,s=!1;do{if(o++,o>i0||B1(e,a,a0))break;let c=e.position,l=await r();if(l.length<0)return;if(l.type===`IHDR`){if(l.length!==13)return;s=!0}switch(l.type){case`IDAT`:return t;case`acTL`:return n;default:if(!s&&l.type!==`CgBI`)return;if(i&&l.length>l0)return s&&REe(l.type)?t:void 0;try{await F1(e,l.length+4,{maximumLength:i?l0+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof g0||e instanceof e1))return t;throw e}}if(e.position<=c)break}while(e.position+8o0||B1(e,i,J1)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(R1(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(o-=await I1(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),R1(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(R1(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(r&&o>u0){t=!0;break}if(await F1(e,o,{maximumLength:r?u0:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof e1||n instanceof g0)z1(e)&&(t=!0);else throw n}return t?void 0:{ext:`asf`,mime:`application/vnd.ms-asf`}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new Z$(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.checkString(`=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x.ms.shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x.apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x.autodesk.fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:`jmp`,mime:`application/x-jmp-data`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&MEe(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254])){let e=`utf-16le`;return this.checkString(`{this.buffer=new Uint8Array(U1);let t=JEe(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?K$:G$);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`}}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?K$:G$);if(!(t>s0)&&!(z1(this.tokenizer)&&2+t*12>f0))for(let n=0;n=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(r>=8){let t=(e?K$:G$).get(this.buffer,8),n=(e?K$:G$).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(z1(this.tokenizer)&&r>d0)return t;let n=z1(this.tokenizer)?f0:this.tokenizer.fileInfo.size;try{await F1(this.tokenizer,r,{maximumLength:n,reason:`TIFF IFD offset`})}catch(e){if(e instanceof e1)return;throw e}let i;try{i=await this.readTiffIFD(e)}catch(e){if(e instanceof e1)return;throw e}return i??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}},new Set(M1),new Set(N1)}),x0={};wz(x0,{fileCommand:()=>T0,flagsForFuzzing:()=>E0});function tDe(e,t){let n=w0.get(e);if(n)return n;let[r,i]=t.split(`/`),a=i?.split(`+`)[0]?.replace(/-/g,` `)||e;switch(r){case`image`:return`${a.toUpperCase()} image data`;case`audio`:return`${a.toUpperCase()} audio`;case`video`:return`${a.toUpperCase()} video`;case`font`:return`${a} font`;case`model`:return`${a} 3D model`;case`application`:return i?.includes(`zip`)||i?.includes(`compressed`)?`${a} archive data`:i?.includes(`executable`)?`${a} executable`:`${e.toUpperCase()} data`;default:return`${e.toUpperCase()} data`}}function nDe(e){let t=e.split(`/`).pop()||e;if(t.startsWith(`.`)&&!t.includes(`.`,1))return t;let n=t.lastIndexOf(`.`);return n===-1||n===0?``:t.slice(n).toLowerCase()}function rDe(e,t){if(e.startsWith(`#!`)){let t=e.split(` +`)[0];return t.includes(`python`)?{description:`Python script, ASCII text executable`,mime:`text/x-python`}:t.includes(`node`)||t.includes(`bun`)||t.includes(`deno`)?{description:`JavaScript script, ASCII text executable`,mime:`text/javascript`}:t.includes(`bash`)?{description:`Bourne-Again shell script, ASCII text executable`,mime:`text/x-shellscript`}:t.includes(`sh`)?{description:`POSIX shell script, ASCII text executable`,mime:`text/x-shellscript`}:t.includes(`ruby`)?{description:`Ruby script, ASCII text executable`,mime:`text/x-ruby`}:t.includes(`perl`)?{description:`Perl script, ASCII text executable`,mime:`text/x-perl`}:{description:`script, ASCII text executable`,mime:`text/plain`}}let n=e.trimStart();if(n.startsWith(`127){c=!0;break}return c?{description:`UTF-8 Unicode text${a}`,mime:`text/plain; charset=utf-8`}:{description:`ASCII text${a}`,mime:`text/plain`}}async function iDe(e,t){if(t.length===0)return{description:`empty`,mime:`inode/x-empty`};let n=await WEe(t);return n?{description:tDe(n.ext,n.mime),mime:n.mime}:rDe(new TextDecoder(`utf-8`,{fatal:!1}).decode(t),e)}var S0,C0,w0,T0,E0,aDe=B(()=>{eDe(),sH(),rV(),sV(),S0={name:`file`,summary:`determine file type`,usage:`file [OPTION]... FILE...`,options:[`-b, --brief do not prepend filenames to output`,`-i, --mime output MIME type strings`,`-L, --dereference follow symlinks`,` --help display this help and exit`]},C0=new Map([[`.js`,{description:`JavaScript source`,mime:`text/javascript`}],[`.mjs`,{description:`JavaScript module`,mime:`text/javascript`}],[`.cjs`,{description:`CommonJS module`,mime:`text/javascript`}],[`.ts`,{description:`TypeScript source`,mime:`text/typescript`}],[`.tsx`,{description:`TypeScript JSX source`,mime:`text/typescript`}],[`.jsx`,{description:`JavaScript JSX source`,mime:`text/javascript`}],[`.py`,{description:`Python script`,mime:`text/x-python`}],[`.rb`,{description:`Ruby script`,mime:`text/x-ruby`}],[`.go`,{description:`Go source`,mime:`text/x-go`}],[`.rs`,{description:`Rust source`,mime:`text/x-rust`}],[`.c`,{description:`C source`,mime:`text/x-c`}],[`.h`,{description:`C header`,mime:`text/x-c`}],[`.cpp`,{description:`C++ source`,mime:`text/x-c++`}],[`.hpp`,{description:`C++ header`,mime:`text/x-c++`}],[`.java`,{description:`Java source`,mime:`text/x-java`}],[`.sh`,{description:`Bourne-Again shell script`,mime:`text/x-shellscript`}],[`.bash`,{description:`Bourne-Again shell script`,mime:`text/x-shellscript`}],[`.zsh`,{description:`Zsh shell script`,mime:`text/x-shellscript`}],[`.json`,{description:`JSON data`,mime:`application/json`}],[`.yaml`,{description:`YAML data`,mime:`text/yaml`}],[`.yml`,{description:`YAML data`,mime:`text/yaml`}],[`.xml`,{description:`XML document`,mime:`application/xml`}],[`.csv`,{description:`CSV text`,mime:`text/csv`}],[`.toml`,{description:`TOML data`,mime:`text/toml`}],[`.html`,{description:`HTML document`,mime:`text/html`}],[`.htm`,{description:`HTML document`,mime:`text/html`}],[`.css`,{description:`CSS stylesheet`,mime:`text/css`}],[`.svg`,{description:`SVG image`,mime:`image/svg+xml`}],[`.md`,{description:`Markdown document`,mime:`text/markdown`}],[`.markdown`,{description:`Markdown document`,mime:`text/markdown`}],[`.txt`,{description:`ASCII text`,mime:`text/plain`}],[`.rst`,{description:`reStructuredText`,mime:`text/x-rst`}],[`.env`,{description:`ASCII text`,mime:`text/plain`}],[`.gitignore`,{description:`ASCII text`,mime:`text/plain`}],[`.dockerignore`,{description:`ASCII text`,mime:`text/plain`}]]),w0=new Map([[`jpg`,`JPEG image data`],[`jpeg`,`JPEG image data`],[`png`,`PNG image data`],[`gif`,`GIF image data`],[`webp`,`WebP image data`],[`bmp`,`PC bitmap`],[`ico`,`MS Windows icon resource`],[`tif`,`TIFF image data`],[`tiff`,`TIFF image data`],[`psd`,`Adobe Photoshop Document`],[`avif`,`AVIF image`],[`heic`,`HEIC image`],[`heif`,`HEIF image`],[`jxl`,`JPEG XL image`],[`icns`,`Mac OS X icon`],[`svg`,`SVG Scalable Vector Graphics image`],[`pdf`,`PDF document`],[`epub`,`EPUB document`],[`mobi`,`Mobipocket E-book`],[`djvu`,`DjVu document`],[`zip`,`Zip archive data`],[`gz`,`gzip compressed data`],[`gzip`,`gzip compressed data`],[`bz2`,`bzip2 compressed data`],[`xz`,`XZ compressed data`],[`tar`,`POSIX tar archive`],[`rar`,`RAR archive data`],[`7z`,`7-zip archive data`],[`lz`,`lzip compressed data`],[`lzma`,`LZMA compressed data`],[`zst`,`Zstandard compressed data`],[`cab`,`Microsoft Cabinet archive`],[`ar`,`Unix ar archive`],[`rpm`,`RPM package`],[`deb`,`Debian binary package`],[`apk`,`Android Package`],[`dmg`,`Apple disk image`],[`iso`,`ISO 9660 CD-ROM filesystem data`],[`vhd`,`Microsoft Virtual Hard Disk`],[`vhdx`,`Microsoft Virtual Hard Disk (new format)`],[`qcow2`,`QEMU QCOW Image`],[`mp3`,`Audio file with ID3`],[`m4a`,`MPEG-4 audio`],[`aac`,`AAC audio`],[`wav`,`RIFF (little-endian) data, WAVE audio`],[`flac`,`FLAC audio bitstream data`],[`ogg`,`Ogg data`],[`oga`,`Ogg audio`],[`opus`,`Ogg Opus audio`],[`aiff`,`AIFF audio`],[`wma`,`Windows Media Audio`],[`amr`,`AMR audio`],[`mid`,`MIDI audio`],[`midi`,`MIDI audio`],[`ape`,`Monkey's Audio`],[`mp4`,`ISO Media, MPEG-4`],[`m4v`,`MPEG-4 video`],[`webm`,`WebM`],[`avi`,`RIFF (little-endian) data, AVI`],[`mov`,`ISO Media, Apple QuickTime movie`],[`mkv`,`Matroska data`],[`wmv`,`Windows Media Video`],[`flv`,`Flash Video`],[`3gp`,`3GPP multimedia`],[`3g2`,`3GPP2 multimedia`],[`ogv`,`Ogg video`],[`mts`,`MPEG transport stream`],[`m2ts`,`MPEG transport stream`],[`ts`,`MPEG transport stream`],[`mpg`,`MPEG video`],[`mpeg`,`MPEG video`],[`exe`,`PE32 executable`],[`dll`,`PE32 DLL`],[`elf`,`ELF executable`],[`mach`,`Mach-O executable`],[`wasm`,`WebAssembly (wasm) binary module`],[`dex`,`Android Dalvik executable`],[`class`,`Java class file`],[`swf`,`Adobe Flash`],[`doc`,`Microsoft Word Document`],[`docx`,`Microsoft Word 2007+ Document`],[`xls`,`Microsoft Excel Spreadsheet`],[`xlsx`,`Microsoft Excel 2007+ Spreadsheet`],[`ppt`,`Microsoft PowerPoint Presentation`],[`pptx`,`Microsoft PowerPoint 2007+ Presentation`],[`odt`,`OpenDocument Text`],[`ods`,`OpenDocument Spreadsheet`],[`odp`,`OpenDocument Presentation`],[`ttf`,`TrueType Font`],[`otf`,`OpenType Font`],[`woff`,`Web Open Font Format`],[`woff2`,`Web Open Font Format 2`],[`eot`,`Embedded OpenType font`],[`stl`,`Stereolithography CAD`],[`obj`,`Wavefront 3D Object`],[`gltf`,`GL Transmission Format`],[`glb`,`GL Transmission Format (binary)`],[`sqlite`,`SQLite 3.x database`],[`mdb`,`Microsoft Access Database`],[`xml`,`XML document`],[`json`,`JSON data`],[`macho`,`Mach-O binary`],[`ics`,`iCalendar data`],[`vcf`,`vCard data`],[`msi`,`Microsoft Installer`],[`ps`,`PostScript`],[`ai`,`Adobe Illustrator`],[`indd`,`Adobe InDesign`],[`sketch`,`Sketch design file`],[`fig`,`Figma design file`],[`xd`,`Adobe XD`],[`blend`,`Blender`],[`fbx`,`Autodesk FBX`],[`lnk`,`MS Windows shortcut`],[`alias`,`Mac OS alias`],[`torrent`,`BitTorrent file`],[`pcap`,`pcap capture file`],[`arrow`,`Apache Arrow`],[`parquet`,`Apache Parquet`]]),T0={name:`file`,async execute(e,t){if(aV(e))return iV(S0);let n=!1,r=!1,i=!1,a=[];for(let t of e)if(t.startsWith(`--`)){if(t===`--brief`)n=!0;else if(t===`--mime`||t===`--mime-type`)r=!0;else if(t===`--dereference`)i=!0;else return oV(`file`,t)}else if(t.startsWith(`-`)&&t!==`-`)for(let e of t.slice(1))if(e===`b`)n=!0;else if(e===`i`)r=!0;else if(e===`L`)i=!0;else return oV(`file`,`-${e}`);else a.push(t);if(a.length===0)return{stdout:``,stderr:`Usage: file [-bLi] FILE... +`,exitCode:1};let o=new oH(Math.min(t.limits.maxOutputSize,t.limits.maxStringLength),`file`),s=0;for(let e of a){t.executionScope?.consumeLimited(`file-operands`,1,t.limits.maxArrayElements,`file`);try{let a=t.fs.resolvePath(t.cwd,e),s=i?await t.fs.stat(a):await t.fs.lstat(a);if(s.isSymbolicLink){let i=await t.fs.readlink(a),s=r?`inode/symlink`:`symbolic link to ${i}`;o.append(n?`${s} +`:`${e}: ${s} +`);continue}if(s.isDirectory){let t=r?`inode/directory`:`directory`;o.append(n?`${t} +`:`${e}: ${t} +`);continue}let c=await t.fs.readFileBuffer(a);t.executionScope?.consumeInput(c.byteLength,`file`);let l=await iDe(e,c),u=r?l.mime:l.description;o.append(n?`${u} +`:`${e}: ${u} +`)}catch(t){nV(t),o.append(n?`cannot open +`:`${e}: cannot open (No such file or directory) +`),s=1}}return{stdout:o.build(),stderr:``,exitCode:s}}},E0={name:`file`,flags:[{flag:`-b`,type:`boolean`},{flag:`-i`,type:`boolean`},{flag:`-L`,type:`boolean`}],needsArgs:!0}}),D0={};wz(D0,{flagsForFuzzing:()=>A0,htmlToMarkdownCommand:()=>k0});var O0,k0,A0,oDe=B(()=>{kB(),rV(),U(),sV(),O0={name:`html-to-markdown`,summary:`convert HTML to Markdown (BashEnv extension)`,usage:`html-to-markdown [OPTION]... [FILE]`,description:[`Convert HTML content to Markdown format using the turndown library.`,`This is a non-standard BashEnv extension command, not available in regular bash.`,``,`Read HTML from FILE or standard input and output Markdown to standard output.`,`Commonly used with curl to convert web pages:`,` curl -s https://example.com | html-to-markdown`,``,`Supported HTML elements:`,` - Headings (h1-h6) → # Markdown headings`,` - Paragraphs (p) → Plain text with blank lines`,` - Links (a) → [text](url)`,` - Images (img) → ![alt](src)`,` - Bold/Strong → **text**`,` - Italic/Em → _text_`," - Code (code, pre) → `inline` or fenced blocks",` - Lists (ul, ol, li) → - or 1. items`,` - Blockquotes → > quoted text`,` - Horizontal rules (hr) → ---`],options:[`-b, --bullet=CHAR bullet character for unordered lists (-, +, or *)`,"-c, --code=FENCE fence style for code blocks (``` or ~~~)",`-r, --hr=STRING string for horizontal rules (default: ---)`,` --heading-style=STYLE`,` heading style: 'atx' for # headings (default),`,` 'setext' for underlined headings (h1/h2 only)`,` --help display this help and exit`],examples:[`echo '

Hello

World

' | html-to-markdown`,`html-to-markdown page.html`,`curl -s https://example.com | html-to-markdown > page.md`]},k0={name:`html-to-markdown`,async execute(e,t){if(aV(e))return iV(O0);let n=`-`,r="```",i=`---`,a=`atx`,o=[];for(let t=0;tc)throw new H(`html-to-markdown: input size limit exceeded (${c} bytes)`,`string_length`);s=vB(t.stdin)}else try{let e=t.fs.resolvePath(t.cwd,o[0]);if((await t.fs.stat(e)).size>c||(s=await t.fs.readFile(e),V(s)>c))throw new H(`html-to-markdown: input size limit exceeded (${c} bytes)`,`string_length`)}catch(e){return nV(e),{stdout:``,stderr:`html-to-markdown: ${o[0]}: No such file or directory +`,exitCode:1}}if(!s.trim())return{stdout:``,stderr:``,exitCode:0};if(![`-`,`+`,`*`].includes(n))return{stdout:``,stderr:`html-to-markdown: invalid bullet marker +`,exitCode:1};if(r!=="```"&&r!==`~~~`)return{stdout:``,stderr:`html-to-markdown: invalid code fence +`,exitCode:1};let l=0,u=t.limits.maxLoopIterations;for(let e=0;eu)throw new H(`html-to-markdown: complexity limit exceeded (${u} tags)`,`iterations`);t.executionScope?.consumeWork(l,`html-to-markdown tags`);let d=V(s),f=Math.min(t.limits.maxStringLength,t.limits.maxOutputSize);if(d>Math.floor((f-1)/4))throw new H(`html-to-markdown: prospective output size limit exceeded (${f} bytes)`,`output_size`);let p=d*4+1,m=t.executionScope?.reserveBytes(`html input`,d,`html-to-markdown`),h=t.executionScope?.reserveBytes(`html prospective output`,p,`html-to-markdown`);try{let e=new dz({bulletListMarker:n,codeBlockStyle:`fenced`,fence:r,hr:i,headingStyle:a});e.remove([`script`,`style`,`footer`]);let t=e.turndown(s).trim();if(V(t)+1>f)throw new H(`html-to-markdown: output size limit exceeded (${f} bytes)`,`output_size`);return{stdout:`${t} +`,stderr:``,exitCode:0}}catch(e){return nV(e),{stdout:``,stderr:`html-to-markdown: conversion error: ${e.message} +`,exitCode:1}}finally{h?.release(),m?.release()}}},A0={name:`html-to-markdown`,flags:[],stdinType:`text`}}),j0={};wz(j0,{flagsForFuzzing:()=>P0,helpCommand:()=>N0});function sDe(e){let t=[],n=new Set(e);t.push(`Available commands: +`);let r=[];for(let[e,r]of M0){let i=r.filter(e=>n.has(e));if(i.length>0){t.push(` ${e}:`),t.push(` ${i.join(`, `)} +`);for(let e of i)n.delete(e)}}for(let e of n)r.push(e);return r.length>0&&(t.push(` Other:`),t.push(` ${r.sort().join(`, `)} +`)),t.push(`Use ' --help' for details on a specific command.`),`${t.join(` +`)} +`}var M0,N0,P0,cDe=B(()=>{mK(),M0=new Map([[`File operations`,[`ls`,`cat`,`head`,`tail`,`wc`,`touch`,`mkdir`,`rm`,`cp`,`mv`,`ln`,`chmod`,`stat`,`readlink`]],[`Text processing`,[`grep`,`sed`,`awk`,`sort`,`uniq`,`cut`,`tr`,`tee`,`diff`]],[`Search`,[`find`]],[`Navigation & paths`,[`pwd`,`basename`,`dirname`,`tree`,`du`]],[`Environment & shell`,[`echo`,`printf`,`env`,`printenv`,`export`,`alias`,`unalias`,`history`,`clear`,`true`,`false`,`bash`,`sh`]],[`Data processing`,[`xargs`,`jq`,`base64`,`date`]],[`Network`,[`curl`,`html-to-markdown`]]]),N0={name:`help`,async execute(e,t){if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`help - display available commands + +Usage: help [command] + +Options: + -h, --help Show this help message + +If a command name is provided, shows help for that command. +Otherwise, lists all available commands. +`,stderr:``,exitCode:0};if(e.length>0&&t.exec){let n=e[0];return t.exec(pK([n]),{cwd:t.cwd,signal:t.signal,args:[`--help`]})}return{stdout:sDe(t.getRegisteredCommands?.()??[]),stderr:``,exitCode:0}}},P0={name:`help`,flags:[]}}),F0={};wz(F0,{flagsForFuzzing:()=>z0,whichCommand:()=>R0});var I0,L0,R0,z0,lDe=B(()=>{lV(),sV(),I0={name:`which`,summary:`locate a command`,usage:`which [-as] program ...`,options:[`-a List all instances of executables found`,`-s No output, just return 0 if found, 1 if not`,`--help display this help and exit`]},L0={showAll:{short:`a`,type:`boolean`},silent:{short:`s`,type:`boolean`}},R0={name:`which`,async execute(e,t){if(aV(e))return iV(I0);let n=cV(`which`,e,L0);if(!n.ok)return n.error;let r=n.result.flags.showAll,i=n.result.flags.silent,a=n.result.positional;if(a.length===0)return{stdout:``,stderr:``,exitCode:1};let o=(t.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`),s=``,c=!0;for(let e of a){let n=!1;for(let a of o){if(!a)continue;let o=t.fs.resolvePath(a,e);if(await t.fs.exists(o)&&(n=!0,i||(s+=`${o} +`),!r))break}n||(c=!1)}return{stdout:s,stderr:``,exitCode:+!c}}},z0={name:`which`,flags:[{flag:`-a`,type:`boolean`},{flag:`-s`,type:`boolean`}],needsArgs:!0}}),B0={};wz(B0,{flagsForFuzzing:()=>H0,tac:()=>V0});async function uDe(e,t){if(e.length>0&&e[0]!==`-`){let n=t.fs.resolvePath(t.cwd,e[0]);try{let e=(await t.fs.readFile(n)).split(` +`);e[e.length-1]===``&&e.pop();let r=e.reverse();return{stdout:r.length>0?`${r.join(` +`)} +`:``,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`tac: ${e[0]}: No such file or directory +`,exitCode:1}}}let n=t.stdin.split(` +`);n[n.length-1]===``&&n.pop();let r=n.reverse();return{stdout:r.length>0?`${r.join(` +`)} +`:``,stderr:``,exitCode:0,stdoutKind:`bytes`}}var V0,H0,dDe=B(()=>{kB(),V0={name:`tac`,execute:uDe},H0={name:`tac`,flags:[],stdinType:`text`,needsFiles:!0}}),U0={};wz(U0,{flagsForFuzzing:()=>G0,hostname:()=>W0});async function fDe(e,t){return{stdout:`localhost +`,stderr:``,exitCode:0}}var W0,G0,pDe=B(()=>{W0={name:`hostname`,execute:fDe},G0={name:`hostname`,flags:[]}}),K0={};wz(K0,{flagsForFuzzing:()=>J0,whoami:()=>q0});async function mDe(e,t){return{stdout:`user +`,stderr:``,exitCode:0}}var q0,J0,hDe=B(()=>{q0={name:`whoami`,execute:mDe},J0={name:`whoami`,flags:[]}}),Y0={};wz(Y0,{flagsForFuzzing:()=>Z0,od:()=>X0});async function gDe(e,t){let n=`octal`,r=[],i=[];for(let t=0;t=32&&e<127?` ${String.fromCharCode(e)}`:` ${e.toString(8).padStart(3,`0`)}`}function l(e){return s?` ${e.toString(16).padStart(2,`0`)}`:` ${e.toString(16).padStart(2,`0`)}`}function u(e){return` ${e.toString(8).padStart(3,`0`)}`}let d=a.build(),f=new oH(Math.min(t.limits.maxOutputSize,t.limits.maxStringLength),`od`),p=r.length;if(p>0&&d.length>Math.floor(t.limits.maxLoopIterations/p))throw new H(`od: format work limit exceeded (${t.limits.maxLoopIterations})`,`iterations`);t.executionScope?.consumeWork(d.length*p,`od formatting`);for(let e=0;ec(e.charCodeAt(0))):i===`hex`?Array.from(d.slice(e,e+16),e=>l(e.charCodeAt(0))):Array.from(d.slice(e,e+16),e=>u(e.charCodeAt(0)));let o=``;t===0&&n!==`none`?o=`${e.toString(8).padStart(7,`0`)} `:(t>0||n===`none`)&&(o=n===`none`?``:` `),f.append(o+a.join(``)).append(` +`)}return n!==`none`&&d.length>0&&f.append(d.length.toString(8).padStart(7,`0`)).append(` +`),{stdout:f.build(),stderr:``,exitCode:0}}var X0,Z0,_De=B(()=>{sH(),kB(),rV(),U(),X0={name:`od`,execute:gDe},Z0={name:`od`,flags:[{flag:`-c`,type:`boolean`},{flag:`-A`,type:`value`,valueHint:`string`},{flag:`-t`,type:`value`,valueHint:`string`},{flag:`-N`,type:`value`,valueHint:`number`}],stdinType:`text`,needsFiles:!0}}),Q0,vDe=B(()=>{Q0=class{options;inputBytes=0;outputBytes=0;workBytes=0;label;constructor(e){this.options=e,this.label=e.label??`codec`;for(let[t,n]of[[`maxInputBytes`,e.maxInputBytes],[`maxOutputBytes`,e.maxOutputBytes],[`maxExpansionRatio`,e.maxExpansionRatio],[`ratioGraceBytes`,e.ratioGraceBytes],[`maxWorkBytes`,e.maxWorkBytes]])if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw Error(`${this.label}: invalid ${t}`)}checkpoint(){if(this.options.signal?.aborted)throw Error(`${this.label}: operation aborted`)}acceptInput(e){this.checkpoint(),this.inputBytes=this.addWithinLimit(this.inputBytes,e,this.options.maxInputBytes,`input`),this.chargeWork(e)}acceptOutput(e){this.checkpoint();let t=this.addWithinLimit(this.outputBytes,e,this.options.maxOutputBytes,`output`),n=this.options.ratioGraceBytes??1048576,r=this.options.maxExpansionRatio;if(r!==void 0&&t>n&&(this.inputBytes===0||t>this.inputBytes*r))throw Error(`${this.label}: expansion ratio exceeds limit (${r}:1)`);this.outputBytes=t,this.chargeWork(e)}get inputLength(){return this.inputBytes}get outputLength(){return this.outputBytes}chargeWork(e){let t=this.options.maxWorkBytes??this.options.maxInputBytes+this.options.maxOutputBytes;this.workBytes=this.addWithinLimit(this.workBytes,e,t,`work`)}addWithinLimit(e,t,n,r){if(!Number.isSafeInteger(t)||t<0||t>n-e)throw Error(`${this.label}: ${r} exceeds limit (${n} bytes)`);return e+t}}}),$0={};wz($0,{flagsForFuzzing:()=>y2,gunzipCommand:()=>_2,gunzipFlagsForFuzzing:()=>b2,gzipCommand:()=>g2,zcatCommand:()=>v2,zcatFlagsForFuzzing:()=>x2});function e2(e){return e.best?SR.constants.Z_BEST_COMPRESSION:e.level8?8:e.level7?7:e.level6?6:e.level5?5:e.level4?4:e.level3?3:e.level2?2:e.fast?SR.constants.Z_BEST_SPEED:SR.constants.Z_DEFAULT_COMPRESSION}function t2(e){if(e.length<10||e[0]!==31||e[1]!==139)return{originalName:null,mtime:null,headerSize:0};let t=e[3],n=e[4]|e[5]<<8|e[6]<<16|e[7]<<24,r=10;if(t&4){if(r+2>e.length)return{originalName:null,mtime:null,headerSize:0};let t=e[r]|e[r+1]<<8;r+=2+t}let i=null;if(t&8){let t=r;for(;r0?new Date(n*1e3):null,headerSize:r}}function yDe(e){return e.length===0||e===`.`||e===`..`||e.includes(`/`)||e.includes(`\\`)||/[\0-\x1f\x7f]/.test(e)?null:e}function n2(e){if(e.length<4)return 0;let t=e.length;return e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24}function r2(e){return e.length>=2&&e[0]===31&&e[1]===139}function i2(e){return Buffer.from(e).toString(`latin1`)}function a2(e){return e.limits.maxOutputSize}function o2(e,t,n,r,i){if(t<=0)throw Error(`decompressed data exceeds limit (0 bytes)`);let a=new Q0({maxInputBytes:n,maxOutputBytes:t,maxExpansionRatio:1e4,signal:r,label:`gzip`});if(a.acceptInput(e.length),n2(e)>t)throw Error(`decompressed data exceeds limit (${t} bytes)`);let o;try{let n=Math.min(t,Math.floor((i?.executionScope?.remainingLiveBytes??t*2)/2));if(n<=0)throw Error(`gzip: live byte limit exceeded`);o=i?.executionScope?.reserveBytes(`gzip output`,n*2,`gzip`);let r=(0,SR.gunzipSync)(e,{maxOutputLength:n});return a.acceptOutput(r.length),{data:r,lease:o}}catch(e){throw o?.release(),e}}function s2(e,t,n){let r=new Q0({maxInputBytes:n.limits.maxInputBytes,maxOutputBytes:n.limits.maxOutputSize,signal:n.signal,label:`gzip`});r.acceptInput(e.length);let i;try{let a=Math.min(n.limits.maxOutputSize,Math.floor((n.executionScope?.remainingLiveBytes??n.limits.maxOutputSize*2)/2));if(a<=0)throw Error(`gzip: live byte limit exceeded`);i=n.executionScope?.reserveBytes(`gzip output`,a*2,`gzip`);let o=(0,SR.gzipSync)(e,{level:t,maxOutputLength:a});return r.acceptOutput(o.length),{data:o,lease:i}}catch(e){throw i?.release(),e}}async function c2(e,t,n){let r=await e.fs.stat(t);if(r.size>e.limits.maxInputBytes)throw new H(`input size limit exceeded (${e.limits.maxInputBytes} bytes)`,`string_length`);let i=e.executionScope?.reserveBytes(`gzip input`,r.size,n);try{let a=await e.fs.readFileBuffer(t);if(a.byteLength>r.size)throw new H(`gzip: input grew while being read`,`string_length`);return e.executionScope?.consumeInput(a.byteLength,n),{data:a,lease:i}}catch(e){throw i?.release(),e}}async function l2(e,t,n){if(t!==`-`&&t!==``)return c2(e,e.fs.resolvePath(e.cwd,t),n);let r=e.stdin,i=e.executionScope?.reserveBytes(`gzip input`,r.length,n);try{return{data:Uint8Array.from(r,e=>e.charCodeAt(0)),lease:i}}catch(e){throw i?.release(),e}}async function u2(e,t,n,r,i,a){let o=n.suffix,s,c,l,u=a2(e);if(t===`-`||t===``){let t=e.stdin,a=e.executionScope?.reserveBytes(`gzip input`,t.length,r),o;try{if(l=Uint8Array.from(t,e=>e.charCodeAt(0)),i){if(!r2(l))return n.quiet?{stdout:``,stderr:``,exitCode:1}:{stdout:``,stderr:`${r}: stdin: not in gzip format +`,exitCode:1};try{let t=o2(l,u,e.limits.maxInputBytes,e.signal,e);return o=t.lease,{stdout:i2(t.data),stderr:``,exitCode:0}}catch(e){return nV(e),{stdout:``,stderr:`${r}: stdin: ${e instanceof Error?e.message:`unknown error`} +`,exitCode:1}}}{let t=s2(l,e2(n),e);return o=t.lease,{stdout:i2(t.data),stderr:``,exitCode:0}}}finally{o?.release(),a?.release()}}s=e.fs.resolvePath(e.cwd,t);try{let o=await e.fs.stat(s);if(o.size>e.limits.maxInputBytes)return{stdout:``,stderr:`${r}: ${t}: input size limit exceeded (${e.limits.maxInputBytes} bytes) +`,exitCode:1};if(o.isDirectory)return n.recursive?await bDe(e,s,n,r,i,a):n.quiet?{stdout:``,stderr:``,exitCode:1}:{stdout:``,stderr:`${r}: ${t}: is a directory -- ignored +`,exitCode:1}}catch{return{stdout:``,stderr:`${r}: ${t}: No such file or directory +`,exitCode:1}}let d,f;try{let t=await c2(e,s,r);l=t.data,d=t.lease}catch(e){return nV(e),{stdout:``,stderr:`${r}: ${t}: No such file or directory +`,exitCode:1}}try{if(i){if(!t.endsWith(o))return n.quiet?{stdout:``,stderr:``,exitCode:1}:{stdout:``,stderr:`${r}: ${t}: unknown suffix -- ignored +`,exitCode:1};if(!r2(l))return n.quiet?{stdout:``,stderr:``,exitCode:1}:{stdout:``,stderr:`${r}: ${t}: not in gzip format +`,exitCode:1};let i;try{let t=o2(l,u,e.limits.maxInputBytes,e.signal,e);i=t.data,f=t.lease}catch(e){return nV(e),{stdout:``,stderr:`${r}: ${t}: ${e instanceof Error?e.message:`unknown error`} +`,exitCode:1}}if(a)return{stdout:i2(i),stderr:``,exitCode:0};if(n.name){let t=t2(l),n=t.originalName?yDe(t.originalName):null;c=n?e.fs.resolvePath(e.cwd,n):s.slice(0,-o.length)}else c=s.slice(0,-o.length);if(!n.force)try{return await e.fs.stat(c),{stdout:``,stderr:`${r}: ${c} already exists; not overwritten +`,exitCode:1}}catch{}return await e.fs.writeFile(c,i),!n.keep&&!a&&await e.fs.rm(s),n.verbose?{stdout:``,stderr:`${t}: ${l.length>0?((1-l.length/i.length)*100).toFixed(1):`0.0`}% -- replaced with ${c.split(`/`).pop()} +`,exitCode:0}:{stdout:``,stderr:``,exitCode:0}}{if(t.endsWith(o))return n.quiet?{stdout:``,stderr:``,exitCode:1}:{stdout:``,stderr:`${r}: ${t} already has ${o} suffix -- unchanged +`,exitCode:1};let i=e2(n),u;try{let t=s2(l,i,e);u=t.data,f=t.lease}catch(e){return nV(e),{stdout:``,stderr:`${r}: ${t}: ${e instanceof Error?e.message:`unknown error`} +`,exitCode:1}}if(a)return{stdout:i2(u),stderr:``,exitCode:0};if(c=s+o,!n.force)try{return await e.fs.stat(c),{stdout:``,stderr:`${r}: ${c} already exists; not overwritten +`,exitCode:1}}catch{}return await e.fs.writeFile(c,u),!n.keep&&!a&&await e.fs.rm(s),n.verbose?{stdout:``,stderr:`${t}: ${l.length>0?((1-u.length/l.length)*100).toFixed(1):`0.0`}% -- replaced with ${c.split(`/`).pop()} +`,exitCode:0}:{stdout:``,stderr:``,exitCode:0}}}finally{f?.release(),d?.release()}}async function bDe(e,t,n,r,i,a){let o=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),s=new oH(o,r),c=new oH(o,r),l=0;return await wH({fs:e.fs,root:t,symlinks:`never`,limits:e.limits,signal:e.signal,executionScope:e.executionScope,site:r},async t=>{if(t.depth===0||t.phase!==`enter`||!t.stat.isFile)return;let o=n.suffix;if(i&&!t.path.endsWith(o)||!i&&t.path.endsWith(o))return;let u=await u2(e,t.path.startsWith(`${e.cwd}/`)?t.path.slice(e.cwd.length+1):t.path,n,r,i,a);s.append(u.stdout),c.append(u.stderr),u.exitCode!==0&&(l=u.exitCode)}),{stdout:s.build(),stderr:c.build(),exitCode:l}}async function xDe(e,t,n,r){let i,a;try{let n=await l2(e,t,r);i=n.data,a=n.lease}catch(e){return nV(e),{stdout:``,stderr:`${r}: ${t}: No such file or directory +`,exitCode:1}}try{if(!r2(i))return n.quiet?{stdout:``,stderr:``,exitCode:1}:{stdout:``,stderr:`${r}: ${t}: not in gzip format +`,exitCode:1};let e=i.length,a=n2(i),o=a>0?((1-e/a)*100).toFixed(1):`0.0`,s=t2(i).originalName||(t===`-`?``:t.replace(/\.gz$/,``));return{stdout:`${e.toString().padStart(10)} ${a.toString().padStart(10)} ${o.padStart(5)}% ${s} +`,stderr:``,exitCode:0}}finally{a?.release()}}async function SDe(e,t,n,r){let i,a;try{let n=await l2(e,t,r);i=n.data,a=n.lease}catch(e){return nV(e),{stdout:``,stderr:`${r}: ${t}: No such file or directory +`,exitCode:1}}try{if(!r2(i))return n.quiet?{stdout:``,stderr:``,exitCode:1}:{stdout:``,stderr:`${r}: ${t}: not in gzip format +`,exitCode:1};try{return o2(i,a2(e),e.limits.maxInputBytes,e.signal,e).lease?.release(),n.verbose?{stdout:``,stderr:`${t}: OK +`,exitCode:0}:{stdout:``,stderr:``,exitCode:0}}catch(e){return nV(e),{stdout:``,stderr:`${r}: ${t}: ${e instanceof Error?e.message:`invalid`} +`,exitCode:1}}}finally{a?.release()}}async function d2(e,t,n){let r=n===`zcat`?m2:n===`gunzip`?p2:f2;if(aV(e))return iV(r);let i=cV(n,e,h2);if(!i.ok)return i.error.stderr.includes(`unrecognized option`),i.error;let a=i.result.flags,o=i.result.positional,s=n===`gunzip`||n===`zcat`||a.decompress||a.uncompress,c=n===`zcat`||a.stdout||a.toStdout;if(a.list){o.length===0&&(o=[`-`]);let e=` compressed uncompressed ratio uncompressed_name +`,r=``,i=0;for(let s of o){let o=await xDe(t,s,a,n);e+=o.stdout,r+=o.stderr,o.exitCode!==0&&(i=o.exitCode)}return{stdout:e,stderr:r,exitCode:i}}if(a.test){o.length===0&&(o=[`-`]);let e=``,r=``,i=0;for(let s of o){let o=await SDe(t,s,a,n);e+=o.stdout,r+=o.stderr,o.exitCode!==0&&(i=o.exitCode)}return{stdout:e,stderr:r,exitCode:i}}o.length===0&&(o=[`-`]);let l=``,u=``,d=0;for(let e of o){let r=await u2(t,e,a,n,s,c);l+=r.stdout,u+=r.stderr,r.exitCode!==0&&(d=r.exitCode)}return{stdout:l,stderr:u,exitCode:d}}var f2,p2,m2,h2,g2,_2,v2,y2,b2,x2,S2=B(()=>{sH(),kB(),rV(),DH(),U(),lV(),vDe(),sV(),f2={name:`gzip`,summary:`compress or expand files`,usage:`gzip [OPTION]... [FILE]...`,description:`Compress FILEs (by default, in-place). + +When no FILE is given, or when FILE is -, read from standard input. + +With -d, decompress instead.`,options:[`-c, --stdout write to standard output, keep original files`,`-d, --decompress decompress`,`-f, --force force overwrite of output file`,`-k, --keep keep (don't delete) input files`,`-l, --list list compressed file contents`,`-n, --no-name do not save or restore the original name and timestamp`,`-N, --name save or restore the original file name and timestamp`,`-q, --quiet suppress all warnings`,`-r, --recursive operate recursively on directories`,`-S, --suffix=SUF use suffix SUF on compressed files (default: .gz)`,`-t, --test test compressed file integrity`,`-v, --verbose verbose mode`,`-1, --fast compress faster`,`-9, --best compress better`,` --help display this help and exit`]},p2={name:`gunzip`,summary:`decompress files`,usage:`gunzip [OPTION]... [FILE]...`,description:`Decompress FILEs (by default, in-place). + +When no FILE is given, or when FILE is -, read from standard input.`,options:[`-c, --stdout write to standard output, keep original files`,`-f, --force force overwrite of output file`,`-k, --keep keep (don't delete) input files`,`-l, --list list compressed file contents`,`-n, --no-name do not restore the original name and timestamp`,`-N, --name restore the original file name and timestamp`,`-q, --quiet suppress all warnings`,`-r, --recursive operate recursively on directories`,`-S, --suffix=SUF use suffix SUF on compressed files (default: .gz)`,`-t, --test test compressed file integrity`,`-v, --verbose verbose mode`,` --help display this help and exit`]},m2={name:`zcat`,summary:`decompress files to stdout`,usage:`zcat [OPTION]... [FILE]...`,description:`Decompress FILEs to standard output. + +When no FILE is given, or when FILE is -, read from standard input.`,options:[`-f, --force force; read compressed data even from a terminal`,`-l, --list list compressed file contents`,`-q, --quiet suppress all warnings`,`-S, --suffix=SUF use suffix SUF on compressed files (default: .gz)`,`-t, --test test compressed file integrity`,`-v, --verbose verbose mode`,` --help display this help and exit`]},h2={stdout:{short:`c`,long:`stdout`,type:`boolean`},toStdout:{long:`to-stdout`,type:`boolean`},decompress:{short:`d`,long:`decompress`,type:`boolean`},uncompress:{long:`uncompress`,type:`boolean`},force:{short:`f`,long:`force`,type:`boolean`},keep:{short:`k`,long:`keep`,type:`boolean`},list:{short:`l`,long:`list`,type:`boolean`},noName:{short:`n`,long:`no-name`,type:`boolean`},name:{short:`N`,long:`name`,type:`boolean`},quiet:{short:`q`,long:`quiet`,type:`boolean`},recursive:{short:`r`,long:`recursive`,type:`boolean`},suffix:{short:`S`,long:`suffix`,type:`string`,default:`.gz`},test:{short:`t`,long:`test`,type:`boolean`},verbose:{short:`v`,long:`verbose`,type:`boolean`},fast:{short:`1`,long:`fast`,type:`boolean`},level2:{short:`2`,type:`boolean`},level3:{short:`3`,type:`boolean`},level4:{short:`4`,type:`boolean`},level5:{short:`5`,type:`boolean`},level6:{short:`6`,type:`boolean`},level7:{short:`7`,type:`boolean`},level8:{short:`8`,type:`boolean`},best:{short:`9`,long:`best`,type:`boolean`}},g2={name:`gzip`,async execute(e,t){return{...await d2(e,t,`gzip`),stdoutEncoding:`binary`}}},_2={name:`gunzip`,async execute(e,t){return{...await d2(e,t,`gunzip`),stdoutEncoding:`binary`}}},v2={name:`zcat`,async execute(e,t){return{...await d2(e,t,`zcat`),stdoutEncoding:`binary`}}},y2={name:`gzip`,flags:[{flag:`-c`,type:`boolean`},{flag:`-d`,type:`boolean`},{flag:`-f`,type:`boolean`},{flag:`-k`,type:`boolean`},{flag:`-l`,type:`boolean`},{flag:`-n`,type:`boolean`},{flag:`-q`,type:`boolean`},{flag:`-r`,type:`boolean`},{flag:`-t`,type:`boolean`},{flag:`-v`,type:`boolean`},{flag:`-1`,type:`boolean`},{flag:`-9`,type:`boolean`}],stdinType:`binary`,needsFiles:!0},b2={name:`gunzip`,flags:[{flag:`-c`,type:`boolean`},{flag:`-f`,type:`boolean`},{flag:`-k`,type:`boolean`},{flag:`-q`,type:`boolean`},{flag:`-v`,type:`boolean`}],stdinType:`binary`,needsFiles:!0},x2={name:`zcat`,flags:[{flag:`-f`,type:`boolean`},{flag:`-q`,type:`boolean`},{flag:`-v`,type:`boolean`}],stdinType:`binary`,needsFiles:!0}});function C2(e,t){if(e instanceof Uint8Array)return e;if(t===`base64`)return Uint8Array.from(atob(e),e=>e.charCodeAt(0));if(t===`hex`){let t=new Uint8Array(e.length/2);for(let n=0;ne.charCodeAt(0));let t=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,`0`)).join(``);if(t===`binary`||t===`latin1`){if(typeof Buffer<`u`)return Buffer.from(e).toString(t);let n=65536;if(e.length<=n)return String.fromCharCode(...e);let r=``;for(let t=0;t{E2=new TextEncoder,D2=new TextDecoder});function k2(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16)}`).replace(/%20/g,`+`).replace(/%[0-9A-F]{2}/g,e=>e.toLowerCase())}function CDe(e){let t=e.indexOf(`=`);if(t>=0){let n=e.slice(0,t),r=k2(e.slice(t+1));return n?`${n}=${r}`:r}return k2(e)}function A2(e){let t=e.indexOf(`=`);if(t<0)return null;let n=e.slice(0,t),r=e.slice(t+1),i,a,o=r.match(/;type=([^;]+)$/);o&&(a=o[1],r=r.slice(0,-o[0].length));let s=r.match(/;filename=([^;]+)/);return s&&(i=s[1],r=r.replace(s[0],``)),(r.startsWith(`@`)||r.startsWith(`<`))&&(i??=r.slice(1).split(`/`).pop()),{name:n,value:r,filename:i,contentType:a}}function wDe(e,t){let n=`----CurlFormBoundary${Date.now().toString(36)}`,r=[];for(let i of e){let e=i.value;if(e.startsWith(`@`)||e.startsWith(`<`)){let n=e.slice(1);e=t.get(n)??``}let a=`--${n}\r +`;i.filename?(a+=`Content-Disposition: form-data; name="${i.name}"; filename="${i.filename}"\r +`,i.contentType&&(a+=`Content-Type: ${i.contentType}\r +`)):a+=`Content-Disposition: form-data; name="${i.name}"\r +`,a+=`\r +${e}\r +`,r.push(a)}return r.push(`--${n}--\r +`),{body:r.join(``),boundary:n}}var j2=B(()=>{}),M2,TDe=B(()=>{M2={name:`curl`,summary:`transfer a URL`,usage:`curl [OPTIONS] URL`,options:[`-X, --request METHOD HTTP method (GET, POST, PUT, DELETE, etc.)`,`-H, --header HEADER Add header (can be used multiple times)`,`-d, --data DATA HTTP POST data (DATA=@file reads from file, strips newlines)`,`-G, --get Append data payloads to URL query string`,` --data-raw DATA HTTP POST data (no @ interpretation)`,` --data-binary DATA HTTP POST binary data (DATA=@file reads file verbatim)`,` --data-urlencode DATA URL-encode and POST data (supports @file and name@file)`,`-F, --form NAME=VALUE Multipart form data`,`-u, --user USER:PASS HTTP authentication`,`-A, --user-agent STR Set User-Agent header`,`-e, --referer URL Set Referer header`,`-b, --cookie DATA Send cookies (name=value or @file)`,`-c, --cookie-jar FILE Save cookies to file`,`-T, --upload-file FILE Upload file (PUT)`,`-o, --output FILE Write output to file`,`-O, --remote-name Write to file named from URL`,`-I, --head Show headers only (HEAD request)`,`-i, --include Include response headers in output`,`-s, --silent Silent mode (no progress)`,`-S, --show-error Show errors even when silent`,`-f, --fail Fail silently on HTTP errors (no output)`,`-L, --location Follow redirects (default)`,` --max-redirs NUM Maximum redirects (default: 20)`,`-m, --max-time SECS Maximum time for request`,` --connect-timeout SECS Connection timeout`,`-w, --write-out FMT Output format after completion`,`-v, --verbose Verbose output`,` --help Display this help and exit`,``,`Note: Network access must be configured via BashEnv network option.`,` curl is not available by default for security reasons.`]}});function N2(e,t,n){n.allowFile&&t.startsWith(`@`)?e.dataParts.push({file:{path:t.slice(1),mode:n.binary?`binary`:`ascii`}}):e.dataParts.push({value:t}),n.binary&&(e.dataBinary=!0)}function P2(e,t){if(t.startsWith(`@`)){e.dataParts.push({file:{path:t.slice(1),mode:`urlencode`}});return}let n=t.indexOf(`@`),r=t.indexOf(`=`);if(n>0&&(r<0||n0){let r=n.slice(0,e).trim(),i=n.slice(e+1).trim();t.headers.append(r,i)}}}else if(a.startsWith(`--header=`)){let e=a.slice(9),n=e.indexOf(`:`);if(n>0){let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();t.headers.append(r,i)}}else if(a===`-G`||a===`--get`)t.getMode=!0,r||(t.method=`GET`);else if(a===`-d`||a===`--data`)N2(t,e[++i]??``,{binary:!1,allowFile:!0}),n=!0;else if(a===`--data-raw`)N2(t,e[++i]??``,{binary:!1,allowFile:!1}),n=!0;else if(a.startsWith(`-d`))N2(t,a.slice(2),{binary:!1,allowFile:!0}),n=!0;else if(a.startsWith(`--data=`))N2(t,a.slice(7),{binary:!1,allowFile:!0}),n=!0;else if(a.startsWith(`--data-raw=`))N2(t,a.slice(11),{binary:!1,allowFile:!1}),n=!0;else if(a===`--data-binary`)N2(t,e[++i]??``,{binary:!0,allowFile:!0}),n=!0;else if(a.startsWith(`--data-binary=`))N2(t,a.slice(14),{binary:!0,allowFile:!0}),n=!0;else if(a===`--data-urlencode`)P2(t,e[++i]??``),n=!0;else if(a.startsWith(`--data-urlencode=`))P2(t,a.slice(17)),n=!0;else if(a===`-F`||a===`--form`){let r=A2(e[++i]??``);r&&t.formFields.push(r),n=!0}else if(a.startsWith(`--form=`)){let e=A2(a.slice(7));e&&t.formFields.push(e),n=!0}else if(a===`-u`||a===`--user`)t.user=e[++i];else if(a.startsWith(`-u`))t.user=a.slice(2);else if(a.startsWith(`--user=`))t.user=a.slice(7);else if(a===`-A`||a===`--user-agent`)t.headers.set(`User-Agent`,e[++i]??``);else if(a.startsWith(`-A`))t.headers.set(`User-Agent`,a.slice(2));else if(a.startsWith(`--user-agent=`))t.headers.set(`User-Agent`,a.slice(13));else if(a===`-e`||a===`--referer`)t.headers.set(`Referer`,e[++i]??``);else if(a.startsWith(`-e`))t.headers.set(`Referer`,a.slice(2));else if(a.startsWith(`--referer=`))t.headers.set(`Referer`,a.slice(10));else if(a===`-b`||a===`--cookie`)t.headers.set(`Cookie`,e[++i]??``);else if(a.startsWith(`-b`))t.headers.set(`Cookie`,a.slice(2));else if(a.startsWith(`--cookie=`))t.headers.set(`Cookie`,a.slice(9));else if(a===`-c`||a===`--cookie-jar`)t.cookieJar=e[++i];else if(a.startsWith(`--cookie-jar=`))t.cookieJar=a.slice(13);else if(a===`-T`||a===`--upload-file`)t.uploadFile=e[++i],t.method===`GET`&&(t.method=`PUT`);else if(a.startsWith(`--upload-file=`))t.uploadFile=a.slice(14),t.method===`GET`&&(t.method=`PUT`);else if(a===`-m`||a===`--max-time`){let n=parseFloat(e[++i]??`0`);!Number.isNaN(n)&&n>0&&(t.timeoutMs=n*1e3)}else if(a.startsWith(`--max-time=`)){let e=parseFloat(a.slice(11));!Number.isNaN(e)&&e>0&&(t.timeoutMs=e*1e3)}else if(a===`--connect-timeout`){let n=parseFloat(e[++i]??`0`);!Number.isNaN(n)&&n>0&&t.timeoutMs===void 0&&(t.timeoutMs=n*1e3)}else if(a.startsWith(`--connect-timeout=`)){let e=parseFloat(a.slice(18));!Number.isNaN(e)&&e>0&&t.timeoutMs===void 0&&(t.timeoutMs=e*1e3)}else if(a===`-o`||a===`--output`)t.outputFile=e[++i];else if(a.startsWith(`--output=`))t.outputFile=a.slice(9);else if(a===`-O`||a===`--remote-name`)t.useRemoteName=!0;else if(a===`-I`||a===`--head`)t.headOnly=!0,t.method=`HEAD`,r=!0;else if(a===`-i`||a===`--include`)t.includeHeaders=!0;else if(a===`-s`||a===`--silent`)t.silent=!0;else if(a===`-S`||a===`--show-error`)t.showError=!0;else if(a===`-f`||a===`--fail`)t.failSilently=!0;else if(a===`-L`||a===`--location`)t.followRedirects=!0;else if(a===`--max-redirs`){let n=e[++i];if(n===void 0||!/^\d+$/.test(n))return{stdout:``,stderr:`curl: option --max-redirs: expected a non-negative integer +`,exitCode:2};let r=Number(n);if(!Number.isSafeInteger(r))return{stdout:``,stderr:`curl: option --max-redirs: value is out of range +`,exitCode:2};t.maxRedirects=r}else if(a.startsWith(`--max-redirs=`)){let e=a.slice(13);if(!/^\d+$/.test(e)||!Number.isSafeInteger(Number(e)))return{stdout:``,stderr:`curl: option --max-redirs: expected a non-negative integer +`,exitCode:2};t.maxRedirects=Number(e)}else if(a===`-w`||a===`--write-out`)t.writeOut=e[++i];else if(a.startsWith(`--write-out=`))t.writeOut=a.slice(12);else if(a===`-v`||a===`--verbose`)t.verbose=!0;else{if(a.startsWith(`--`)&&a!==`--`)return oV(`curl`,a);if(a.startsWith(`-`)&&a!==`-`)for(let e of a.slice(1))switch(e){case`s`:t.silent=!0;break;case`S`:t.showError=!0;break;case`f`:t.failSilently=!0;break;case`L`:t.followRedirects=!0;break;case`I`:t.headOnly=!0,t.method=`HEAD`,r=!0;break;case`i`:t.includeHeaders=!0;break;case`O`:t.useRemoteName=!0;break;case`v`:t.verbose=!0;break;case`G`:t.getMode=!0,r||(t.method=`GET`);break;default:return oV(`curl`,`-${e}`)}else a.startsWith(`-`)||(t.url=a)}}return n&&!r&&!t.getMode&&(t.method=`POST`),t}var DDe=B(()=>{m$(),sV(),j2()});function F2(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join(`\r +`)}function ODe(e){try{return new URL(e).pathname.split(`/`).pop()||`index.html`}catch{return`index.html`}}function I2(e,t){let n=e;return n=n.replace(/%\{http_code\}/g,String(t.status)),n=n.replace(/%\{content_type\}/g,t.headers[`content-type`]||``),n=n.replace(/%\{url_effective\}/g,t.url),n=n.replace(/%\{size_download\}/g,String(t.bodyLength)),n=n.replace(/\\n/g,` +`),n}var kDe=B(()=>{}),L2={};wz(L2,{curlCommand:()=>R2});async function ADe(e,t){if(e.dataParts.length===0)return;let n=[];for(let r of e.dataParts)if(r.file){let e=t.fs.resolvePath(t.cwd,r.file.path),i=await t.fs.readFile(e);if(r.file.mode===`ascii`)n.push(i.replace(/[\r\n]/g,``));else if(r.file.mode===`binary`)n.push(i);else{let e=k2(i);n.push(r.file.name?`${r.file.name}=${e}`:e)}}else n.push(r.value??``);return n.join(`&`)}async function jDe(e,t,n){if(e.uploadFile){let n=t.fs.resolvePath(t.cwd,e.uploadFile);return{body:await t.fs.readFile(n)}}if(e.formFields.length>0){let n=new Map;for(let r of e.formFields)if(r.value.startsWith(`@`)||r.value.startsWith(`<`)){let e=t.fs.resolvePath(t.cwd,r.value.slice(1));try{let i=await t.fs.readFile(e);n.set(r.value.slice(1),i)}catch{n.set(r.value.slice(1),``)}}let{body:r,boundary:i}=wDe(e.formFields,n);return{body:r,contentType:`multipart/form-data; boundary=${i}`}}return n!==void 0&&!e.getMode?{body:n,contentType:`application/x-www-form-urlencoded`}:{}}function MDe(e,t){if(!t)return e;let n=e.indexOf(`#`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n);return`${r}${r.endsWith(`?`)||r.endsWith(`&`)?``:r.includes(`?`)?`&`:`?`}${t}${i}`}function NDe(e,t){let n=new f$(e.headers);if(e.user){let t=Buffer.from(e.user).toString(`base64`);n.set(`Authorization`,`Basic ${t}`)}return t&&!n.has(`Content-Type`)&&n.set(`Content-Type`,t),n}async function PDe(e,t,n){if(!e.cookieJar)return;let r=t[`set-cookie`];if(!r)return;let i=n.fs.resolvePath(n.cwd,e.cookieJar);await n.fs.writeFile(i,r)}function FDe(e){return w2(e,`binary`)}function IDe(e,t,n){let r=``;if(e.verbose){r+=`> ${e.method} ${n} +`;for(let[t,n]of e.headers)r+=`> ${t}: ${n} +`;r+=`> +`,r+=`< HTTP/1.1 ${t.status} ${t.statusText} +`;for(let[e,n]of Object.entries(t.headers))r+=`< ${e}: ${n} +`;r+=`< +`}return e.includeHeaders&&!e.verbose&&(r+=`HTTP/1.1 ${t.status} ${t.statusText}\r +`,r+=F2(t.headers),r+=`\r +\r +`),e.headOnly?e.includeHeaders||e.verbose||(r+=`HTTP/1.1 ${t.status} ${t.statusText}\r +`,r+=F2(t.headers),r+=`\r +`):r+=FDe(t.body),e.writeOut&&(r+=I2(e.writeOut,{status:t.status,headers:t.headers,url:t.url,bodyLength:t.body.byteLength})),r}var R2,LDe=B(()=>{O2(),TV(),m$(),sV(),j2(),TDe(),DDe(),kDe(),R2={name:`curl`,async execute(e,t){if(aV(e))return iV(M2);let n=EDe(e);if(`exitCode`in n)return n;let r=n;if(!r.url)return{stdout:``,stderr:`curl: no URL specified +`,exitCode:2};if(!t.fetch)return{stdout:``,stderr:`curl: internal error: fetch not available +`,exitCode:1};let i=r.url;i.match(/^https?:\/\//)||(i=`https://${i}`);try{let e=await ADe(r,t);r.getMode&&(i=MDe(i,e));let{body:n,contentType:a}=await jDe(r,t,e),o=NDe(r,a),s=await t.fetch(i,{method:r.method,headers:o,body:n,followRedirects:r.followRedirects,timeoutMs:r.timeoutMs,maxRedirects:r.maxRedirects,signal:t.signal});if(await PDe(r,s.headers,t),r.failSilently&&s.status>=400)return{stdout:``,stderr:r.showError||!r.silent?`curl: (22) The requested URL returned error: ${s.status} +`:``,exitCode:22};let c=IDe(r,s,i);if(r.outputFile||r.useRemoteName){let e=r.outputFile||ODe(i),n=t.fs.resolvePath(t.cwd,e);await t.fs.writeFile(n,r.headOnly?``:s.body),r.verbose||(c=``),r.writeOut&&(c=I2(r.writeOut,{status:s.status,headers:s.headers,url:s.url,bodyLength:s.body.byteLength}))}return{stdout:c,stderr:``,exitCode:0,stdoutKind:`bytes`}}catch(e){let t=wV(e),n=1;return t.includes(`Network access denied`)?n=7:t.includes(`HTTP method`)&&t.includes(`not allowed`)?n=3:t.includes(`Redirect target not in allow-list`)||t.includes(`Too many redirects`)?n=47:t.includes(`aborted`)&&(n=28),{stdout:``,stderr:!r.silent||r.showError?`curl: (${n}) ${t} +`:``,exitCode:n}}}}});mB(),gB(),XB(),aB();var z2=[{name:`echo`,load:async()=>(await Promise.resolve().then(()=>(tV(),ZB))).echoCommand},{name:`cat`,load:async()=>(await Promise.resolve().then(()=>(CV(),hV))).catCommand},{name:`printf`,load:async()=>(await Promise.resolve().then(()=>(eH(),IV))).printfCommand},{name:`ls`,load:async()=>(await Promise.resolve().then(()=>(BH(),OH))).lsCommand},{name:`mkdir`,load:async()=>(await Promise.resolve().then(()=>(GH(),VH))).mkdirCommand},{name:`rmdir`,load:async()=>(await Promise.resolve().then(()=>(eU(),KH))).rmdirCommand},{name:`touch`,load:async()=>(await Promise.resolve().then(()=>(aU(),tU))).touchCommand},{name:`rm`,load:async()=>(await Promise.resolve().then(()=>(uU(),oU))).rmCommand},{name:`cp`,load:async()=>(await Promise.resolve().then(()=>(gU(),dU))).cpCommand},{name:`mv`,load:async()=>(await Promise.resolve().then(()=>(SU(),_U))).mvCommand},{name:`ln`,load:async()=>(await Promise.resolve().then(()=>(Bbe(),CU))).lnCommand},{name:`chmod`,load:async()=>(await Promise.resolve().then(()=>(Hbe(),DU))).chmodCommand},{name:`pwd`,load:async()=>(await Promise.resolve().then(()=>(Ube(),MU))).pwdCommand},{name:`readlink`,load:async()=>(await Promise.resolve().then(()=>(Wbe(),FU))).readlinkCommand},{name:`head`,load:async()=>(await Promise.resolve().then(()=>(qbe(),HU))).headCommand},{name:`tail`,load:async()=>(await Promise.resolve().then(()=>(Jbe(),KU))).tailCommand},{name:`wc`,load:async()=>(await Promise.resolve().then(()=>(Ybe(),XU))).wcCommand},{name:`stat`,load:async()=>(await Promise.resolve().then(()=>(Xbe(),aW))).statCommand},{name:`grep`,load:async()=>(await Promise.resolve().then(()=>(JG(),MG))).grepCommand},{name:`fgrep`,load:async()=>(await Promise.resolve().then(()=>(JG(),MG))).fgrepCommand},{name:`egrep`,load:async()=>(await Promise.resolve().then(()=>(JG(),MG))).egrepCommand},{name:`rg`,load:async()=>(await Promise.resolve().then(()=>(Zxe(),wK))).rgCommand},{name:`sed`,load:async()=>(await Promise.resolve().then(()=>(dSe(),qK))).sedCommand},{name:`awk`,load:async()=>(await Promise.resolve().then(()=>(kCe(),lJ))).awkCommand2},{name:`sort`,load:async()=>(await Promise.resolve().then(()=>(FCe(),wJ))).sortCommand},{name:`uniq`,load:async()=>(await Promise.resolve().then(()=>(ICe(),OJ))).uniqCommand},{name:`comm`,load:async()=>(await Promise.resolve().then(()=>(LCe(),NJ))).commCommand},{name:`cut`,load:async()=>(await Promise.resolve().then(()=>(BCe(),LJ))).cutCommand},{name:`paste`,load:async()=>(await Promise.resolve().then(()=>(VCe(),VJ))).pasteCommand},{name:`tr`,load:async()=>(await Promise.resolve().then(()=>(HCe(),qJ))).trCommand},{name:`rev`,load:async()=>(await Promise.resolve().then(()=>(WCe(),eY))).rev},{name:`nl`,load:async()=>(await Promise.resolve().then(()=>(qCe(),iY))).nl},{name:`fold`,load:async()=>(await Promise.resolve().then(()=>(XCe(),lY))).fold},{name:`expand`,load:async()=>(await Promise.resolve().then(()=>($Ce(),mY))).expand},{name:`unexpand`,load:async()=>(await Promise.resolve().then(()=>(twe(),bY))).unexpand},{name:`strings`,load:async()=>(await Promise.resolve().then(()=>(rwe(),DY))).strings},{name:`split`,load:async()=>(await Promise.resolve().then(()=>(dwe(),NY))).split},{name:`column`,load:async()=>(await Promise.resolve().then(()=>(hwe(),UY))).column},{name:`join`,load:async()=>(await Promise.resolve().then(()=>(ywe(),YY))).join},{name:`tee`,load:async()=>(await Promise.resolve().then(()=>(bwe(),eX))).teeCommand},{name:`find`,load:async()=>(await Promise.resolve().then(()=>(Mwe(),gX))).findCommand},{name:`basename`,load:async()=>(await Promise.resolve().then(()=>(Nwe(),SX))).basenameCommand},{name:`dirname`,load:async()=>(await Promise.resolve().then(()=>(Pwe(),EX))).dirnameCommand},{name:`tree`,load:async()=>(await Promise.resolve().then(()=>(Iwe(),AX))).treeCommand},{name:`du`,load:async()=>(await Promise.resolve().then(()=>(Rwe(),IX))).duCommand},{name:`env`,load:async()=>(await Promise.resolve().then(()=>(YX(),HX))).envCommand},{name:`printenv`,load:async()=>(await Promise.resolve().then(()=>(YX(),HX))).printenvCommand},{name:`alias`,load:async()=>(await Promise.resolve().then(()=>(rZ(),XX))).aliasCommand},{name:`unalias`,load:async()=>(await Promise.resolve().then(()=>(rZ(),XX))).unaliasCommand},{name:`history`,load:async()=>(await Promise.resolve().then(()=>(zwe(),iZ))).historyCommand},{name:`xargs`,load:async()=>(await Promise.resolve().then(()=>(Vwe(),lZ))).xargsCommand},{name:`true`,load:async()=>(await Promise.resolve().then(()=>(yZ(),mZ))).trueCommand},{name:`false`,load:async()=>(await Promise.resolve().then(()=>(yZ(),mZ))).falseCommand},{name:`clear`,load:async()=>(await Promise.resolve().then(()=>(Hwe(),bZ))).clearCommand},{name:`bash`,load:async()=>(await Promise.resolve().then(()=>(jZ(),wZ))).bashCommand},{name:`sh`,load:async()=>(await Promise.resolve().then(()=>(jZ(),wZ))).shCommand},{name:`jq`,load:async()=>(await Promise.resolve().then(()=>(NTe(),kQ))).jqCommand},{name:`base64`,load:async()=>(await Promise.resolve().then(()=>(PTe(),IQ))).base64Command},{name:`diff`,load:async()=>(await Promise.resolve().then(()=>(FTe(),GQ))).diffCommand},{name:`date`,load:async()=>(await Promise.resolve().then(()=>(BTe(),XQ))).dateCommand},{name:`sleep`,load:async()=>(await Promise.resolve().then(()=>(VTe(),n$))).sleepCommand},{name:`timeout`,load:async()=>(await Promise.resolve().then(()=>(HTe(),s$))).timeoutCommand},{name:`time`,load:async()=>(await Promise.resolve().then(()=>(WTe(),h$))).timeCommand},{name:`seq`,load:async()=>(await Promise.resolve().then(()=>(GTe(),v$))).seqCommand},{name:`expr`,load:async()=>(await Promise.resolve().then(()=>(qTe(),x$))).exprCommand},{name:`md5sum`,load:async()=>(await Promise.resolve().then(()=>(YTe(),O$))).md5sumCommand},{name:`sha1sum`,load:async()=>(await Promise.resolve().then(()=>(XTe(),j$))).sha1sumCommand},{name:`sha256sum`,load:async()=>(await Promise.resolve().then(()=>(ZTe(),P$))).sha256sumCommand},{name:`file`,load:async()=>(await Promise.resolve().then(()=>(aDe(),x0))).fileCommand},{name:`html-to-markdown`,load:async()=>(await Promise.resolve().then(()=>(oDe(),D0))).htmlToMarkdownCommand},{name:`help`,load:async()=>(await Promise.resolve().then(()=>(cDe(),j0))).helpCommand},{name:`which`,load:async()=>(await Promise.resolve().then(()=>(lDe(),F0))).whichCommand},{name:`tac`,load:async()=>(await Promise.resolve().then(()=>(dDe(),B0))).tac},{name:`hostname`,load:async()=>(await Promise.resolve().then(()=>(pDe(),U0))).hostname},{name:`whoami`,load:async()=>(await Promise.resolve().then(()=>(hDe(),K0))).whoami},{name:`od`,load:async()=>(await Promise.resolve().then(()=>(_De(),Y0))).od},{name:`gzip`,load:async()=>(await Promise.resolve().then(()=>(S2(),$0))).gzipCommand},{name:`gunzip`,load:async()=>(await Promise.resolve().then(()=>(S2(),$0))).gunzipCommand},{name:`zcat`,load:async()=>(await Promise.resolve().then(()=>(S2(),$0))).zcatCommand}],RDe=[],zDe=[],BDe=[{name:`curl`,load:async()=>(await Promise.resolve().then(()=>(LDe(),L2))).curlCommand}],B2=new Map;function V2(e){return{name:e.name,async execute(t,n){let r=B2.get(e.name);return r||(r=await iB.runTrustedAsync(()=>e.load()),B2.set(e.name,r)),n.coverage,r.execute(t,n)}}}function VDe(e){return(e?z2.filter(t=>e.includes(t.name)):z2).map(V2)}function HDe(){return BDe.map(V2)}function UDe(){return RDe.map(V2)}function WDe(){return zDe.map(V2)}kB();var H2=new WeakMap,U2=new WeakSet;function GDe(e){let t=H2.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),H2.set(e,t),U2.add(t)),t}function KDe(e){return U2.has(e)}var W2={maxSourceBytes:67108864,maxExecDepth:64,maxCallDepth:100,maxCommandCount:1e5,maxLoopIterations:1e5,maxAwkIterations:1e5,maxSedIterations:1e5,maxJqIterations:1e7,maxQueryTokens:1e5,maxQueryDepth:1e3,maxQueryElements:1e6,maxAwkParserTokens:1e5,maxAwkParserDepth:256,maxAwkParserOperations:1e6,maxCsvRows:1e6,maxCsvCells:1e7,maxWorkUnits:1e8,maxTraversalEntries:1e6,maxTraversalDepth:1e3,maxTraversalWork:1e6,maxLiveBytes:536870912,maxInputBytes:536870912,maxFileSystemBytes:1073741824,maxDatabaseBytes:1073741824,maxDatabaseResultBytes:268435456,maxArchiveBytes:1073741824,maxArchiveCompressedBytes:536870912,maxArchiveEntryBytes:536870912,maxArchiveEntries:1e6,maxWorkerMessageBytes:67108864,maxExecutionTimeMs:36e5,maxExtensionCleanupTimeMs:100,maxSqliteTimeoutMs:3e4,maxPythonTimeoutMs:3e4,maxJsTimeoutMs:3e4,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},qDe={...W2,maxSourceBytes:8388608,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxExtensionCleanupTimeMs:25,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxQueryTokens:25e3,maxQueryDepth:256,maxQueryElements:1e5,maxAwkParserTokens:25e3,maxAwkParserDepth:128,maxAwkParserOperations:1e5,maxCsvRows:1e5,maxCsvCells:1e6,maxWorkUnits:1e5,maxTraversalEntries:1e5,maxTraversalDepth:256,maxTraversalWork:1e5,maxLiveBytes:67108864,maxInputBytes:33554432,maxFileSystemBytes:134217728,maxDatabaseBytes:67108864,maxDatabaseResultBytes:16777216,maxArchiveBytes:134217728,maxArchiveCompressedBytes:67108864,maxArchiveEntryBytes:67108864,maxArchiveEntries:1e5,maxWorkerMessageBytes:16777216,maxExecutionTimeMs:3e4};function JDe(e,t=`normal`){if(t!==`normal`&&t!==`hardened`)throw RangeError(`executionLimitProfile must be "normal" or "hardened"`);let n=t===`hardened`?qDe:W2;if(!e)return{...n};let r={maxSourceBytes:e.maxSourceBytes??n.maxSourceBytes,maxExecDepth:e.maxExecDepth??n.maxExecDepth,maxCallDepth:e.maxCallDepth??n.maxCallDepth,maxCommandCount:e.maxCommandCount??n.maxCommandCount,maxLoopIterations:e.maxLoopIterations??n.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??n.maxAwkIterations,maxSedIterations:e.maxSedIterations??n.maxSedIterations,maxJqIterations:e.maxJqIterations??n.maxJqIterations,maxQueryTokens:e.maxQueryTokens??n.maxQueryTokens,maxQueryDepth:e.maxQueryDepth??n.maxQueryDepth,maxQueryElements:e.maxQueryElements??n.maxQueryElements,maxAwkParserTokens:e.maxAwkParserTokens??n.maxAwkParserTokens,maxAwkParserDepth:e.maxAwkParserDepth??n.maxAwkParserDepth,maxAwkParserOperations:e.maxAwkParserOperations??n.maxAwkParserOperations,maxCsvRows:e.maxCsvRows??n.maxCsvRows,maxCsvCells:e.maxCsvCells??n.maxCsvCells,maxWorkUnits:e.maxWorkUnits??n.maxWorkUnits,maxTraversalEntries:e.maxTraversalEntries??n.maxTraversalEntries,maxTraversalDepth:e.maxTraversalDepth??n.maxTraversalDepth,maxTraversalWork:e.maxTraversalWork??n.maxTraversalWork,maxLiveBytes:e.maxLiveBytes??n.maxLiveBytes,maxInputBytes:e.maxInputBytes??n.maxInputBytes,maxFileSystemBytes:e.maxFileSystemBytes??n.maxFileSystemBytes,maxDatabaseBytes:e.maxDatabaseBytes??n.maxDatabaseBytes,maxDatabaseResultBytes:e.maxDatabaseResultBytes??n.maxDatabaseResultBytes,maxArchiveBytes:e.maxArchiveBytes??n.maxArchiveBytes,maxArchiveCompressedBytes:e.maxArchiveCompressedBytes??n.maxArchiveCompressedBytes,maxArchiveEntryBytes:e.maxArchiveEntryBytes??n.maxArchiveEntryBytes,maxArchiveEntries:e.maxArchiveEntries??n.maxArchiveEntries,maxWorkerMessageBytes:e.maxWorkerMessageBytes??n.maxWorkerMessageBytes,maxExecutionTimeMs:e.maxExecutionTimeMs??n.maxExecutionTimeMs,maxExtensionCleanupTimeMs:e.maxExtensionCleanupTimeMs??n.maxExtensionCleanupTimeMs,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??n.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??n.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??n.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??n.maxGlobOperations,maxStringLength:e.maxStringLength??n.maxStringLength,maxArrayElements:e.maxArrayElements??n.maxArrayElements,maxHeredocSize:e.maxHeredocSize??n.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??n.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??n.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??n.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??n.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??n.maxSourceDepth};for(let e of Object.keys(r)){let t=r[e];if(t!==1/0&&(!Number.isSafeInteger(t)||t<0))throw RangeError(`${e} must be a non-negative safe integer or positive Infinity`)}return r}function YDe(e){return`load`in e&&typeof e.load==`function`}function XDe(e){let t=null,n=null;return{name:e.name,trusted:e.trusted!==!1,async execute(r,i){if(!t){let r=n;r||(r=e.load().then(e=>(t=e,e)),n=r);try{t=await r}catch(e){throw n===r&&(n=null),e}}let a=t;if(!a)throw Error(`Failed to load command: ${e.name}`);return a.execute(r,i)}}}kB(),kB(),U(),mB();var G2=Object.freeze(Object.create(null)),ZDe=class{limits;signal;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(e,t=void 0){this.limits=e,this.signal=t}fail(e){throw this.poisoned??=e,this.poisoned}poisonAfterAbort(e){this.poisoned??=e}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw Error(`execution budget is already closed`);this.throwIfAborted()}chargeCommand(){return this.consume(`commands`,1,`execution`)}consumeWork(e=1,t=`execution`){return this.consume(`work`,e,t)}consumeLimited(e,t,n,r=e){this.assertUsable();let i=this.countersByKind.get(e)??0;return(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(n)||n<0||t>n-i)&&this.fail(new H(`${r}: ${e} work limit exceeded (${n})`,`iterations`)),t>this.limits.maxWorkUnits-this.workUnits&&this.fail(new H(`${r}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,`iterations`)),this.countersByKind.set(e,i+t),this.workUnits+=t,i+t}consumeInput(e,t=`execution`){return this.assertUsable(),(!Number.isSafeInteger(e)||e<0||e>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new H(`${t}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,`string_length`)),this.inputBytes+=e,this.inputBytes}consume(e,t=1,n=e){this.assertUsable();let r=this.countersByKind.get(e)??0,i=e===`commands`?this.commandCount:this.workUnits,a=e===`commands`?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(t)||t<0||t>a-i)&&this.fail(new H(e===`commands`?`too many commands executed (>${a}), increase executionLimits.maxCommandCount`:`${n}: ${e} work limit exceeded (${a})`,e===`commands`?`commands`:`iterations`));let o=i+t;return e===`commands`?this.commandCount=o:this.workUnits=o,this.countersByKind.set(e,r+t),o}reserveBytes(e,t,n){this.assertUsable();let r=typeof e==`string`?e:`live`,i=typeof e==`string`?t:e,a=typeof e==`string`?n??r:t??`execution`;(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new H(`${a}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,`string_length`)),this.liveBytes+=i,this.bytesByKind.set(r,(this.bytesByKind.get(r)??0)+i);let o=!1;return{release:()=>{if(o)return;o=!0,this.liveBytes-=i;let e=(this.bytesByKind.get(r)??i)-i;e<=0?this.bytesByKind.delete(r):this.bytesByKind.set(r,e)}}}appendOutput(e,t,n=`execution`,r=0,i=`text`){this.assertUsable();let a=i===`bytes`?t.length:V(t);(!Number.isSafeInteger(r)||r<0||r>a)&&this.fail(new H(`${n}: invalid ${e} accounting`,`output_size`));let o=a-r;return o>this.limits.maxOutputSize-this.outputBytes&&this.fail(new H(`${n}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,`output_size`)),this.outputBytes+=o,a}accountResult(e,t=`execution`,n=1/0){let r=e.internalOutputAccounting,i=Math.min(r?.stdout??0,n),a=Math.min(r?.stderr??0,Math.max(0,n-i)),o=this.appendOutput(`stdout`,e.stdout,t,i,e.stdoutKind===`bytes`||e.stdoutEncoding===`binary`?`bytes`:`text`),s=this.appendOutput(`stderr`,e.stderr,t,a);return Object.isExtensible(e)?(e.internalOutputAccounting={stdout:o,stderr:s},e):o===0&&s===0?e:{...e,internalOutputAccounting:{stdout:o,stderr:s}}}relinquishOutput(e,t,n){this.assertUsable(),n!==G2&&this.fail(new H(`${t}: unauthorized output accounting release`,`output_size`)),(!Number.isSafeInteger(e)||e<0||e>this.outputBytes)&&this.fail(new H(`${t}: invalid output accounting release`,`output_size`)),this.outputBytes-=e}enterDepth(e,t=this.limits.maxCallDepth,n){this.assertUsable();let r=typeof t==`number`?t:this.limits.maxCallDepth,i=typeof t==`string`?t:n??e,a=this.depthByKind.get(e)??0;a>=r&&this.fail(new H(`${i}: maximum depth (${r}) exceeded`,`recursion`)),this.depthByKind.set(e,a+1);let o=!1;return{release:()=>{if(o)return;o=!0;let t=(this.depthByKind.get(e)??1)-1;t<=0?this.depthByKind.delete(e):this.depthByKind.set(e,t)}}}throwIfAborted(e=`execution`){this.signal?.aborted&&this.fail(new HB(``,`bash: ${e} aborted +`)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new HB(``,`bash: ${e} exceeded execution deadline (${this.limits.maxExecutionTimeMs}ms) +`))}remainingTimeMs(){return Math.max(0,this.limits.maxExecutionTimeMs-(Date.now()-this.startedAt))}registerCleanup(e){this.assertUsable(),this.cleanupCallbacks.push(e);let t=!0;return()=>{if(!t)return;t=!1;let n=this.cleanupCallbacks.indexOf(e);n>=0&&this.cleanupCallbacks.splice(n,1)}}async close(){if(this.closed)return;this.closed=!0;let e=[],t=Date.now()+this.limits.maxExtensionCleanupTimeMs;for(let n=this.cleanupCallbacks.length-1;n>=0;n--)try{let r=t-Date.now();if(r<=0){e.push(Error(`execution cleanup grace period exceeded`));break}let i,a=await Promise.race([Promise.resolve().then(this.cleanupCallbacks[n]).then(()=>({ok:!0}),e=>({ok:!1,error:e})),new Promise(e=>{i=sB(()=>e({ok:!1,error:Error(`execution cleanup grace period exceeded`)}),r)})]);if(cB(i),!a.ok&&(e.push(a.error),Date.now()>=t))break}catch(t){e.push(t)}if(this.cleanupCallbacks.length=0,this.depthByKind.clear(),this.bytesByKind.clear(),this.liveBytes=0,e.length>0)throw AggregateError(e,`execution cleanup failed`)}assertExecDepth(e){this.assertUsable(),e>this.limits.maxExecDepth&&this.fail(new H(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,`recursion`))}};function QDe(e){let t=Object.create(null);return Object.defineProperties(t,{remainingLiveBytes:{enumerable:!0,get:()=>e.remainingLiveBytes},consumeWork:{enumerable:!0,value:e.consumeWork.bind(e)},consumeLimited:{enumerable:!0,value:e.consumeLimited.bind(e)},consumeInput:{enumerable:!0,value:e.consumeInput.bind(e)},reserveBytes:{enumerable:!0,value:e.reserveBytes.bind(e)},enterDepth:{enumerable:!0,value:e.enterDepth.bind(e)},throwIfAborted:{enumerable:!0,value:e.throwIfAborted.bind(e)},remainingTimeMs:{enumerable:!0,value:e.remainingTimeMs.bind(e)},registerCleanup:{enumerable:!0,value:e.registerCleanup.bind(e)}}),Object.freeze(t)}function $De(e,t,n=`pipeline`){e.relinquishOutput(t,n,G2)}kB(),O2(),hH();var K2=new TextEncoder;function eOe(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var q2=class{data=new Map;entryIdentities=new WeakMap;nextEntryIdentity=1;maxTotalBytes;retainedBytes=0;contentReferences=new WeakMap;materializedContent(e){return e?.type===`file`&&`content`in e?e.content:null}storedByteLength(e){return e===null?0:e instanceof Uint8Array?e.byteLength:V(e)}wouldReleaseBytes(e){let t=this.materializedContent(e);return t===null?0:t instanceof Uint8Array?this.contentReferences.get(t)===1?t.byteLength:0:this.storedByteLength(t)}assertCanAllocate(e,t){let n=this.wouldReleaseBytes(this.data.get(e));if(!Number.isSafeInteger(t)||t<0||t>this.maxTotalBytes-this.retainedBytes+n)throw Error(`ENOSPC: in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`)}setEntry(e,t){let n=this.data.get(e),r=this.materializedContent(n),i=this.materializedContent(t);if(r===i){this.data.set(e,t);return}let a=this.wouldReleaseBytes(n),o=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(o>this.maxTotalBytes-this.retainedBytes+a)throw Error(`ENOSPC: in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`);if(r instanceof Uint8Array){let e=this.contentReferences.get(r)??0;e<=1?this.contentReferences.delete(r):this.contentReferences.set(r,e-1)}i instanceof Uint8Array&&this.contentReferences.set(i,(this.contentReferences.get(i)??0)+1),this.retainedBytes+=o-a,this.data.set(e,t)}deleteEntry(e){let t=this.data.get(e);if(!t)return!1;let n=this.materializedContent(t),r=this.wouldReleaseBytes(t);if(n instanceof Uint8Array){let e=this.contentReferences.get(n)??0;e<=1?this.contentReferences.delete(n):this.contentReferences.set(n,e-1)}return this.retainedBytes-=r,this.data.delete(e)}contentByteLength(e,t){if(e instanceof Uint8Array)return e.byteLength;if(t===`hex`)return Math.floor(e.length/2);if(t===`base64`){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`);return Math.max(0,Math.floor(e.length*3/4)-t)}return t===`binary`||t===`latin1`?e.length:V(e)}identityFor(e){let t=this.entryIdentities.get(e);return t||(t=`memfs:${this.nextEntryIdentity++}`,this.entryIdentities.set(e,t)),t}constructor(e,t={}){if(this.maxTotalBytes=t.maxTotalBytes??1073741824,!Number.isSafeInteger(this.maxTotalBytes)||this.maxTotalBytes<0)throw Error(`InMemoryFs: invalid maxTotalBytes`);if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,n]of Object.entries(e))typeof n==`function`?this.writeFileLazy(t,n):eOe(n)?this.writeFileSync(t,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(t,n)}ensureParentDirs(e){let t=dH(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,n,r){uH(e,`write`);let i=cH(e);this.ensureParentDirs(i);let a=T2(n);this.assertCanAllocate(i,this.contentByteLength(t,a));let o=C2(t,a);this.setEntry(i,{type:`file`,content:o,mode:r?.mode??420,mtime:r?.mtime??new Date})}writeFileLazy(e,t,n){uH(e,`write`);let r=cH(e);this.ensureParentDirs(r),this.setEntry(r,{type:`file`,lazy:t,mode:n?.mode??420,mtime:n?.mtime??new Date})}async materializeLazy(e,t){let n=await t.lazy(),r=typeof n==`string`?K2.encode(n):n,i={type:`file`,content:r,mode:t.mode,mtime:t.mtime};return this.assertCanAllocate(e,r.byteLength),this.setEntry(e,i),i}async readFile(e,t){return w2(await this.readFileBuffer(e),T2(t))}async readFileBytes(e){return w2(await this.readFileBuffer(e),`binary`)}async readFileBuffer(e){uH(e,`open`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in n){let e=await this.materializeLazy(t,n);return e.content instanceof Uint8Array?e.content:K2.encode(e.content)}return n.content instanceof Uint8Array?n.content:K2.encode(n.content)}async writeFile(e,t,n){this.writeFileSync(e,t,n)}async appendFile(e,t,n){uH(e,`append`);let r=cH(e),i=this.data.get(r);if(i&&i.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=T2(n),o=this.contentByteLength(t,a);if(i?.type===`file`){let e=i;`lazy`in e&&(e=await this.materializeLazy(r,e));let n=`content`in e&&e.content instanceof Uint8Array?e.content:K2.encode(`content`in e?e.content:``);this.assertCanAllocate(r,n.byteLength+o);let s=C2(t,a),c=new Uint8Array(n.length+s.length);c.set(n),c.set(s,n.length),this.setEntry(r,{type:`file`,content:c,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,n)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){uH(e,`stat`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, stat '${e}'`);n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:K2.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date,identity:this.identityFor(n)}}async lstat(e){uH(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:K2.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date,identity:this.identityFor(n)}}resolveIntermediateSymlinks(e){let t=cH(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`);if(n.length<=1)return t;let r=``,i=new Set;for(let t=0;t=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(e){let t=cH(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`),r=``,i=new Set;for(let t of n){r=`${r}/${t}`;let n=this.data.get(r),a=0;for(;n&&n.type===`symlink`&&a<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(r),r=mH(r,n.target),n=this.data.get(r),a++}if(a>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return r}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){uH(e,`mkdir`);let n=cH(e);if(this.data.has(n)){if(this.data.get(n)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let r=dH(n);if(r!==`/`&&!this.data.has(r)){if(t?.recursive)this.mkdirSync(r,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`)}this.data.set(n,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){uH(e,`scandir`);let t=cH(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set;for(;n&&n.type===`symlink`;){if(r.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);r.add(t),t=mH(t,n.target),n=this.data.get(t)}if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let i=t===`/`?`/`:`${t}/`,a=new Map;for(let[e,n]of this.data.entries())if(e!==t&&e.startsWith(i)){let t=e.slice(i.length),r=t.split(`/`)[0];r&&!t.includes(`/`,r.length)&&!a.has(r)&&a.set(r,{name:r,isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`})}return Array.from(a.values()).sort((e,t)=>e.namet.name))}async rm(e,t){uH(e,`rm`);let n=cH(e),r=this.data.get(n);if(!r){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(r.type===`directory`){let r=await this.readdir(n);if(r.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of r){let r=pH(n,e);await this.rm(r,t)}}}this.deleteEntry(n)}async cp(e,t,n){uH(e,`cp`),uH(t,`cp`);let r=cH(e),i=cH(t),a=this.data.get(r);if(!a)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type===`file`){if(this.ensureParentDirs(i),`content`in a){let e=a.content instanceof Uint8Array?a.content.byteLength:K2.encode(a.content).byteLength;this.assertCanAllocate(i,e);let t=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.setEntry(i,{...a,content:t})}else this.setEntry(i,{...a})}else if(a.type===`symlink`)this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type===`directory`){if(!n?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);if(lH(r,i))throw Error(`EINVAL: cannot copy '${e}' into itself, '${t}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(r);for(let e of a){let t=pH(r,e),a=pH(i,e);await this.cp(t,a,n)}}}async mv(e,t){uH(e,`mv`),uH(t,`mv`);let n=cH(e),r=cH(t);if(n===r)return;let i=this.data.get(n);if(!i)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(i.type===`directory`&&lH(n,r))throw Error(`EINVAL: cannot move '${e}' into itself, '${t}'`);if(i.type===`directory`){await this.mkdir(r,{recursive:!0});let e=await this.readdir(n);for(let t of e)await this.mv(pH(n,t),pH(r,t));this.deleteEntry(n);return}this.ensureParentDirs(r),this.setEntry(r,i),this.deleteEntry(n)}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return fH(e,t)}async chmod(e,t){uH(e,`chmod`);let n=cH(e),r=this.data.get(n);if(!r)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);r.mode=t}async symlink(e,t){uH(t,`symlink`);let n=cH(t);if(this.data.has(n))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(n),this.data.set(n,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){uH(e,`link`),uH(t,`link`);let n=cH(e),r=cH(t),i=this.data.get(n);if(!i)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(r))throw Error(`EEXIST: file already exists, link '${t}'`);let a=i;`lazy`in a&&(a=await this.materializeLazy(n,a)),this.ensureParentDirs(r);let o={type:`file`,content:a.content,mode:a.mode,mtime:a.mtime};this.entryIdentities.set(o,this.identityFor(a)),this.setEntry(r,o)}async readlink(e){uH(e,`readlink`);let t=cH(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}async realpath(e){uH(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,n){uH(e,`utimes`);let r=cH(e),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);a.mtime=n}},tOe=`5.1.0(1)-release`,nOe=`Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT`;function J2(e){let{pid:t,ppid:n,uid:r,gid:i}=e;return`Name: bash +State: R (running) +Pid: ${t} +PPid: ${n} +Uid: ${r} ${r} ${r} ${r} +Gid: ${i} ${i} ${i} ${i} +`}function rOe(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function iOe(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function aOe(e){e.mkdirSync(`/dev`,{recursive:!0}),e.mkdirSync(`/dev/fd`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function oOe(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${nOe} +`),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash +`),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>J2(t)):e.writeFileSync(`/proc/self/status`,J2(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function sOe(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){rOe(e)&&(iOe(e,t),aOe(e),oOe(e,n))}vH(),tq(),U(),kB(),U();function Y2(e){return{kind:e.kind,elements:new Map(e.elements)}}function X2(e){return new Map(Array.from(e??[],([e,t])=>[e,Y2(t)]))}function Z2(e,t){return e.state.arrays?.get(t)}function Q2(e,t,n=`indexed`){e.state.arrays??=new Map;let r=e.state.arrays.get(t);return r||(r={kind:n,elements:new Map},e.state.arrays.set(t,r)),r}function $2(e,t,n){let r=Q2(e,t,n);return r.kind=n,r}function e4(e,t){return e.state.arrays?.has(t)??!1}function t4(e,t,n){return Z2(e,t)?.elements.get(String(n))}function n4(e,t,n){return Z2(e,t)?.elements.has(String(n))??!1}function r4(e,t,n,r,i){let a=Q2(e,t,i),o=String(n);if(!a.elements.has(o)&&a.elements.size>=e.limits.maxArrayElements)throw new H(`array element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);if(V(r)>e.limits.maxStringLength)throw new H(`array value string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);a.elements.set(o,r)}function i4(e,t,n,r=!1){let i=new Set(r?[]:Z2(e,t)?.elements.keys()??[]);for(let t of n)if(i.add(String(t)),i.size>e.limits.maxArrayElements)throw new H(`array element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`)}function a4(e,t,n){return Z2(e,t)?.elements.delete(String(n))??!1}function o4(e,t){e.state.arrays?.delete(t),e.state.associativeArrays?.delete(t)}function s4(e,t){return Array.from(Z2(e,t)?.elements.keys()??[]).filter(e=>/^(0|[1-9]\d*)$/.test(e)).map(Number).sort((e,t)=>e-t)}function c4(e,t){Q2(e,t,e.state.associativeArrays?.has(t)?`associative`:`indexed`).elements.clear()}function l4(e,t){return Array.from(Z2(e,t)?.elements.keys()??[]).sort()}function u4(e){return e.startsWith(`'`)&&e.endsWith(`'`)||e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}function d4(e){if(e.parts.length<2)return null;let t=e.parts[0],n=e.parts[1];if(t.type!==`Glob`||!t.pattern.startsWith(`[`))return null;let r,i=n,a=1;if(n.type===`Literal`&&n.value.startsWith(`]`)){let o=n.value.slice(1);if(o.startsWith(`+=`)||o.startsWith(`=`))r=t.pattern.slice(1);else if(o===``){if(e.parts.length<3)return null;let n=e.parts[2];if(n.type!==`Literal`||!n.value.startsWith(`=`)&&!n.value.startsWith(`+=`))return null;r=t.pattern.slice(1),i=n,a=2}else return null}else if(t.pattern===`[`&&(n.type===`DoubleQuoted`||n.type===`SingleQuoted`)){if(e.parts.length<3)return null;let t=e.parts[2];if(t.type!==`Literal`||!t.value.startsWith(`]=`)&&!t.value.startsWith(`]+=`))return null;if(n.type===`SingleQuoted`)r=n.value;else{r=``;for(let e of n.parts)(e.type===`Literal`||e.type===`Escaped`)&&(r+=e.value)}i=t,a=2}else if(t.pattern.endsWith(`]`)){if(n.type!==`Literal`||!n.value.startsWith(`=`)&&!n.value.startsWith(`+=`))return null;r=t.pattern.slice(1,-1)}else return null;r=u4(r);let o;if(i.type!==`Literal`)return null;o=i.value.startsWith(`]=`)||i.value.startsWith(`]+=`)?i.value.slice(1):i.value;let s=o.startsWith(`+=`);if(!s&&!o.startsWith(`=`))return null;let c=[],l=s?2:1,u=o.slice(l);u&&c.push({type:`Literal`,value:u});for(let t=a+1;t{if(e.type===`Range`){let t=`${e.startStr??String(e.start)}..${e.endStr??String(e.end)}`;return e.step&&(t+=`..${e.step}`),t}return f4(e.word)}).join(`,`)}}`}function f4(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:t+=n.value;break;case`Glob`:t+=n.pattern;break;case`SingleQuoted`:t+=n.value;break;case`DoubleQuoted`:for(let e of n.parts)(e.type===`Literal`||e.type===`Escaped`)&&(t+=e.value);break;case`Escaped`:t+=n.value;break;case`BraceExpansion`:t+=`{`,t+=n.items.map(e=>e.type===`Range`?`${e.startStr}..${e.endStr}${e.step?`..${e.step}`:``}`:f4(e.word)).join(`,`),t+=`}`;break;case`TildeExpansion`:t+=`~`,n.user&&(t+=n.user)}return t}var lOe=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],uOe=[`braceexpand`,`hashall`,`interactive-comments`];function p4(e){let t=[],n=[...uOe.map(e=>({name:e,enabled:!0})),...lOe.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of n)e.enabled&&t.push(e.name);return t.join(`:`)}function m4(e){e.state.env.set(`SHELLOPTS`,p4(e.state.options))}var dOe=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function h4(e){let t=[];for(let n of dOe)e[n]&&t.push(n);return t.join(`:`)}function g4(e){e.state.env.set(`BASHOPTS`,h4(e.state.shoptOptions))}kB(),oX(),tq();var X={script(e){return{type:`Script`,statements:e}},statement(e,t=[],n=!1,r,i){let a={type:`Statement`,pipelines:e,operators:t,background:n};return r&&(a.deferredError=r),i!==void 0&&(a.sourceText=i),a},pipeline(e,t=!1,n=!1,r=!1,i){return{type:`Pipeline`,commands:e,negated:t,timed:n,timePosix:r,pipeStderr:i}},simpleCommand(e,t=[],n=[],r=[]){return{type:`SimpleCommand`,name:e,args:t,assignments:n,redirections:r}},word(e){return{type:`Word`,parts:e}},literal(e){return{type:`Literal`,value:e}},singleQuoted(e){return{type:`SingleQuoted`,value:e}},doubleQuoted(e){return{type:`DoubleQuoted`,parts:e}},escaped(e){return{type:`Escaped`,value:e}},parameterExpansion(e,t=null){return{type:`ParameterExpansion`,parameter:e,operation:t}},commandSubstitution(e,t=!1){return{type:`CommandSubstitution`,body:e,legacy:t}},arithmeticExpansion(e){return{type:`ArithmeticExpansion`,expression:e}},processSubstitution(e,t){return{type:`ProcessSubstitution`,body:e,direction:t}},assignment(e,t,n=!1,r=null){return{type:`Assignment`,name:e,value:t,append:n,array:r}},redirection(e,t,n=null,r){let i={type:`Redirection`,fd:n,operator:e,target:t};return r&&(i.fdVariable=r),i},hereDoc(e,t,n=!1,r=!1,i){let a={type:`HereDoc`,delimiter:e,content:t,stripTabs:n,quoted:r};return i!==void 0&&(a.terminated=i),a},ifNode(e,t=null,n=[]){return{type:`If`,clauses:e,elseBody:t,redirections:n}},forNode(e,t,n,r=[]){return{type:`For`,variable:e,words:t,body:n,redirections:r}},whileNode(e,t,n=[]){return{type:`While`,condition:e,body:t,redirections:n}},untilNode(e,t,n=[]){return{type:`Until`,condition:e,body:t,redirections:n}},caseNode(e,t,n=[]){return{type:`Case`,word:e,items:t,redirections:n}},caseItem(e,t,n=`;;`){return{type:`CaseItem`,patterns:e,body:t,terminator:n}},subshell(e,t=[]){return{type:`Subshell`,body:e,redirections:t}},group(e,t=[]){return{type:`Group`,body:e,redirections:t}},functionDef(e,t,n=[],r){return{type:`FunctionDef`,name:e,body:t,redirections:n,sourceFile:r}},conditionalCommand(e,t=[],n){return{type:`ConditionalCommand`,expression:e,redirections:t,line:n}},arithmeticCommand(e,t=[],n){return{type:`ArithmeticCommand`,expression:e,redirections:t,line:n}}};function fOe(e,t){let n=e.length,r=t+3,i=2,a=!1,o=!1;for(;r0;){let t=e[r];if(a){t===`'`&&(a=!1),r++;continue}if(o){if(t===`\\`){r+=2;continue}t===`"`&&(o=!1),r++;continue}if(t===`'`){a=!0,r++;continue}if(t===`"`){o=!0,r++;continue}if(t===`\\`){r+=2;continue}if(t===`(`){i++,r++;continue}if(t===`)`){if(i--,i===1){let t=r+1;return!(te===` `||e===` `||e===` +`||e===`;`||e===`&`||e===`|`||e===`<`||e===`>`||e===`(`||e===`)`;for(;r0;for(s||(a=!0),s&&(n+=t),r++;r0;for(s||(a=!0),s&&(n+=t),r++;r0){n+=e.slice(r,r+2),r+=2;continue}a=!0;let t=e[r+1];t!==` +`&&(n+=t),r+=2;continue}if(i===0&&(t===`$`||t===`<`||t===`>`)&&e[r+1]===`(`){n+=`${t}(`,i=1,r+=2;continue}if(i===0&&s(t))break;i>0&&(t===`(`?i++:t===`)`&&i--),n+=t,r++}return{delim:n,endPos:r,quoted:a,unclosedQuote:o,unclosedSubstitution:i>0}}function pOe(e,t,n){let r=t+1;for(let{delim:t,stripTabs:i}of n)for(;;){if(r>=e.length)return e.length;let n=e.indexOf(` +`,r);n===-1&&(n=e.length);let a=e.slice(r,n);if(i&&(a=a.replace(/^\t+/,``)),a===t){r=n+1;break}if(n>=e.length)return e.length;r=n+1}return Math.min(r,e.length)}function v4(e,t,n){let r=1,i=t,a=!1,o=!1,s=0,c=!1,l=``,u=[],d=0;for(;i0;){let t=e[i];if(a)t===`'`&&(a=!1);else if(o)t===`\\`&&i+10&&d--,d===0&&t===`<`&&e[i+1]===`<`&&e[i+2]!==`<`){let t=i+2,r=!1;for(e[t]===`-`&&(r=!0,t++);e[t]===` `||e[t]===` `;)t++;let{delim:a,endPos:o,unclosedQuote:s,unclosedSubstitution:c}=_4(e,t);if(s&&n(`unexpected EOF while looking for matching \`${s}'`),c&&n("unexpected EOF while looking for matching `)'"),a.length>0){u.push({delim:a,stripTabs:r}),l=``,i=o;continue}}if(t===` +`&&u.length>0){let t=pOe(e,i,u);u.length=0,l=``,i=t;continue}t===`'`?(a=!0,l=``):t===`"`?(o=!0,l=``):t===`\\`&&i+10?c=!0:l===`esac`&&s>0&&(s--,c=!1),l=``,t===`(`?i>0&&e[i-1]===`$`?r++:c||r++:t===`)`?c?c=!1:r--:t===`;`&&s>0&&i+10&&i++}return r>0&&n("unexpected EOF while looking for matching `)'"),i}function mOe(e,t,n,r){let i=t+2,a=v4(e,i,r),o=e.slice(i,a),s=n().parse(o);return{part:X.commandSubstitution(s,!1),endIndex:a+1}}function hOe(e,t,n,r){let i=e[t]===`<`?`input`:`output`,a=t+2,o=v4(e,a,r),s=n().parse(e.slice(a,o));return{part:X.processSubstitution(s,i),endIndex:o+1}}function gOe(e,t,n,r,i){let a=t+1,o=``;for(;a=e.length&&i("unexpected EOF while looking for matching ``'");let s=r().parse(o);return{part:X.commandSubstitution(s,!0),endIndex:a+1}}var _Oe=10485760,Z;(function(e){e.EOF=`EOF`,e.NEWLINE=`NEWLINE`,e.SEMICOLON=`SEMICOLON`,e.AMP=`AMP`,e.PIPE=`PIPE`,e.PIPE_AMP=`PIPE_AMP`,e.AND_AND=`AND_AND`,e.OR_OR=`OR_OR`,e.BANG=`BANG`,e.LESS=`LESS`,e.GREAT=`GREAT`,e.DLESS=`DLESS`,e.DGREAT=`DGREAT`,e.LESSAND=`LESSAND`,e.GREATAND=`GREATAND`,e.LESSGREAT=`LESSGREAT`,e.DLESSDASH=`DLESSDASH`,e.CLOBBER=`CLOBBER`,e.TLESS=`TLESS`,e.AND_GREAT=`AND_GREAT`,e.AND_DGREAT=`AND_DGREAT`,e.LPAREN=`LPAREN`,e.RPAREN=`RPAREN`,e.LBRACE=`LBRACE`,e.RBRACE=`RBRACE`,e.DSEMI=`DSEMI`,e.SEMI_AND=`SEMI_AND`,e.SEMI_SEMI_AND=`SEMI_SEMI_AND`,e.DBRACK_START=`DBRACK_START`,e.DBRACK_END=`DBRACK_END`,e.DPAREN_START=`DPAREN_START`,e.DPAREN_END=`DPAREN_END`,e.IF=`IF`,e.THEN=`THEN`,e.ELSE=`ELSE`,e.ELIF=`ELIF`,e.FI=`FI`,e.FOR=`FOR`,e.WHILE=`WHILE`,e.UNTIL=`UNTIL`,e.DO=`DO`,e.DONE=`DONE`,e.CASE=`CASE`,e.ESAC=`ESAC`,e.IN=`IN`,e.FUNCTION=`FUNCTION`,e.SELECT=`SELECT`,e.TIME=`TIME`,e.COPROC=`COPROC`,e.WORD=`WORD`,e.NAME=`NAME`,e.NUMBER=`NUMBER`,e.ASSIGNMENT_WORD=`ASSIGNMENT_WORD`,e.FD_VARIABLE=`FD_VARIABLE`,e.COMMENT=`COMMENT`,e.HEREDOC_CONTENT=`HEREDOC_CONTENT`})(Z||={});var y4=class extends Error{line;column;constructor(e,t,n){super(`line ${t}: ${e}`),this.line=t,this.column=n,this.name=`LexerError`}},b4=new Map([[`if`,Z.IF],[`then`,Z.THEN],[`else`,Z.ELSE],[`elif`,Z.ELIF],[`fi`,Z.FI],[`for`,Z.FOR],[`while`,Z.WHILE],[`until`,Z.UNTIL],[`do`,Z.DO],[`done`,Z.DONE],[`case`,Z.CASE],[`esac`,Z.ESAC],[`in`,Z.IN],[`function`,Z.FUNCTION],[`select`,Z.SELECT],[`time`,Z.TIME],[`coproc`,Z.COPROC]]),vOe=new Set(b4.values());function x4(e){return vOe.has(e)}function S4(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return!1;let n=e.slice(t[0].length);if(n===``||n===`+`)return!0;if(n[0]===`[`){let e=0,t=0;for(;t=n.length)return!1;let r=n.slice(t+1);return r===``||r===`+`}return!1}function C4(e){let t=0;for(let n=0;n`,`>`,Z.AND_DGREAT]],bOe=[[`[`,`[`,Z.DBRACK_START],[`]`,`]`,Z.DBRACK_END],[`(`,`(`,Z.DPAREN_START],[`)`,`)`,Z.DPAREN_END],[`&`,`&`,Z.AND_AND],[`|`,`|`,Z.OR_OR],[`;`,`;`,Z.DSEMI],[`;`,`&`,Z.SEMI_AND],[`|`,`&`,Z.PIPE_AMP],[`>`,`>`,Z.DGREAT],[`<`,`&`,Z.LESSAND],[`>`,`&`,Z.GREATAND],[`<`,`>`,Z.LESSGREAT],[`>`,`|`,Z.CLOBBER],[`&`,`>`,Z.AND_GREAT]],xOe=new Map([[`|`,Z.PIPE],[`&`,Z.AMP],[`;`,Z.SEMICOLON],[`(`,Z.LPAREN],[`)`,Z.RPAREN],[`<`,Z.LESS],[`>`,Z.GREAT]]);function SOe(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function w4(e){return e===` `||e===` `||e===` +`||e===`;`||e===`&`||e===`|`||e===`(`||e===`)`||e===`<`||e===`>`}var COe=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];pendingHeredocDelimiterMode;dparenDepth=0;maxHeredocSize;constructor(e,t){this.input=e,this.maxHeredocSize=t?.maxHeredocSize??_Oe}tokenize(){let e=this.input.length,t=this.tokens,n=this.pendingHeredocs;for(;this.pos0&&t.length>0&&t[t.length-1].type===Z.NEWLINE){this.readHeredocContent();continue}if(this.skipWhitespace(),this.pos>=e)break;let r=this.nextToken();r&&t.push(r)}return n.length>0&&this.readHeredocContent(),t.push({type:Z.EOF,value:``,start:this.pos,end:this.pos,line:this.line,column:this.column}),t}skipWhitespace(){let e=this.input,t=e.length,n=this.pos,r=this.column,i=this.line;for(;n0?(this.pos=t+1,this.column=r+1,this.dparenDepth++,this.makeToken(Z.LPAREN,`(`,t,n,r)):this.looksLikeNestedSubshells(t+2)||this.dparenClosesWithSpacedParens(t+2)?(this.pos=t+1,this.column=r+1,this.makeToken(Z.LPAREN,`(`,t,n,r)):(this.pos=t+2,this.column=r+2,this.dparenDepth=1,this.makeToken(Z.DPAREN_START,`((`,t,n,r))}if(i===`)`&&a===`)`)return this.dparenDepth===1?(this.pos=t+2,this.column=r+2,this.dparenDepth=0,this.makeToken(Z.DPAREN_END,`))`,t,n,r)):this.dparenDepth>1?(this.pos=t+1,this.column=r+1,this.dparenDepth--,this.makeToken(Z.RPAREN,`)`,t,n,r)):(this.pos=t+1,this.column=r+1,this.makeToken(Z.RPAREN,`)`,t,n,r));for(let[o,s,c]of bOe)if(!(o===`(`&&s===`(`||o===`)`&&s===`)`)&&!(this.dparenDepth>0&&o===`;`&&(c===Z.DSEMI||c===Z.SEMI_AND||c===Z.SEMI_SEMI_AND))&&i===o&&a===s){if(c===Z.DBRACK_START||c===Z.DBRACK_END){let n=e[t+2];if(n!==void 0&&n!==` `&&n!==` `&&n!==` +`&&n!==`;`&&n!==`&`&&n!==`|`&&n!==`(`&&n!==`)`&&n!==`<`&&n!==`>`)break}return this.pos=t+2,this.column=r+2,this.makeToken(c,o+s,t,n,r)}if(i===`(`&&this.dparenDepth>0)return this.pos=t+1,this.column=r+1,this.dparenDepth++,this.makeToken(Z.LPAREN,`(`,t,n,r);if(i===`)`&&this.dparenDepth>1)return this.pos=t+1,this.column=r+1,this.dparenDepth--,this.makeToken(Z.RPAREN,`)`,t,n,r);let c=xOe.get(i);if(c!==void 0)return this.pos=t+1,this.column=r+1,this.makeToken(c,i,t,n,r);if(i===`{`){let e=this.scanFdVariable(t);return e===null?a===`}`?(this.pos=t+2,this.column=r+2,{type:Z.WORD,value:`{}`,start:t,end:t+2,line:n,column:r,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(t)===null&&this.scanLiteralBraceWord(t)===null?a!==void 0&&a!==` `&&a!==` `&&a!==` +`?this.readWord(t,n,r):(this.pos=t+1,this.column=r+1,this.makeToken(Z.LBRACE,`{`,t,n,r)):this.readWordWithBraceExpansion(t,n,r):(this.pos=e.end,this.column=r+(e.end-t),{type:Z.FD_VARIABLE,value:e.varname,start:t,end:e.end,line:n,column:r})}return i===`}`?this.isWordCharFollowing(t+1)?this.readWord(t,n,r):(this.pos=t+1,this.column=r+1,this.makeToken(Z.RBRACE,`}`,t,n,r)):i===`!`?a===`=`?(this.pos=t+2,this.column=r+2,this.makeToken(Z.WORD,`!=`,t,n,r)):(this.pos=t+1,this.column=r+1,this.makeToken(Z.BANG,`!`,t,n,r)):this.readWord(t,n,r)}looksLikeNestedSubshells(e){let t=this.input,n=t.length,r=e;for(;r=n)return!1;let i=t[r];if(i===`(`)return this.looksLikeNestedSubshells(r+1);let a=/[a-zA-Z_]/.test(i),o=i===`!`||i===`[`;if(!a&&!o)return!1;let s=r;for(;s=n)return!1;let l=t[c];if(l===`=`&&t[c+1]!==`=`||l===` +`||s===c&&/[+\-*/%<>&|^!~?:]/.test(l)&&l!==`-`||l===`)`&&t[c+1]===`)`)return!1;if(c>s&&(l===`-`||l===`"`||l===`'`||l===`$`||/[a-zA-Z_/.]/.test(l))){let e=c;for(;e`||e===`'`||e===`"`||e===`\\`||e===`$`||e==="`"||e===`{`||e===`}`||e===`~`||e===`*`||e===`?`||e===`[`)break;a++}if(a>o){let s=r[a];if(!(s===`(`&&a>o&&`@*+?!`.includes(r[a-1]))&&(a>=i||s===` `||s===` `||s===` +`||s===`;`||s===`&`||s===`|`||s===`(`||s===`)`||s===`<`||s===`>`)){let i=r.slice(o,a);this.pos=a,this.column=n+(a-o);let s=b4.get(i);if(s!==void 0)return{type:s,value:i,start:e,end:a,line:t,column:n};let c=C4(i);return c>0&&S4(i.slice(0,c))?{type:Z.ASSIGNMENT_WORD,value:i,start:e,end:a,line:t,column:n}:/^[0-9]+$/.test(i)?{type:Z.NUMBER,value:i,start:e,end:a,line:t,column:n}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)?{type:Z.NAME,value:i,start:e,end:a,line:t,column:n,quoted:!1,singleQuoted:!1}:{type:Z.WORD,value:i,start:e,end:a,line:t,column:n,quoted:!1,singleQuoted:!1}}}a=this.pos;let s=this.column,c=this.line,l=``,u=!1,d=!1,f=!1,p=!1,m=r[a]===`"`||r[a]===`'`,h=!1,g=0;for(;a0&&`@*+?!`.includes(l[l.length-1])){let e=this.scanExtglobPattern(a);if(e!==null){l+=e.content,a=e.end,s+=e.content.length;continue}}if(e===`[`&&g===0){if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l)){let t=a+10){l.length>0&&l[l.length-1]!==`\\`&&g++,l+=e,a++,s++;continue}else if(e===`]`&&g>0){l.length>0&&l[l.length-1]!==`\\`&&g--,l+=e,a++,s++;continue}if(g>0){if(e===` +`)break;l+=e,a++,s++;continue}if(e===` `||e===` `||e===` +`||e===`;`||e===`&`||e===`|`||e===`(`||e===`)`||e===`<`||e===`>`)break}if(e===`$`&&a+10&&a0&&h--,h===0&&e===`<`&&r[a+1]===`<`&&r[a+2]!==`<`){let e=a+2,t=!1;for(r[e]===`-`&&(t=!0,e++);r[e]===` `||r[e]===` `;)e++;let{delim:n,endPos:i,unclosedQuote:o,unclosedSubstitution:u}=_4(r,e);if(o)throw new y4(`unexpected EOF while looking for matching \`${o}'`,c,s);if(u)throw new y4("unexpected EOF while looking for matching `)'",c,s);if(n.length>0){l+=r.slice(a+1,i),s+=i-a,p.push({delim:n,stripTabs:t}),a=i;continue}}if(e===` +`&&p.length>0){c++,s=0;let e=a+1;for(let{delim:t,stripTabs:n}of p)for(;!(e>=i);){let a=r.indexOf(` +`,e);a===-1&&(a=i);let o=r.slice(e,a),s=n?o.replace(/^\t+/,``):o;l+=r.slice(e,Math.min(a+1,i)),a=i;if(e=a+1,s===t||u)break}p.length=0,s=0,a=Math.min(e,i);continue}if(e===`'`)n=!0,f=``;else if(e===`"`)o=!0,f=``;else if(e===`\\`&&a+10&&a0?d=!0:f===`esac`&&u>0&&(u--,d=!1),f=``,e===`(`?a>0&&r[a-1]===`$`?t++:d||t++:e===`)`?d?d=!1:t--:e===`;`&&u>0&&(a+10&&a0&&a=`0`&&t<=`9`){l+=e+t,a+=2,s+=2;continue}}if(e==="`"&&!f){for(l+=e,a++,s++;a=2){if(l[0]===`'`&&l[l.length-1]===`'`){let e=l.slice(1,-1);!e.includes(`'`)&&!e.includes(`"`)&&(l=e,u=!0,d=!0)}else if(l[0]===`"`&&l[l.length-1]===`"`){let e=l.slice(1,-1),t=!1;for(let n=0;n0&&S4(l.slice(0,r)))return{type:Z.ASSIGNMENT_WORD,value:l,start:e,end:a,line:t,column:n,quoted:u,singleQuoted:d}}return/^[0-9]+$/.test(l)?{type:Z.NUMBER,value:l,start:e,end:a,line:t,column:n}:SOe(l)?{type:Z.NAME,value:l,start:e,end:a,line:t,column:n,quoted:u,singleQuoted:d}:{type:Z.WORD,value:l,start:e,end:a,line:t,column:n,quoted:u,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let t=this.pos,n=this.line,r=this.column,i=``,a=!1;for(;this.pos=this.input.length)break;s=s.slice(0,-1),o+=`${t} +`,this.pos++,this.line++,this.column=1}if((e.stripTabs?s.replace(/^\t+/,``):s)===e.delimiter){a=!0,this.pos0&&(i+=` +`),i.length>this.maxHeredocSize)throw new y4(`Heredoc size limit exceeded (${this.maxHeredocSize} bytes)`,n,r)}this.tokens.push({type:Z.HEREDOC_CONTENT,value:i,start:t,end:this.pos,line:n,column:r,heredocTerminated:a})}}readHeredocDelimiterToken(e,t,n,r){let i=this.input,{delim:a,endPos:o,quoted:s,unclosedQuote:c,unclosedSubstitution:l}=_4(i,e);if(c)throw new y4(`unexpected EOF while looking for matching \`${c}'`,t,n);if(l)throw new y4("unexpected EOF while looking for matching `)'",t,n);if(o===e)throw new y4(`Expected here-document delimiter`,t,n);let u=t,d=n;for(let t=e;t=this.input.length)return!1;let t=this.input[e];return t!==` `&&t!==` `&&t!==` +`&&t!==`;`&&t!==`&`&&t!==`|`&&t!==`(`&&t!==`)`&&t!==`<`&&t!==`>`}readWordWithBraceExpansion(e,t,n){let r=this.input,i=r.length,a=e,o=n;for(;a`)break;if(e===`{`){if(this.scanBraceExpansion(a)!==null){let e=1;for(a++,o++;a0;)r[a]===`{`?e++:r[a]===`}`&&e--,a++,o++;continue}a++,o++;continue}if(e===`}`){a++,o++;continue}if(e===`$`&&a+10&&a0&&a0;){let e=t[r];if(e===`{`)i++,r++;else if(e===`}`)i--,r++;else if(e===`,`&&i===1)a=!0,r++;else if(e===`.`&&r+10;){let n=t[r];if(n===`{`)i++,r++;else if(n===`}`){if(i--,i===0)return t.slice(e,r+1);r++}else{if(n===` `||n===` `||n===` +`||n===`;`||n===`&`||n===`|`)return null;r++}}return null}scanExtglobPattern(e){let t=this.input,n=t.length,r=e+1,i=1;for(;r0;){let e=t[r];if(e===`\\`&&r+1=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`_`))return null}else if(!(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`_`))break;r++}if(r===i)return null;let a=t.slice(i,r);if(r>=n||t[r]!==`}`||(r++,r>=n))return null;let o=t[r],s=r+1`||o===`<`||o===`&`&&(s===`>`||s===`<`)?{varname:a,end:r}:null}dollarDparenIsSubshell(e){let t=this.input,n=t.length,r=e+1,i=2,a=!1,o=!1,s=!1;for(;r0;){let e=t[r];if(a){e===`'`&&(a=!1),e===` +`&&(s=!0),r++;continue}if(o){if(e===`\\`){r+=2;continue}e===`"`&&(o=!1),e===` +`&&(s=!0),r++;continue}if(e===`'`){a=!0,r++;continue}if(e===`"`){o=!0,r++;continue}if(e===`\\`){r+=2;continue}if(e===` +`&&(s=!0),e===`(`){i++,r++;continue}if(e===`)`){if(i--,i===1){let e=r+1;if(e0;){let e=t[r];if(a){e===`'`&&(a=!1),r++;continue}if(o){if(e===`\\`){r+=2;continue}e===`"`&&(o=!1),r++;continue}if(e===`'`){a=!0,r++;continue}if(e===`"`){o=!0,r++;continue}if(e===`\\`){r+=2;continue}if(e===`(`){i++,r++;continue}if(e===`)`){if(i--,i===1){let e=r+1;if(ewOe)throw new k4(`Maximum parse iterations exceeded (possible infinite loop)`,e,t)}chargeTokens(e,t=1,n=1){if(this.tokens+=e,this.tokens>E4)throw new k4(`Too many tokens: cumulative count exceeds limit of ${E4}`,t,n)}enter(e,t){if(this.depth++,this.depth>D4)throw this.depth--,new k4(`Maximum parser nesting depth exceeded (${D4})`,e,t);let n=!0;return()=>{n&&(n=!1,this.depth--)}}};aB(),XB(),U();function A4(e,t){for(;t>=`,`&=`,`|=`,`^=`];function M4(e){if(e.includes(`#`)){let t=e.split(`#`);if(t.length!==2)return NaN;let[n,r]=t;if(!/^\d+$/.test(n)||r.length===0)return NaN;let i=Number.parseInt(n,10);if(i<2||i>64)return NaN;let a=0;for(let e of r){let t;if(/[0-9]/.test(e))t=e.charCodeAt(0)-48;else if(/[a-z]/.test(e))t=e.charCodeAt(0)-97+10;else if(/[A-Z]/.test(e))t=e.charCodeAt(0)-65+(i<=36?10:36);else if(e===`@`)t=62;else if(e===`_`)t=63;else return NaN;if(t>=i)return NaN;if(a=a*i+t,a>2**53-1)return 2**53-1}return a}if(e.startsWith(`0x`)||e.startsWith(`0X`)){let t=Number.parseInt(e.slice(2),16);return t>2**53-1?2**53-1:t}if(e.startsWith(`0`)&&e.length>1&&/^[0-9]+$/.test(e)){if(/[89]/.test(e))return NaN;let t=Number.parseInt(e,8);return t>2**53-1?2**53-1:t}let t=Number.parseInt(e,10);return t>2**53-1?2**53-1:t}function kOe(e,t,n,r){if(n.slice(r,r+3)!==`$((`)return null;let i=r+3,a=1,o=i;for(;i0;)n[i]===`(`&&n[i+1]===`(`?(a++,i+=2):n[i]===`)`&&n[i+1]===`)`?(a--,a>0&&(i+=2)):i++;let{expr:s}=e(t,n.slice(o,i),0);return i+=2,{expr:{type:`ArithNested`,expression:s},pos:i}}function AOe(e,t){if(e.slice(t,t+2)!==`$'`)return null;let n=t+2,r=``;for(;n=e.length}function I4(e,t,n){return NOe(e,t,n)}function L4(e,t,n){return e.withDepth(()=>I4(e,t,n))}function NOe(e,t,n){let{expr:r,pos:i}=R4(e,t,n);for(i=A4(t,i);t[i]===`,`;){if(i++,F4(t,i))return P4(`,`,i);let{expr:n,pos:a}=R4(e,t,i);r={type:`ArithBinary`,operator:`,`,left:r,right:n},i=A4(t,a)}return{expr:r,pos:i}}function R4(e,t,n){let{expr:r,pos:i}=POe(e,t,n);if(i=A4(t,i),t[i]===`?`){i++;let{expr:n,pos:a}=L4(e,t,i);if(i=A4(t,a),t[i]===`:`){i++;let{expr:a,pos:o}=L4(e,t,i);return{expr:{type:`ArithTernary`,condition:r,consequent:n,alternate:a},pos:o}}}return{expr:r,pos:i}}function POe(e,t,n){let{expr:r,pos:i}=z4(e,t,n);for(;i=A4(t,i),t.slice(i,i+2)===`||`;){if(i+=2,F4(t,i))return P4(`||`,i);let{expr:n,pos:a}=z4(e,t,i);r={type:`ArithBinary`,operator:`||`,left:r,right:n},i=a}return{expr:r,pos:i}}function z4(e,t,n){let{expr:r,pos:i}=B4(e,t,n);for(;i=A4(t,i),t.slice(i,i+2)===`&&`;){if(i+=2,F4(t,i))return P4(`&&`,i);let{expr:n,pos:a}=B4(e,t,i);r={type:`ArithBinary`,operator:`&&`,left:r,right:n},i=a}return{expr:r,pos:i}}function B4(e,t,n){let{expr:r,pos:i}=V4(e,t,n);for(;i=A4(t,i),t[i]===`|`&&t[i+1]!==`|`;){if(i++,F4(t,i))return P4(`|`,i);let{expr:n,pos:a}=V4(e,t,i);r={type:`ArithBinary`,operator:`|`,left:r,right:n},i=a}return{expr:r,pos:i}}function V4(e,t,n){let{expr:r,pos:i}=H4(e,t,n);for(;i=A4(t,i),t[i]===`^`;){if(i++,F4(t,i))return P4(`^`,i);let{expr:n,pos:a}=H4(e,t,i);r={type:`ArithBinary`,operator:`^`,left:r,right:n},i=a}return{expr:r,pos:i}}function H4(e,t,n){let{expr:r,pos:i}=U4(e,t,n);for(;i=A4(t,i),t[i]===`&`&&t[i+1]!==`&`;){if(i++,F4(t,i))return P4(`&`,i);let{expr:n,pos:a}=U4(e,t,i);r={type:`ArithBinary`,operator:`&`,left:r,right:n},i=a}return{expr:r,pos:i}}function U4(e,t,n){let{expr:r,pos:i}=W4(e,t,n);for(;i=A4(t,i),t.slice(i,i+2)===`==`||t.slice(i,i+2)===`!=`;){let n=t.slice(i,i+2);if(i+=2,F4(t,i))return P4(n,i);let{expr:a,pos:o}=W4(e,t,i);r={type:`ArithBinary`,operator:n,left:r,right:a},i=o}return{expr:r,pos:i}}function W4(e,t,n){let{expr:r,pos:i}=G4(e,t,n);for(;;)if(i=A4(t,i),t.slice(i,i+2)===`<=`||t.slice(i,i+2)===`>=`){let n=t.slice(i,i+2);if(i+=2,F4(t,i))return P4(n,i);let{expr:a,pos:o}=G4(e,t,i);r={type:`ArithBinary`,operator:n,left:r,right:a},i=o}else if(t[i]===`<`||t[i]===`>`){let n=t[i];if(i++,F4(t,i))return P4(n,i);let{expr:a,pos:o}=G4(e,t,i);r={type:`ArithBinary`,operator:n,left:r,right:a},i=o}else break;return{expr:r,pos:i}}function G4(e,t,n){let{expr:r,pos:i}=K4(e,t,n);for(;i=A4(t,i),t.slice(i,i+2)===`<<`||t.slice(i,i+2)===`>>`;){let n=t.slice(i,i+2);if(i+=2,F4(t,i))return P4(n,i);let{expr:a,pos:o}=K4(e,t,i);r={type:`ArithBinary`,operator:n,left:r,right:a},i=o}return{expr:r,pos:i}}function K4(e,t,n){let{expr:r,pos:i}=q4(e,t,n);for(;i=A4(t,i),(t[i]===`+`||t[i]===`-`)&&t[i+1]!==t[i];){let n=t[i];if(i++,F4(t,i))return P4(n,i);let{expr:a,pos:o}=q4(e,t,i);r={type:`ArithBinary`,operator:n,left:r,right:a},i=o}return{expr:r,pos:i}}function q4(e,t,n){let{expr:r,pos:i}=J4(e,t,n);for(;;)if(i=A4(t,i),t[i]===`*`&&t[i+1]!==`*`){if(i++,F4(t,i))return P4(`*`,i);let{expr:n,pos:a}=J4(e,t,i);r={type:`ArithBinary`,operator:`*`,left:r,right:n},i=a}else if(t[i]===`/`||t[i]===`%`){let n=t[i];if(i++,F4(t,i))return P4(n,i);let{expr:a,pos:o}=J4(e,t,i);r={type:`ArithBinary`,operator:n,left:r,right:a},i=o}else break;return{expr:r,pos:i}}function J4(e,t,n){let{expr:r,pos:i}=Y4(e,t,n),a=A4(t,i);if(t.slice(a,a+2)===`**`){if(a+=2,F4(t,a))return P4(`**`,a);let{expr:n,pos:i}=e.withDepth(()=>J4(e,t,a));return{expr:{type:`ArithBinary`,operator:`**`,left:r,right:n},pos:i}}return{expr:r,pos:i}}function Y4(e,t,n){let r=A4(t,n);if(t.slice(r,r+2)===`++`||t.slice(r,r+2)===`--`){let n=t.slice(r,r+2);r+=2;let{expr:i,pos:a}=e.withDepth(()=>Y4(e,t,r));return{expr:{type:`ArithUnary`,operator:n,operand:i,prefix:!0},pos:a}}if(t[r]===`+`||t[r]===`-`||t[r]===`!`||t[r]===`~`){let n=t[r];r++;let{expr:i,pos:a}=e.withDepth(()=>Y4(e,t,r));return{expr:{type:`ArithUnary`,operator:n,operand:i,prefix:!0},pos:a}}return IOe(e,t,r)}function FOe(e,t){let n=e[t];return n===`$`||n==="`"}function IOe(e,t,n){let{expr:r,pos:i}=X4(e,t,n,!1),a=[r];for(;FOe(t,i);){let{expr:n,pos:r}=X4(e,t,i,!0);a.push(n),i=r}a.length>1&&(r={type:`ArithConcat`,parts:a});let o;if(t[i]===`[`&&r.type===`ArithConcat`){i++;let{expr:n,pos:r}=L4(e,t,i);o=n,i=r,t[i]===`]`&&i++}if(o&&r.type===`ArithConcat`&&(r={type:`ArithDynamicElement`,nameExpr:r,subscript:o},o=void 0),i=A4(t,i),r.type===`ArithConcat`||r.type===`ArithVariable`||r.type===`ArithDynamicElement`){for(let n of j4)if(t.slice(i,i+n.length)===n&&t.slice(i,i+n.length+1)!==`==`){i+=n.length;let{expr:a,pos:o}=e.withDepth(()=>R4(e,t,i));return r.type===`ArithDynamicElement`?{expr:{type:`ArithDynamicAssignment`,operator:n,target:r.nameExpr,subscript:r.subscript,value:a},pos:o}:r.type===`ArithConcat`?{expr:{type:`ArithDynamicAssignment`,operator:n,target:r,value:a},pos:o}:{expr:{type:`ArithAssignment`,operator:n,variable:r.name,value:a},pos:o}}}if(t.slice(i,i+2)===`++`||t.slice(i,i+2)===`--`){let e=t.slice(i,i+2);return i+=2,{expr:{type:`ArithUnary`,operator:e,operand:r,prefix:!1},pos:i}}return{expr:r,pos:i}}function X4(e,t,n,r=!1){let i=A4(t,n),a=kOe(L4,e,t,i);if(a)return a;let o=AOe(t,i);if(o)return o;let s=jOe(t,i);if(s)return s;if(t.slice(i,i+2)===`$(`&&t[i+2]!==`(`){i+=2;let e=1,n=i;for(;i0;)t[i]===`(`?e++:t[i]===`)`&&e--,e>0&&i++;let r=t.slice(n,i);return i++,{expr:{type:`ArithCommandSubst`,command:r},pos:i}}if(t[i]==="`"){i++;let e=i;for(;i0;)t[r]===`{`?n++:t[r]===`}`&&n--,n>0&&r++;let a=t.slice(e,r),o=r+1;if(t[o]===`#`){let e=o+1;for(;eR4(e,t,i));return{expr:{type:`ArithAssignment`,operator:r,variable:n,subscript:o,stringKey:a,value:s},pos:c}}}return{expr:{type:`ArithArrayElement`,array:n,index:o,stringKey:a},pos:i}}if(i=A4(t,i),!r){for(let r of j4)if(t.slice(i,i+r.length)===r&&t.slice(i,i+r.length+1)!==`==`){i+=r.length;let{expr:a,pos:o}=e.withDepth(()=>R4(e,t,i));return{expr:{type:`ArithAssignment`,operator:r,variable:n,value:a},pos:o}}}return{expr:{type:`ArithVariable`,name:n,hasDollarPrefix:c},pos:i}}if(t[i]===`#`){let e=i+1;for(;e{let t,n=``;for(let r=0;r=194){let i=(r&31)<<6|e[n+1]&63;t+=String.fromCharCode(i),n+=2;continue}t+=String.fromCharCode(r),n++;continue}if((r&240)==224){if(n+2=55296&&i<=57343){t+=String.fromCharCode(r),n++;continue}t+=String.fromCharCode(i),n+=3;continue}t+=String.fromCharCode(r),n++;continue}if((r&248)==240&&r<=244){if(n+31114111){t+=String.fromCharCode(r),n++;continue}t+=String.fromCodePoint(i),n+=4;continue}t+=String.fromCharCode(r),n++;continue}t+=String.fromCharCode(r),n++}return t}function ROe(e,t,n){let r=n+1;for(;r0;)t[o]===r?a++:t[o]===i&&a--,a>0&&o++;return a===0?o:-1}function $4(e,t,n){let r=n,i=1;for(;r0;){let e=t[r];if(e===`\\`&&r+10&&r++}return r}function zOe(e,t,n){let r=n,i=!1;for(;r0)e.push(i),n+=2+r.length;else break}e.length>0?(r+=LOe(e),i=n):(r+=`\\x`,i+=2);break}case`u`:{let e=t.slice(i+2,i+6),n=parseInt(e,16);Number.isNaN(n)?(r+=`\\u`,i+=2):(r+=String.fromCharCode(n),i+=6);break}case`c`:if(i+2e.withDepth(()=>({type:`Word`,word:X.word(r(e,t,!1,!1,!1))})))},endIndex:i+1}:a.includes(`,`)?{part:{type:`BraceExpansion`,items:t3(a).map(e=>({type:`Word`,word:X.word([X.literal(e)])}))},endIndex:i+1}:null}function n3(e,t){let n=``;for(let r of t.parts)switch(r.type){case`Literal`:n+=r.value;break;case`SingleQuoted`:n+=`'${r.value}'`;break;case`Escaped`:n+=r.value;break;case`DoubleQuoted`:n+=`"`;for(let e of r.parts)e.type===`Literal`||e.type===`Escaped`?n+=e.value:e.type===`ParameterExpansion`&&(n+=`\${${e.parameter}}`);n+=`"`;break;case`ParameterExpansion`:n+=`\${${r.parameter}}`;break;case`Glob`:n+=r.pattern;break;case`TildeExpansion`:n+=`~`,r.user&&(n+=r.user);break;case`BraceExpansion`:{n+=`{`;let t=[];for(let n of r.items)if(n.type===`Range`){let e=n.startStr??String(n.start),r=n.endStr??String(n.end);n.step===void 0?t.push(`${e}..${r}`):t.push(`${e}..${r}..${n.step}`)}else t.push(n3(e,n.word));t.length===1&&r.items[0].type===`Range`?n+=t[0]:n+=t.join(`,`),n+=`}`;break}default:n+=r.type}return n}function WOe(e,t){return{[Z.LESS]:`<`,[Z.GREAT]:`>`,[Z.DGREAT]:`>>`,[Z.LESSAND]:`<&`,[Z.GREATAND]:`>&`,[Z.LESSGREAT]:`<>`,[Z.CLOBBER]:`>|`,[Z.TLESS]:`<<<`,[Z.AND_GREAT]:`&>`,[Z.AND_DGREAT]:`&>>`,[Z.DLESS]:`<`,[Z.DLESSDASH]:`<`}[t]||`>`}function r3(e){let t=e.current(),n=t.type;if(n===Z.NUMBER){let n=e.peek(1);return t.end!==n.start||e.isProcessSubstitutionStart(1)?!1:EOe.has(n.type)}if(n===Z.FD_VARIABLE){let n=e.peek(1);return t.end!==n.start||e.isProcessSubstitutionStart(1)?!1:DOe.has(n.type)}return!e.isProcessSubstitutionStart()&&TOe.has(n)}function i3(e){let t=null,n;e.check(Z.NUMBER)?t=Number.parseInt(e.advance().value,10):e.check(Z.FD_VARIABLE)&&(n=e.advance().value);let r=e.advance(),i=WOe(e,r.type);if(r.type===Z.DLESS||r.type===Z.DLESSDASH)return GOe(e,t,n,r.type===Z.DLESSDASH);e.isWord()||e.error(`Expected redirection target`);let a=e.parseWord();return X.redirection(i,a,t,n)}function GOe(e,t,n,r){e.isWord()||e.error(`Expected here-document delimiter`);let i=e.advance(),a=i.heredocDelimiter??i.value,o=i.quoted||!1,s=X.redirection(r?`<<-`:`<<`,X.hereDoc(a,X.word([]),r,o),t,n);return e.addPendingHeredoc(s,a,r,o),s}function a3(e){let t=e.getSourceLine(),n=[],r=null,i=[],a=[];for(;e.check(Z.ASSIGNMENT_WORD)||r3(e);)e.checkIterationLimit(),e.check(Z.ASSIGNMENT_WORD)?n.push(KOe(e)):a.push(i3(e));if(e.isWord())r=e.parseWord();else if(n.length>0&&(e.check(Z.DBRACK_START)||e.check(Z.DPAREN_START))){let t=e.advance();r=X.word([X.literal(t.value)])}for(;(!e.isStatementEnd()||e.check(Z.RBRACE))&&!e.check(Z.PIPE,Z.PIPE_AMP);)if(e.checkIterationLimit(),r3(e))a.push(i3(e));else if(e.check(Z.ASSIGNMENT_WORD)){let t=e.advance(),n=t.value,r=n.endsWith(`=`),a=n.endsWith(`=(`);if((r||a)&&(a||e.check(Z.LPAREN))){let t=a?n.slice(0,-2):n.slice(0,-1);a||e.expect(Z.LPAREN);let r=o3(e);e.expect(Z.RPAREN);let o=`${t}=(${r.map(t=>n3(e,t)).join(` `)})`;i.push(e.parseWordFromString(o,!1,!1,!0))}else{let r=e.parseWordFromString(n,t.quoted,t.singleQuoted,!0);i.push(e.parseAdjacentWordParts(r.parts,t.end,O4.Assignment))}}else if(e.isWord())i.push(e.parseWord());else if(e.check(Z.RBRACE)){let t=e.advance();i.push(e.parseWordFromString(t.value,!1,!1))}else if(e.check(Z.LBRACE)){let t=e.advance();i.push(e.parseWordFromString(t.value,!1,!1))}else if(e.check(Z.DBRACK_END)){let t=e.advance();i.push(e.parseWordFromString(t.value,!1,!1))}else if(e.check(Z.LPAREN))e.error("syntax error near unexpected token `('");else break;let o=X.simpleCommand(r,i,n,a);return o.line=t,o}function KOe(e){let t=e.expect(Z.ASSIGNMENT_WORD),n=t.value,r=n.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||e.error(`Invalid assignment: ${n}`);let i=r[0],a,o=i.length;if(n[o]===`[`){let t=0,r=o+1;for(;o2)break}else t.value===`(`&&c++,t.value===`)`&&c--,o[s]+=t.value}e.expect(Z.DPAREN_END),o[0].trim()&&(r=N4(e,o[0].trim())),o[1].trim()&&(i=N4(e,o[1].trim())),o[2].trim()&&(a=N4(e,o[2].trim())),e.skipNewlines(),e.check(Z.SEMICOLON)&&e.advance(),e.skipNewlines();let l;e.check(Z.LBRACE)?(e.advance(),l=e.parseCompoundList(),e.expect(Z.RBRACE)):(e.expect(Z.DO),l=e.parseCompoundList(),e.expect(Z.DONE));let u=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:`CStyleFor`,init:r,condition:i,update:a,body:l,redirections:u,line:n}}function l3(e,t){e.expect(Z.WHILE);let n=e.parseCompoundList();e.expect(Z.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(Z.DONE);let i=t?.skipRedirections?[]:e.parseOptionalRedirections();return X.whileNode(n,r,i)}function u3(e,t){e.expect(Z.UNTIL);let n=e.parseCompoundList();e.expect(Z.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(Z.DONE);let i=t?.skipRedirections?[]:e.parseOptionalRedirections();return X.untilNode(n,r,i)}function d3(e,t){e.expect(Z.CASE),e.isWord()||e.error(`Expected word after 'case'`);let n=e.parseWord();e.skipNewlines(),e.expect(Z.IN),e.skipNewlines();let r=[];for(;!e.check(Z.ESAC,Z.EOF);){e.checkIterationLimit();let t=e.getPos(),n=YOe(e);if(n&&r.push(n),e.skipNewlines(),e.getPos()===t&&!n)break}e.expect(Z.ESAC);let i=t?.skipRedirections?[]:e.parseOptionalRedirections();return X.caseNode(n,r,i)}function YOe(e){e.check(Z.LPAREN)&&e.advance();let t=[];for(;e.isWord()&&(t.push(e.parseWord()),e.check(Z.PIPE));)e.advance();if(t.length===0)return null;e.expect(Z.RPAREN),e.skipNewlines();let n=[];for(;!e.check(Z.DSEMI,Z.SEMI_AND,Z.SEMI_SEMI_AND,Z.ESAC,Z.EOF);){e.checkIterationLimit(),e.isWord()&&e.peek(1).type===Z.RPAREN&&e.error("syntax error near unexpected token `)'"),e.check(Z.LPAREN)&&e.peek(1).type===Z.WORD&&e.error(`syntax error near unexpected token \`${e.peek(1).value}'`);let t=e.getPos(),r=e.parseStatement();if(r&&n.push(r),e.skipSeparators(!1),e.getPos()===t&&!r)break}let r=`;;`;return e.check(Z.DSEMI)?(e.advance(),r=`;;`):e.check(Z.SEMI_AND)?(e.advance(),r=`;&`):e.check(Z.SEMI_SEMI_AND)&&(e.advance(),r=`;;&`),X.caseItem(t,n,r)}function f3(e,t){e.expect(Z.LPAREN);let n=e.parseCompoundList();e.expect(Z.RPAREN);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return X.subshell(n,r)}function p3(e,t){e.expect(Z.LBRACE);let n=e.parseCompoundList();e.expect(Z.RBRACE);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return X.group(n,r)}var XOe=`-a.-b.-c.-d.-e.-f.-g.-h.-k.-p.-r.-s.-t.-u.-w.-x.-G.-L.-N.-O.-S.-z.-n.-o.-v.-R`.split(`.`),ZOe=[`==`,`!=`,`=~`,`<`,`>`,`-eq`,`-ne`,`-lt`,`-le`,`-gt`,`-ge`,`-nt`,`-ot`,`-ef`];function m3(e){return e.isWord()||e.check(Z.LBRACE)||e.check(Z.RBRACE)||e.check(Z.ASSIGNMENT_WORD)}function h3(e){if(e.check(Z.BANG)&&e.peek(1).type===Z.LPAREN){e.advance(),e.advance();let t=1,n=`!(`;for(;t>0&&!e.check(Z.EOF);)if(e.check(Z.LPAREN))t++,n+=`(`,e.advance();else if(e.check(Z.RPAREN))t--,t>0&&(n+=`)`),e.advance();else if(e.isWord())n+=e.advance().value;else if(e.check(Z.PIPE))n+=`|`,e.advance();else break;return n+=`)`,e.parseWordFromString(n,!1,!1,!1,!1,!0)}return e.parseWordNoBraceExpansion()}function g3(e){return e.skipNewlines(),QOe(e)}function QOe(e){let t=_3(e);for(e.skipNewlines();e.check(Z.OR_OR);){e.advance(),e.skipNewlines();let n=_3(e);t={type:`CondOr`,left:t,right:n},e.skipNewlines()}return t}function _3(e){let t=v3(e);for(e.skipNewlines();e.check(Z.AND_AND);){e.advance(),e.skipNewlines();let n=v3(e);t={type:`CondAnd`,left:t,right:n},e.skipNewlines()}return t}function v3(e){return e.skipNewlines(),e.check(Z.BANG)?(e.advance(),e.skipNewlines(),{type:`CondNot`,operand:e.withDepth(()=>v3(e))}):$Oe(e)}function $Oe(e){if(e.check(Z.LPAREN)){e.advance();let t=e.withDepth(()=>g3(e));return e.expect(Z.RPAREN),{type:`CondGroup`,expression:t}}if(m3(e)){let t=e.current(),n=t.value;if(XOe.includes(n)&&!t.quoted){if(e.advance(),e.check(Z.DBRACK_END)&&e.error(`Expected operand after ${n}`),m3(e))return{type:`CondUnary`,operator:n,operand:e.parseWordNoBraceExpansion()};let t=e.current();e.error(`unexpected argument \`${t.value}' to conditional unary operator`)}let r=e.parseWordNoBraceExpansion();if(e.isWord()&&ZOe.includes(e.current().value)){let t=e.advance().value,n;return n=t===`=~`?eke(e):t===`==`||t===`!=`?h3(e):e.parseWordNoBraceExpansion(),{type:`CondBinary`,operator:t,left:r,right:n}}return e.check(Z.LESS)?(e.advance(),{type:`CondBinary`,operator:`<`,left:r,right:e.parseWordNoBraceExpansion()}):e.check(Z.GREAT)?(e.advance(),{type:`CondBinary`,operator:`>`,left:r,right:e.parseWordNoBraceExpansion()}):e.isWord()&&e.current().value===`=`?(e.advance(),{type:`CondBinary`,operator:`==`,left:r,right:h3(e)}):{type:`CondWord`,word:r}}e.error(`Expected conditional expression`)}function eke(e){let t=[],n=0,r=-1,i=e.getInput(),a=()=>e.check(Z.DBRACK_END)||e.check(Z.AND_AND)||e.check(Z.OR_OR)||e.check(Z.NEWLINE)||e.check(Z.EOF);for(;!a();){let a=e.current(),o=r>=0&&a.start>r;if(n===0&&o)break;if(n>0&&o){let e=i.slice(r,a.start);t.push({type:`Literal`,value:e})}if(e.isWord()||e.check(Z.ASSIGNMENT_WORD)){let n=e.parseWordForRegex();t.push(...n.parts),r=e.peek(-1).end}else if(e.check(Z.LPAREN)){let i=e.advance();t.push({type:`Literal`,value:`(`}),n++,r=i.end}else if(e.check(Z.DPAREN_START)){let i=e.advance();t.push({type:`Literal`,value:`((`}),n+=2,r=i.end}else if(e.check(Z.DPAREN_END)){if(n>=2){let i=e.advance();t.push({type:`Literal`,value:`))`}),n-=2,r=i.end}else{if(n===1)break;break}}else if(e.check(Z.RPAREN)){if(n>0){let i=e.advance();t.push({type:`Literal`,value:`)`}),n--,r=i.end}else break}else if(e.check(Z.PIPE)){let n=e.advance();t.push({type:`Literal`,value:`|`}),r=n.end}else if(e.check(Z.SEMICOLON)){if(n>0){let n=e.advance();t.push({type:`Literal`,value:`;`}),r=n.end}else break}else if(n>0&&e.check(Z.LESS)){let n=e.advance();t.push({type:`Literal`,value:`<`}),r=n.end}else if(n>0&&e.check(Z.GREAT)){let n=e.advance();t.push({type:`Literal`,value:`>`}),r=n.end}else if(n>0&&e.check(Z.DGREAT)){let n=e.advance();t.push({type:`Literal`,value:`>>`}),r=n.end}else if(n>0&&e.check(Z.DLESS)){let n=e.advance();t.push({type:`Literal`,value:`<<`}),r=n.end}else if(n>0&&e.check(Z.LESSAND)){let n=e.advance();t.push({type:`Literal`,value:`<&`}),r=n.end}else if(n>0&&e.check(Z.GREATAND)){let n=e.advance();t.push({type:`Literal`,value:`>&`}),r=n.end}else if(n>0&&e.check(Z.LESSGREAT)){let n=e.advance();t.push({type:`Literal`,value:`<>`}),r=n.end}else if(n>0&&e.check(Z.CLOBBER)){let n=e.advance();t.push({type:`Literal`,value:`>|`}),r=n.end}else if(n>0&&e.check(Z.TLESS)){let n=e.advance();t.push({type:`Literal`,value:`<<<`}),r=n.end}else if(n>0&&e.check(Z.AMP)){let n=e.advance();t.push({type:`Literal`,value:`&`}),r=n.end}else if(n>0&&e.check(Z.LBRACE)){let n=e.advance();t.push({type:`Literal`,value:`{`}),r=n.end}else if(n>0&&e.check(Z.RBRACE)){let n=e.advance();t.push({type:`Literal`,value:`}`}),r=n.end}else break}return t.length===0&&e.error(`Expected regex pattern after =~`),{type:`Word`,parts:t}}function tke(e){let t=``;for(let n=0;n0?e:[X.literal(``)]}function nke(e,t){let n=1,r=t+1;for(;r0;){let t=e[r];if(t===`\\`){r+=2;continue}if(`@*+?!`.includes(t)&&r+10;)t[r]===`{`?e++:t[r]===`}`&&e--,e>0&&r++;let a=t.slice(n+2,r);return{part:X.parameterExpansion(``,{type:`BadSubstitution`,text:a}),endIndex:r+1}}}if(s===``&&!a&&!o&&t[i]!==`}`){let e=1,r=i;for(;r0;)t[r]===`{`?e++:t[r]===`}`&&e--,e>0&&r++;if(e>0)throw new k4(`unexpected EOF while looking for matching '}'`,0,0);let a=t.slice(n+2,r);return{part:X.parameterExpansion(``,{type:`BadSubstitution`,text:a}),endIndex:r+1}}let l=null;if(a){let n=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(n){if(i=t.length)throw new k4(`unexpected EOF while looking for matching '}'`,0,0);return{part:X.parameterExpansion(s,l),endIndex:i+1}}function b3(e,t,n,r,i=!1){let a=n,o=t[a],s=t[a+1]||``;if(o===`:`){let n=s;if(`-=?+`.includes(n)){a+=2;let r=$4(e,t,a),o=t.slice(a,r),s=e.withDepth(()=>C3(e,o,!1,!1,!0,!1,i,!1,!1,!0)),c=X.word(y3(s));if(n===`-`)return{operation:{type:`DefaultValue`,word:c,checkEmpty:!0},endIndex:r};if(n===`=`)return{operation:{type:`AssignDefault`,word:c,checkEmpty:!0},endIndex:r};if(n===`?`)return{operation:{type:`ErrorIfUnset`,word:c,checkEmpty:!0},endIndex:r};if(n===`+`)return{operation:{type:`UseAlternative`,word:c,checkEmpty:!0},endIndex:r}}a++;let r=$4(e,t,a),o=t.slice(a,r),c=-1,l=0,u=0;for(let e=0;e0)u--;else{c=e;break}}}let d=c>=0?o.slice(0,c):o,f=c>=0?o.slice(c+1):null;return{operation:{type:`Substring`,offset:e3(e,d),length:f===null?null:e3(e,f)},endIndex:r}}if(`-=?+`.includes(o)){a++;let n=$4(e,t,a),r=t.slice(a,n),s=e.withDepth(()=>C3(e,r,!1,!1,!0,!1,i,!1,!1,!0)),c=X.word(y3(s));if(o===`-`)return{operation:{type:`DefaultValue`,word:c,checkEmpty:!1},endIndex:n};if(o===`=`)return{operation:{type:`AssignDefault`,word:c,checkEmpty:!1},endIndex:n};if(o===`?`)return{operation:{type:`ErrorIfUnset`,word:r?c:null,checkEmpty:!1},endIndex:n};if(o===`+`)return{operation:{type:`UseAlternative`,word:c,checkEmpty:!1},endIndex:n}}if(o===`#`||o===`%`){let n=s===o,r=o===`#`?`prefix`:`suffix`;a+=n?2:1;let i=$4(e,t,a),c=t.slice(a,i),l=e.withDepth(()=>C3(e,c,!1,!1,!1));return{operation:{type:`PatternRemoval`,pattern:X.word(y3(l)),side:r,greedy:n},endIndex:i}}if(o===`/`){let n=s===`/`;a+=n?2:1;let r=null;t[a]===`#`?(r=`start`,a++):t[a]===`%`&&(r=`end`,a++);let i;i=r!==null&&(t[a]===`/`||t[a]===`}`)?a:zOe(e,t,a);let o=t.slice(a,i),c=e.withDepth(()=>C3(e,o,!1,!1,!1)),l=X.word(y3(c)),u=null,d=i;if(t[i]===`/`){let n=i+1,r=$4(e,t,n),a=t.slice(n,r),o=e.withDepth(()=>C3(e,a,!1,!1,!1));u=X.word(y3(o)),d=r}return{operation:{type:`PatternReplacement`,pattern:l,replacement:u,all:n,anchor:r},endIndex:d}}if(o===`^`||o===`,`){let n=s===o,r=o===`^`?`upper`:`lower`;a+=n?2:1;let i=$4(e,t,a),c=t.slice(a,i);return{operation:{type:`CaseModification`,direction:r,all:n,pattern:c?X.word([X.literal(c)]):null},endIndex:i}}return o===`@`&&/[QPaAEKkuUL]/.test(s)?{operation:{type:`Transform`,operator:s},endIndex:a+2}:{operation:null,endIndex:a}}function x3(e,t,n,r=!1){let i=n+1;if(i>=t.length)return{part:X.literal(`$`),endIndex:i};let a=t[i];if(a===`(`&&t[i+1]===`(`)return e.isDollarDparenSubshell(t,n)?e.parseCommandSubstitution(t,n):e.parseArithmeticExpansion(t,n);if(a===`[`){let n=1,r=i+1;for(;r0;)t[r]===`[`?n++:t[r]===`]`&&n--,n>0&&r++;if(n===0){let n=N4(e,t.slice(i+1,r));return{part:X.arithmeticExpansion(n),endIndex:r+1}}}return a===`(`?e.parseCommandSubstitution(t,n):a===`{`?ike(e,t,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(a)?rke(e,t,n):{part:X.literal(`$`),endIndex:i}}function S3(e,t){let n=[],r=0,i=``,a=()=>{i&&=(n.push(X.literal(i)),``)};for(;r{a&&=(r.push(X.literal(a)),``)};for(;i=2&&t[0]===`"`&&t[t.length-1]===`"`){let n=t.slice(1,-1),r=!1;for(let e=0;e{p&&=(d.push(X.literal(p)),``)};for(;f`)&&t[f+1]===`(`&&!a&&!o){m();let{part:n,endIndex:r}=e.parseProcessSubstitutionFromString(t,f);d.push(n),f=r;continue}if(n===`~`){let n=f>0?t[f-1]:``;if(f===0&&u||n===`=`||i&&n===`:`){let n=ROe(e,t,f),r=t[n];if(r===void 0||r===`/`||r===`:`){m();let e=t.slice(f+1,n)||null;d.push({type:`TildeExpansion`,user:e}),f=n;continue}}}if(`@*+?!`.includes(n)&&f+1T4)throw new k4(`Input too large: ${e.length} bytes exceeds limit of ${T4}`,1,1);this._input=e,this.processLineState=void 0;let n=new COe(e,t);if(this.tokens=n.tokenize(),this.tokens.length>E4)throw new k4(`Too many tokens: ${this.tokens.length} exceeds limit of ${E4}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseBudget.chargeTokens(this.tokens.length),this.parseScript()}finally{n?.()}}parseTokens(e){this.ownsParseBudget&&this.parseBudget.reset();let t=this.ownsParseBudget?void 0:this.enterDepth();try{return this.tokens=e,this.pos=0,this.pendingHeredocs=[],this.processLineState=void 0,this.parseBudget.chargeTokens(e.length),this.parseScript()}finally{t?.()}}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(e=0){return this.tokens[this.pos+e]||this.tokens[this.tokens.length-1]}advance(){let e=this.current();return this.post.currentPhysicalLine&&(t.currentPhysicalLine=e.line,t.currentLogicalLine+=1),t.currentLogicalLine):e.line}check(e,t,n,r,...i){let a=this.tokens[this.pos]?.type;return a===e||t!==void 0&&a===t||n!==void 0&&a===n||r!==void 0&&a===r||i.length>0&&i.includes(a)}expect(e,t){if(this.check(e))return this.advance();let n=this.current();throw new k4(t||`Expected ${e}, got ${n.type}`,n.line,n.column,n)}error(e){let t=this.current();throw new k4(e,t.line,t.column,t)}skipNewlines(){for(;this.check(Z.NEWLINE,Z.COMMENT);)this.check(Z.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(e=!0){for(;;){if(this.check(Z.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(Z.SEMICOLON,Z.COMMENT)){this.advance();continue}if(e&&this.check(Z.DSEMI,Z.SEMI_AND,Z.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(e,t,n,r){this.pendingHeredocs.push({redirect:e,delimiter:t,stripTabs:n,quoted:r})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(Z.HEREDOC_CONTENT)){let t=this.advance(),n;n=e.quoted?X.word([X.literal(t.value)]):this.parseWordFromString(t.value,!1,!1,!1,!0),e.redirect.target=X.hereDoc(e.delimiter,n,e.stripTabs,e.quoted,t.heredocTerminated??!1)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(Z.EOF,Z.NEWLINE,Z.SEMICOLON,Z.AMP,Z.AND_AND,Z.OR_OR,Z.RPAREN,Z.RBRACE,Z.DSEMI,Z.SEMI_AND,Z.SEMI_SEMI_AND)}isCommandStart(){let e=this.current().type;return this.isWord()||e===Z.ASSIGNMENT_WORD||e===Z.FD_VARIABLE||e===Z.LPAREN||e===Z.LBRACE||e===Z.DPAREN_START||e===Z.DBRACK_START||r3(this)}parseScript(){let e=[],t=0;for(this.skipNewlines();!this.check(Z.EOF);){t++,t>1e4&&this.error(`Parser stuck: too many iterations (>10000)`);let n=this.checkUnexpectedToken();if(n){e.push(n),this.skipSeparators(!1);continue}let r=this.pos,i=this.parseStatement();i&&e.push(i),this.check(Z.HEREDOC_CONTENT)&&this.processHeredocs(),this.skipSeparators(!1),this.check(Z.DSEMI,Z.SEMI_AND,Z.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===r&&!this.check(Z.EOF)&&this.error(`syntax error near unexpected token \`${this.current().value}'`)}return X.script(e)}checkUnexpectedToken(){let e=this.current().type,t=this.current().value;if(this.currentTokenJoinsProcessSubstitution())return null;if((e===Z.DO||e===Z.DONE||e===Z.THEN||e===Z.ELSE||e===Z.ELIF||e===Z.FI||e===Z.ESAC)&&this.error(`syntax error near unexpected token \`${t}'`),e===Z.RBRACE||e===Z.RPAREN){let e=`syntax error near unexpected token \`${t}'`;return this.advance(),X.statement([X.pipeline([X.simpleCommand(null,[],[],[])])],[],!1,{message:e,token:t})}return(e===Z.DSEMI||e===Z.SEMI_AND||e===Z.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${t}'`),e===Z.SEMICOLON&&this.error(`syntax error near unexpected token \`${t}'`),(e===Z.AMP||e===Z.AND_AND||e===Z.OR_OR||e===Z.PIPE||e===Z.PIPE_AMP)&&this.error(`syntax error near unexpected token \`${t}'`),null}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=this.current().start,t=[],n=[],r=!1,i=this.parsePipeline();for(t.push(i);this.check(Z.AND_AND,Z.OR_OR);){let e=this.advance();n.push(e.type===Z.AND_AND?`&&`:`||`),this.skipNewlines();let r=this.parsePipeline();t.push(r)}this.check(Z.AMP)&&(this.advance(),r=!0);let a=this.pos>0?this.tokens[this.pos-1].end:e,o=this._input.slice(e,a);return X.statement(t,n,r,void 0,o)}parseTimePrefix(){if(!this.check(Z.TIME)||this.currentTokenJoinsProcessSubstitution())return;this.advance();let e=!1;return this.check(Z.WORD,Z.NAME)&&this.current().value===`-p`&&(this.advance(),e=!0),e}parsePipeline(){let e=!1,t=!1,n=0;for(;this.check(Z.BANG)&&!this.currentTokenJoinsProcessSubstitution();)this.advance(),n++;if(n===0){let r=this.parseTimePrefix();if(r!==void 0)for(e=!0,t=r;this.check(Z.BANG)&&!this.currentTokenJoinsProcessSubstitution();)this.advance(),n++}let r=n%2==1,i=[],a=[],o=this.parseCommand();for(i.push(o);this.check(Z.PIPE,Z.PIPE_AMP);){let e=this.advance();this.skipNewlines(),a.push(e.type===Z.PIPE_AMP);let t=this.parseCommand();i.push(t)}return X.pipeline(i,r,e,t,a.length>0?a:void 0)}parseCommand(){if(this.currentTokenJoinsProcessSubstitution())return a3(this);let e=this.current();switch(e.type){case Z.IF:return s3(this);case Z.FOR:return c3(this);case Z.WHILE:return l3(this);case Z.UNTIL:return u3(this);case Z.CASE:return d3(this);case Z.LPAREN:return f3(this);case Z.LBRACE:return p3(this);case Z.DPAREN_START:return this.dparenClosesWithSpacedParens()?this.parseNestedSubshellsFromDparen():this.parseArithmeticCommand();case Z.DBRACK_START:return this.parseConditionalCommand();case Z.FUNCTION:return this.parseFunctionDef();case Z.TIME:break;case Z.BANG:this.error(`syntax error near unexpected token \`${e.value}'`);break;default:x4(e.type)&&this.error(`syntax error near unexpected token \`${e.value}'`)}return this.check(Z.NAME,Z.WORD)&&this.peek(1).type===Z.LPAREN&&this.peek(2).type===Z.RPAREN?this.parseFunctionDef():a3(this)}dparenClosesWithSpacedParens(){let e=1,t=1;for(;tnew e(this.parseBudget),e=>this.error(e))}parseProcessSubstitutionFromString(t,n){return hOe(t,n,()=>new e(this.parseBudget),e=>this.error(e))}parseProcessSubstitution(){let e=this.advance();this.expect(Z.LPAREN);let t=this.processLineState,n=this.getSourceLine(e);this.processLineState={currentLogicalLine:n};let r;try{r=X.script(this.parseCompoundList())}finally{this.processLineState=t}return this.check(Z.EOF)&&this.error("unexpected EOF while looking for matching `)'"),this.expect(Z.RPAREN),X.processSubstitution(r,e.type===Z.LESS?`input`:`output`)}parseBacktickSubstitution(t,n,r=!1){return gOe(t,n,r,()=>new e(this.parseBudget),e=>this.error(e))}isDollarDparenSubshell(e,t){return fOe(e,t)}parseArithmeticExpansion(e,t){let n=t+3,r=1,i=0,a=n;for(;a0;)e[a]===`$`&&e[a+1]===`(`?e[a+2]===`(`?(r++,a+=3):(i++,a+=2):e[a]===`(`&&e[a+1]===`(`?(r++,a+=2):e[a]===`)`&&e[a+1]===`)`?i>0?(i--,a++):(r--,r>0&&(a+=2)):e[a]===`(`?(i++,a++):(e[a]===`)`&&i>0&&i--,a++);let o=e.slice(n,a),s=this.parseArithmeticExpression(o);return{part:X.arithmeticExpansion(s),endIndex:a+2}}parseArithmeticCommand(){let e=this.expect(Z.DPAREN_START),t=``,n=1,r=0,i=!1,a=!1;for(;n>0&&!this.check(Z.EOF);){if(i){if(i=!1,r>0){r--,t+=`)`;continue}if(this.check(Z.RPAREN)){n--,a=!0,this.advance();continue}if(this.check(Z.DPAREN_END)){n--,a=!0;continue}t+=`)`;continue}if(this.check(Z.DPAREN_START))n++,t+=`((`,this.advance();else if(this.check(Z.DPAREN_END))r>=2?(r-=2,t+=`))`,this.advance()):r===1?(r--,t+=`)`,i=!0,this.advance()):(n--,a=!0,n>0&&(t+=`))`),this.advance());else if(this.check(Z.LPAREN))r++,t+=`(`,this.advance();else if(this.check(Z.RPAREN))r>0&&r--,t+=`)`,this.advance();else{let e=this.current().value,n=t.length>0?t[t.length-1]:``;t.length>0&&!t.endsWith(` `)&&!(e===`=`&&/[|&^+\-*/%<>]$/.test(t))&&(e!==`<`||n!==`<`)&&(e!==`>`||n!==`>`)&&(t+=` `),t+=e,this.advance()}}a||this.expect(Z.DPAREN_END);let o=this.parseArithmeticExpression(t.trim()),s=this.parseOptionalRedirections();return X.arithmeticCommand(o,s,this.getSourceLine(e))}parseConditionalCommand(){let e=this.expect(Z.DBRACK_START),t=g3(this);this.expect(Z.DBRACK_END);let n=this.parseOptionalRedirections();return X.conditionalCommand(t,n,this.getSourceLine(e))}parseFunctionDef(){let e;if(this.check(Z.FUNCTION)){if(this.advance(),this.check(Z.NAME)||this.check(Z.WORD))e=this.advance().value;else{let e=this.current();throw new k4(`Expected function name`,e.line,e.column,e)}this.check(Z.LPAREN)&&(this.advance(),this.expect(Z.RPAREN))}else e=this.advance().value,e.includes(`$`)&&this.error(`\`${e}': not a valid identifier`),this.expect(Z.LPAREN),this.expect(Z.RPAREN);this.skipNewlines();let t=this.parseCompoundCommandBody({forFunctionBody:!0}),n=this.parseOptionalRedirections();return X.functionDef(e,t,n)}parseCompoundCommandBody(e){let t=e?.forFunctionBody;if(this.check(Z.LBRACE))return p3(this,{skipRedirections:t});if(this.check(Z.LPAREN))return f3(this,{skipRedirections:t});if(this.check(Z.IF))return s3(this,{skipRedirections:t});if(this.check(Z.FOR))return c3(this,{skipRedirections:t});if(this.check(Z.WHILE))return l3(this,{skipRedirections:t});if(this.check(Z.UNTIL))return u3(this,{skipRedirections:t});if(this.check(Z.CASE))return d3(this,{skipRedirections:t});this.error(`Expected compound command for function body`)}parseCompoundList(){let e=this.enterDepth();try{let e=[];for(this.skipNewlines();(this.currentTokenJoinsProcessSubstitution()||!this.check(Z.EOF,Z.FI,Z.ELSE,Z.ELIF,Z.THEN,Z.DO,Z.DONE,Z.ESAC,Z.RPAREN,Z.RBRACE,Z.DSEMI,Z.SEMI_AND,Z.SEMI_SEMI_AND))&&this.isCommandStart();){this.checkIterationLimit();let t=this.pos,n=this.parseStatement();if(n&&e.push(n),this.skipSeparators(),this.pos===t&&!n)break}return e}finally{e()}}parseOptionalRedirections(){let e=[];for(;r3(this);){this.checkIterationLimit();let t=this.pos;if(e.push(i3(this)),this.pos===t)break}return e}parseArithmeticExpression(e){return N4(this,e)}};function T3(e,t){return new w3().parse(e,t)}function oke(e){return E3(e)}function E3(e){return e.statements.map(D3).join(` +`)}function D3(e){let t=[];for(let n=0;n0?`${t.join(` `)} `:``)+n.join(` `)}function O3(e){switch(e.type){case`SimpleCommand`:return cke(e);case`If`:return _ke(e);case`For`:return vke(e);case`CStyleFor`:return yke(e);case`While`:return bke(e);case`Until`:return xke(e);case`Case`:return Ske(e);case`Subshell`:return wke(e);case`Group`:return Tke(e);case`ArithmeticCommand`:return Eke(e);case`ConditionalCommand`:return Dke(e);case`FunctionDef`:return Oke(e);default:throw Error(`Unsupported command type: ${e.type}`)}}function cke(e){let t=[];for(let n of e.assignments)t.push(lke(n));e.name&&t.push(k3(e.name));for(let n of e.args)t.push(k3(n));for(let n of e.redirections)t.push(P3(n));return t.join(` `)}function lke(e){let t=e.append?`+=`:`=`;if(e.array){let n=e.array.map(k3).join(` `);return`${e.name}${t}(${n})`}return e.value?`${e.name}${t}${k3(e.value)}`:`${e.name}${t}`}function k3(e){return e.parts.map(e=>j3(e,!1)).join(``)}function A3(e){return e.parts.map(e=>j3(e,!0)).join(``)}function j3(e,t){switch(e.type){case`Literal`:return t?dke(e.value):uke(e.value);case`SingleQuoted`:return`'${e.value}'`;case`DoubleQuoted`:return`"${e.parts.map(e=>j3(e,!0)).join(``)}"`;case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return M3(e);case`CommandSubstitution`:return e.legacy?`\`${E3(e.body)}\``:`$(${E3(e.body)})`;case`ArithmeticExpansion`:return`$((${L3(e.expression.expression)}))`;case`ProcessSubstitution`:return e.direction===`input`?`<(${E3(e.body)})`:`>(${E3(e.body)})`;case`BraceExpansion`:return hke(e);case`TildeExpansion`:return e.user===null?`~`:`~${e.user}`;case`Glob`:return e.pattern;default:throw Error(`Unsupported word part type: ${e.type}`)}}function uke(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,`\\$&`)}function dke(e){return e.replace(/[$`"\\]/g,`\\$&`)}function fke(e,t){return e.parts.map(e=>pke(e,t)).join(``)}function pke(e,t){switch(e.type){case`Literal`:return t?e.value:e.value.replace(/[$`]/g,`\\$&`);case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return M3(e);case`CommandSubstitution`:return e.legacy?`\`${E3(e.body)}\``:`$(${E3(e.body)})`;case`ArithmeticExpansion`:return`$((${L3(e.expression.expression)}))`;default:return j3(e,!1)}}function M3(e){return e.operation?`\${${N3(e.parameter,e.operation)}}`:mke(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function mke(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function N3(e,t){switch(t.type){case`Length`:return`#${e}`;case`LengthSliceError`:return`#${e}:`;case`BadSubstitution`:return t.text;case`DefaultValue`:return`${e}${t.checkEmpty?`:`:``}-${A3(t.word)}`;case`AssignDefault`:return`${e}${t.checkEmpty?`:`:``}=${A3(t.word)}`;case`ErrorIfUnset`:return`${e}${t.checkEmpty?`:`:``}?${t.word?A3(t.word):``}`;case`UseAlternative`:return`${e}${t.checkEmpty?`:`:``}+${A3(t.word)}`;case`Substring`:{let n=L3(t.offset.expression);return t.length?`${e}:${n}:${L3(t.length.expression)}`:`${e}:${n}`}case`PatternRemoval`:{let n=t.side===`prefix`?`#`:`%`;return`${e}${t.greedy?`${n}${n}`:n}${A3(t.pattern)}`}case`PatternReplacement`:{let n=`/`;t.all?n=`//`:t.anchor===`start`?n=`/#`:t.anchor===`end`&&(n=`/%`);let r=t.replacement?`/${A3(t.replacement)}`:``;return`${e}${n}${A3(t.pattern)}${r}`}case`CaseModification`:{let n=t.direction===`upper`?`^`:`,`;return`${e}${t.all?`${n}${n}`:n}${t.pattern?A3(t.pattern):``}`}case`Transform`:return`${e}@${t.operator}`;case`Indirection`:return t.innerOp?`!${N3(e,t.innerOp)}`:`!${e}`;case`ArrayKeys`:return`!${t.array}[${t.star?`*`:`@`}]`;case`VarNamePrefix`:return`!${t.prefix}${t.star?`*`:`@`}`;default:throw Error(`Unsupported parameter operation type: ${t.type}`)}}function hke(e){return`{${e.items.map(gke).join(`,`)}}`}function gke(e){if(e.type===`Word`)return k3(e.word);let t=e.startStr??String(e.start),n=e.endStr??String(e.end);return e.step===void 0?`${t}..${n}`:`${t}..${n}..${e.step}`}function P3(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd===null?``:String(e.fd);if(e.operator===`<<`||e.operator===`<<-`){let n=e.target;if(n.terminated===!1)throw Error(`Cannot serialize an unterminated here-document`);let r=n.quoted?`'${n.delimiter}'`:n.delimiter,i=fke(n.content,n.quoted);return`${t}${e.operator}${r} +${i}${n.delimiter}`}return e.operator===`<<<`?`${t}<<< ${k3(e.target)}`:e.operator===`&>`||e.operator===`&>>`?`${e.operator} ${k3(e.target)}`:`${t}${e.operator} ${k3(e.target)}`}function F3(e){return e.length===0?``:` ${e.map(P3).join(` `)}`}function I3(e){return e.map(D3).join(` +`)}function _ke(e){let t=[];for(let n=0;nn-r.value)throw new H(`alias expansion exceeds string length limit (${n} bytes)`,`string_length`);return r.value+=i,e+t}function B3(e){return e.parts.length===1&&e.parts[0].type===`Literal`}function V3(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function H3(e,t){return e.env.get(`${kke}${t}`)}function Ake(e,t,n){return U3(e,t,n)}function U3(e,t,n,r=!0){if(!t.name||!B3(t.name))return t;let i=V3(t.name);if(!i)return t;let a=H3(e,i);if(!a||n.has(i))return t;try{n.add(i);let o=new w3,s={value:0},c=z3(``,a,e.limits.maxStringLength,s),l=a.endsWith(` `);if(!l)for(let n of t.args){let t=k3(n);c=z3(c,` ${t}`,e.limits.maxStringLength,s)}let u;try{u=o.parse(c)}catch(e){if(e instanceof k4)throw e;return t}if(u.statements.length!==1||u.statements[0].pipelines.length!==1||u.statements[0].pipelines[0].commands.length!==1)return W3(e,t,a);let d=u.statements[0].pipelines[0].commands[0];if(d.type!==`SimpleCommand`)return W3(e,t,a);let f={...d,assignments:[...t.assignments,...d.assignments],redirections:[...d.redirections,...t.redirections],line:t.line};if(l&&t.args.length>0){f={...f,args:[...f.args,...t.args]};let i=1;for(;r&&f.args.length>0;){let t=f.args[0];if(!B3(t))break;let r=V3(t),a=r?H3(e,r):null;if(!a)break;if(i>=e.limits.maxCallDepth)throw new H(`alias expansion depth limit exceeded (${e.limits.maxCallDepth})`,`recursion`);i++;let o={type:`SimpleCommand`,name:t,args:f.args.slice(1),assignments:[],redirections:[]},s=U3(e,o,n,!1);if(s===o||(f={...f,name:s.name,args:[...s.args]},!a.endsWith(` `)))break}}return f}catch(e){throw n.delete(i),e}}function W3(e,t,n){let r={value:0},i=z3(``,n,e.limits.maxStringLength,r);for(let n of t.args){let t=k3(n);i=z3(i,` ${t}`,e.limits.maxStringLength,r)}let a=new w3,o=a.parseWordFromString(`eval`,!1,!1),s=0;for(let e of i)e===`'`&&s++;if(r.value+2+s*3>e.limits.maxStringLength)throw new H(`alias expansion exceeds string length limit (${e.limits.maxStringLength} bytes)`,`string_length`);return{type:`SimpleCommand`,name:o,args:[a.parseWordFromString(`'${i.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:t.assignments,redirections:t.redirections,line:t.line}}U(),U(),yG(),uV(),yG();var jke=new Map([[`alnum`,`a-zA-Z0-9`],[`alpha`,`a-zA-Z`],[`ascii`,`\\x00-\\x7F`],[`blank`,` \\t`],[`cntrl`,`\\x00-\\x1F\\x7F`],[`digit`,`0-9`],[`graph`,`!-~`],[`lower`,`a-z`],[`print`,` -~`],[`punct`,"!-/:-@\\[-`{-~"],[`space`,` \\t\\n\\r\\f\\v`],[`upper`,`A-Z`],[`word`,`a-zA-Z0-9_`],[`xdigit`,`0-9a-fA-F`]]);function G3(e){return jke.get(e)??``}function Mke(e){let t=[],n=``,r=0;for(;r0;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return r;r++}return-1}function q3(e){let t=[],n=``,r=0,i=!1,a=0;for(;athis.maxOps)throw new H(`Glob operation limit exceeded (${this.maxOps})`,`glob_operations`);this.consumeOperation?.()}hasNullglob(){return this.nullglob}hasFailglob(){return this.failglob}filterGlobignore(e){return!this.hasGlobignore&&!this.globskipdots?e:e.filter(e=>{let t=e.split(`/`).pop()||e;if((this.hasGlobignore||this.globskipdots)&&(t===`.`||t===`..`))return!1;if(this.hasGlobignore){for(let t of this.globignorePatterns)if(this.matchGlobignorePattern(e,t))return!1}return!0})}matchGlobignorePattern(e,t){return Nke(t).test(e)}isGlobPattern(e){return!!(e.includes(`*`)||e.includes(`?`)||/\[.*\]/.test(e)||this.extglob&&/[@*+?!]\(/.test(e))}async expandArgs(e,t){let n=e.map((e,n)=>(t?.[n]??!1)||!this.isGlobPattern(e)?null:this.expand(e)),r=await Promise.all(n.map(e=>e||Promise.resolve(null))),i=[];for(let t=0;t0?i.push(...n):i.push(e[t])}return i}async expand(e){if(this.globstar){let t=e.split(`/`),n=0;for(let e of t)if(e===`**`&&(n++,n>J3))throw new H(`Glob pattern has too many ** segments (max ${J3})`,`glob_operations`)}let t;if(e.includes(`**`)&&this.globstar&&this.isGlobstarValid(e))t=await this.expandRecursive(e);else{let n=e.replace(/\*\*+/g,`*`);t=await this.expandSimple(n)}return this.filterGlobignore(t)}isGlobstarValid(e){let t=e.split(`/`);for(let e of t)if(e.includes(`**`)&&e!==`**`)return!1;return!0}hasGlobChars(e){return!!(e.includes(`*`)||e.includes(`?`)||/\[.*\]/.test(e)||this.extglob&&/[@*+?!]\(/.test(e))}async expandSimple(e){let t=e.startsWith(`/`),n=e.split(`/`).filter(e=>e!==``),r=-1;for(let e=0;ee.name===`.`),t=n.some(e=>e.name===`..`);e||s.push({name:`.`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}),t||s.push({name:`..`,isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let n of s)if((!n.name.startsWith(`.`)||r.startsWith(`.`)||c)&&this.matchPattern(n.name,r)){let r=e===`/`?`/${n.name}`:`${e}/${n.name}`,a;a=t===``?n.name:t===`/`?`/${n.name}`:`${t}/${n.name}`,i.length===0?o.push(Promise.resolve([a])):n.isDirectory&&o.push(this.expandSegments(r,a,i))}let l=await Promise.all(o);for(let e of l)a.push(...e)}else{this.checkOpsLimit();let n=await this.fs.readdir(e),o=[],s=[...n],c=this.dotglob||this.hasGlobignore;(r.startsWith(`.`)||this.dotglob)&&(n.includes(`.`)||s.push(`.`),n.includes(`..`)||s.push(`..`));for(let n of s)if((!n.startsWith(`.`)||r.startsWith(`.`)||c)&&this.matchPattern(n,r)){let r=e===`/`?`/${n}`:`${e}/${n}`,a;a=t===``?n:t===`/`?`/${n}`:`${t}/${n}`,i.length===0?o.push(Promise.resolve([a])):o.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(r)).isDirectory)return this.expandSegments(r,a,i)}catch(e){if(e instanceof H)throw e}return[]})())}let l=await Promise.all(o);for(let e of l)a.push(...e)}}catch(e){if(e instanceof H)throw e}return a}async expandRecursive(e){let t=[],n=e.indexOf(`**`),r=e.slice(0,n).replace(/\/$/,``)||`.`,i=e.slice(n+2).replace(/^\//,``);return i.includes(`**`)&&this.isGlobstarValid(i)?(await this.walkDirectoryMultiGlobstar(r,i,t),[...new Set(t)].sort()):(await this.walkDirectory(r,i,t),t.sort())}async walkDirectoryMultiGlobstar(e,t,n){this.checkOpsLimit();let r=this.fs.resolvePath(this.cwd,e);try{this.checkOpsLimit();let i=this.fs.readdirWithFileTypes?await this.fs.readdirWithFileTypes(r):null;if(i){let r=[];for(let t of i){let n=e===`.`?t.name:`${e}/${t.name}`;t.isDirectory&&r.push(n)}let a=e===`.`?t:`${e}/${t}`,o=await this.expandRecursive(a);n.push(...o);for(let e=0;ethis.walkDirectoryMultiGlobstar(e,t,n)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(r),a=[];for(let t of i){let n=e===`.`?t:`${e}/${t}`,r=this.fs.resolvePath(this.cwd,n);try{this.checkOpsLimit(),(await this.fs.stat(r)).isDirectory&&a.push(n)}catch(e){if(e instanceof H)throw e}}let o=e===`.`?t:`${e}/${t}`,s=await this.expandRecursive(o);n.push(...s);for(let e=0;ethis.walkDirectoryMultiGlobstar(e,t,n)))}}}catch(e){if(e instanceof H)throw e}}async walkDirectory(e,t,n){this.checkOpsLimit();let r=this.fs.resolvePath(this.cwd,e);try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let i=await this.fs.readdirWithFileTypes(r),a=[],o=[];for(let n of i){let r=e===`.`?n.name:`${e}/${n.name}`;n.isDirectory?o.push(r):t&&this.matchPattern(n.name,t)&&a.push(r)}n.push(...a);for(let e=0;ethis.walkDirectory(e,t,n)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(r),a=[];for(let t=0;t{let n=e===`.`?t:`${e}/${t}`,r=this.fs.resolvePath(this.cwd,n);try{return this.checkOpsLimit(),{name:t,path:n,isDirectory:(await this.fs.stat(r)).isDirectory}}catch(e){if(e instanceof H)throw e;return null}}));a.push(...r.filter(e=>e!==null))}for(let e of a)!e.isDirectory&&t&&this.matchPattern(e.name,t)&&n.push(e.path);let o=a.filter(e=>e.isDirectory);for(let e=0;ethis.walkDirectory(e.path,t,n)))}}}catch(e){if(e instanceof H)throw e}}matchPattern(e,t){return this.patternToRegex(t).test(e)}patternToRegex(e){return mG(`^${this.patternToRegexStr(e)}$`)}patternToRegexStr(e){let t=``,n=!1;for(let r=0;rthis.patternToRegexStr(e)),s=o.length>0?o.join(`|`):`(?:)`;if(i===`@`)t+=`(?:${s})`;else if(i===`*`)t+=`(?:${s})*`;else if(i===`+`)t+=`(?:${s})+`;else if(i===`?`)t+=`(?:${s})?`;else if(i===`!`){if(nthis.computePatternLength(e));if(e.every(e=>e!==null)&&e.every(t=>t===e[0])&&e[0]!==null){let n=e[0];if(n===0)t+=`(?:.+)`;else{let e=[];n>0&&e.push(`.{0,${n-1}}`),e.push(`.{${n+1},}`),e.push(`(?!(?:${s})).{${n}}`),t+=`(?:${e.join(`|`)})`}}else t+=`(?:(?!(?:${s})).)*?`}else t+=`(?!(?:${s})$).*`}r=n;continue}}if(i===`*`)t+=`.*`;else if(i===`?`)t+=`.`;else if(i===`[`){let n=r+1,i=`[`;nthis.computePatternLength(e));if(i.every(e=>e!==null)&&i.every(e=>e===i[0])){t+=i[0],n=r+1;continue}return null}return null}}if(i===`*`)return null;if(i===`?`){t+=1,n++;continue}if(i===`[`){let r=e.indexOf(`]`,n+1);if(r!==-1){t+=1,n=r+1;continue}t+=1,n++;continue}if(i===`\\`){t+=1,n+=2;continue}t+=1,n++}return t}};U();function X3(e){for(let t=0;t=t)throw new H(`array element limit exceeded (${t})`,`array_elements`)}function $3(e,t,n,r,i){Q3(e.length,i),Q3(t.length,i),e.push(n),t.push(r)}function e6(e){return e.get(`IFS`)??Ike}function t6(e){return e.get(`IFS`)===``}function n6(e){let t=e6(e);if(t===``)return!0;for(let e of t)if(e!==` `&&e!==` `&&e!==` +`)return!1;return!0}function Lke(e){let t=!1,n=[];for(let r of e.split(``))r===`-`?t=!0:/[\\^$.*+?()[\]{}|]/.test(r)?n.push(`\\${r}`):r===` `?n.push(`\\t`):r===` +`?n.push(`\\n`):n.push(r);return t&&n.push(`\\-`),n.join(``)}function r6(e){let t=e.get(`IFS`);return t===void 0?` `:t[0]||``}var Rke=` +`;function zke(e){return Rke.includes(e)}function i6(e){let t=new Set,n=new Set;for(let r of e)zke(r)?t.add(r):n.add(r);return{whitespace:t,nonWhitespace:n}}function a6(e,t,n,r,i){if(t===``)return e===``?{words:[],wordStarts:[]}:(Q3(0,n),{words:[e],wordStarts:[0]});let{whitespace:a,nonWhitespace:o}=i6(t),s=[],c=[],l=0;for(;l=e.length)return{words:[],wordStarts:[]};if(o.has(e[l]))for($3(s,c,``,l,n),l++;l=r);){let t=l;for(;l=e.length)break;for(;l=r);)for($3(s,c,``,l,n),l++;ll&&(s=!0),o>=e.length)return{words:[],hadLeadingDelimiter:!0,hadTrailingDelimiter:!0};if(i.has(e[o]))for(Q3(a.length,n),a.push(``),o++;o=e.length){c=!1;break}let s=o;for(;o=e.length&&o>s&&(c=!0)}return{words:a,hadLeadingDelimiter:s,hadTrailingDelimiter:c}}function s6(e,t,n){return o6(e,t,n).words}function Bke(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Vke(e,t,n){if(t===``)return e;let{whitespace:r,nonWhitespace:i}=i6(t),a=e.length;for(;a>0&&r.has(e[a-1]);){if(!n&&a>=2){let t=0,n=a-2;for(;n>=0&&e[n]===`\\`;)t++,n--;if(t%2==1)break}a--}let o=e.substring(0,a);if(o.length>=1&&i.has(o[o.length-1])){if(!n&&o.length>=2){let e=0,t=o.length-2;for(;t>=0&&o[t]===`\\`;)e++,t--;if(e%2==1)return o}let e=o.substring(0,o.length-1);if(!Bke(e,i))return e}return o}function c6(e,t){return e.state.namerefs?.has(t)??!1}function l6(e,t){e.state.namerefs??=new Set,e.state.namerefs.add(t)}function Hke(e,t){e.state.namerefs?.delete(t),e.state.boundNamerefs?.delete(t),e.state.invalidNamerefs?.delete(t)}function Uke(e,t){e.state.invalidNamerefs??=new Set,e.state.invalidNamerefs.add(t)}function u6(e,t){return e.state.invalidNamerefs?.has(t)??!1}function d6(e,t){e.state.boundNamerefs??=new Set,e.state.boundNamerefs.add(t)}function f6(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let t=n[1],r=e4(e,t),i=e.state.associativeArrays?.has(t)??!1;return r||i}return e4(e,t)?!0:e.state.env.has(t)}function p6(e,t,n=100){if(!c6(e,t)||u6(e,t))return t;let r=new Set,i=t;for(;n-->0;){if(r.has(i))return;if(r.add(i),!c6(e,i))return i;let t=e.state.env.get(i);if(t===void 0||t===``||!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(t))return i;i=t}}function m6(e,t){if(c6(e,t))return e.state.env.get(t)}function h6(e,t,n,r=100){if(!c6(e,t)||u6(e,t))return t;let i=new Set,a=t;for(;r-->0;){if(i.has(a))return;if(i.add(a),!c6(e,a))return a;let t=e.state.env.get(a);if(t===void 0||t===``)return n===void 0||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&f6(e,n)?a:null;if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(t))return a;a=t}}function g6(e,t){let n=t.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g,(t,n)=>e.state.env.get(n)??``);return n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n)=>e.state.env.get(n)??``),n}function _6(e,t){return t===`FUNCNAME`?(e.state.funcNameStack??[]).map((e,t)=>[t,e]):t===`BASH_LINENO`?(e.state.callLineStack??[]).map((e,t)=>[t,String(e)]):t===`BASH_SOURCE`?(e.state.sourceStack??[]).map((e,t)=>[t,e]):e.state.associativeArrays?.has(t)?l4(e,t).map(n=>[n,t4(e,t,n)??``]):s4(e,t).map(n=>[n,t4(e,t,n)??``])}function v6(e,t){return t===`FUNCNAME`?(e.state.funcNameStack?.length??0)>0:t===`BASH_LINENO`?(e.state.callLineStack?.length??0)>0:t===`BASH_SOURCE`?(e.state.sourceStack?.length??0)>0:(e.state.associativeArrays?.has(t),e4(e,t))}async function y6(e,t,n=!0,r=!1){switch(t){case`?`:return String(e.state.lastExitCode);case`$`:return String(e.state.virtualPid);case`#`:return e.state.env.get(`#`)||`0`;case`@`:return e.state.env.get(`@`)||``;case`_`:return e.state.lastArg;case`-`:{let t=``;return t+=`h`,e.state.options.errexit&&(t+=`e`),e.state.options.noglob&&(t+=`f`),e.state.options.nounset&&(t+=`u`),e.state.options.verbose&&(t+=`v`),e.state.options.xtrace&&(t+=`x`),t+=`B`,e.state.options.noclobber&&(t+=`C`),t+=`s`,t}case`*`:{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);if(t===0)return``;let n=[];for(let r=1;r<=t;r++)n.push(e.state.env.get(String(r))||``);return n.join(r6(e.state.env))}case`0`:return e.state.env.get(`0`)||`bash`;case`PWD`:return e.state.env.get(`PWD`)??``;case`OLDPWD`:return e.state.env.get(`OLDPWD`)??``;case`PPID`:return String(e.state.virtualPpid);case`UID`:return String(e.state.virtualUid);case`EUID`:return String(e.state.virtualUid);case`RANDOM`:return String(Math.floor(Math.random()*32768));case`SECONDS`:return String(Math.floor((Date.now()-e.state.startTime)/1e3));case`BASH_VERSION`:return tOe;case`!`:return String(e.state.lastBackgroundPid);case`BASHPID`:return String(e.state.bashPid);case`LINENO`:return String(e.state.currentLine);case`FUNCNAME`:{let t=e.state.funcNameStack?.[0];if(t!==void 0)return t;if(n&&e.state.options.nounset)throw new IB(`FUNCNAME`);return``}case`BASH_LINENO`:{let t=e.state.callLineStack?.[0];if(t!==void 0)return String(t);if(n&&e.state.options.nounset)throw new IB(`BASH_LINENO`);return``}case`BASH_SOURCE`:{let t=e.state.sourceStack?.[0];if(t!==void 0)return t;if(n&&e.state.options.nounset)throw new IB(`BASH_SOURCE`);return``}}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(t))throw new zB(`\${${t}}`);let i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let t=i[1],r=i[2];if(c6(e,t)){let n=p6(e,t);if(n&&n!==t){if(n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return``;t=n}}if(r===`@`||r===`*`){let n=_6(e,t);if(n.length>0)return n.map(([,e])=>e).join(` `);let r=e.state.env.get(t);return r===void 0?``:r}if(t===`FUNCNAME`){let t=Number.parseInt(r,10);return!Number.isNaN(t)&&t>=0?e.state.funcNameStack?.[t]??``:``}if(t===`BASH_LINENO`){let t=Number.parseInt(r,10);if(!Number.isNaN(t)&&t>=0){let n=e.state.callLineStack?.[t];return n===void 0?``:String(n)}return``}if(t===`BASH_SOURCE`){let t=Number.parseInt(r,10);return!Number.isNaN(t)&&t>=0?e.state.sourceStack?.[t]??``:``}if(e.state.associativeArrays?.has(t)){let i=u4(r);i=g6(e,i);let a=t4(e,t,i);if(a===void 0&&n&&e.state.options.nounset)throw new IB(`${t}[${r}]`);return a||``}let a;if(/^-?\d+$/.test(r))a=Number.parseInt(r,10);else try{a=await M8(e,N4(new w3,r).expression)}catch{let t=e.state.env.get(r);a=t?Number.parseInt(t,10):0,Number.isNaN(a)&&(a=0)}if(a<0){let n=_6(e,t),r=e.state.currentLine;if(n.length===0)return e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${r}: ${t}: bad array subscript +`,``;let i=Math.max(...n.map(([e])=>typeof e==`number`?e:0))+1+a;return i<0?(e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${r}: ${t}: bad array subscript +`,``):t4(e,t,i)||``}let o=t4(e,t,a);if(o!==void 0)return o;if(a===0){let n=e.state.env.get(t);if(n!==void 0)return n}if(n&&e.state.options.nounset)throw new IB(`${t}[${a}]`);return``}if(/^[1-9][0-9]*$/.test(t)){let r=e.state.env.get(t);if(r===void 0&&n&&e.state.options.nounset)throw new IB(t);return r||``}if(c6(e,t)){let i=p6(e,t);if(i===void 0)return``;if(i!==t)return await y6(e,i,n,r);let a=e.state.env.get(t);if((a===void 0||a===``)&&n&&e.state.options.nounset)throw new IB(t);return a||``}let a=e.state.env.get(t);if(a!==void 0)return e.state.tempEnvBindings?.some(e=>e.has(t))&&(e.state.accessedTempEnvVars=e.state.accessedTempEnvVars||new Set,e.state.accessedTempEnvVars.add(t)),a;if(v6(e,t)){let r=t4(e,t,0);if(r!==void 0)return r;if(n&&e.state.options.nounset)throw new IB(t);return``}if(n&&e.state.options.nounset)throw new IB(t);return``}async function b6(e,t){if(new Set([`?`,`$`,`#`,`_`,`-`,`0`,`PPID`,`UID`,`EUID`,`RANDOM`,`SECONDS`,`BASH_VERSION`,`!`,`BASHPID`,`LINENO`]).has(t))return!0;if(t===`@`||t===`*`)return Number.parseInt(e.state.env.get(`#`)||`0`,10)>0;if(t===`PWD`||t===`OLDPWD`)return e.state.env.has(t);let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let t=n[1],r=n[2];if(c6(e,t)){let n=p6(e,t);if(n&&n!==t){if(n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return!1;t=n}}if(r===`@`||r===`*`)return _6(e,t).length>0||e.state.env.has(t);if(e.state.associativeArrays?.has(t)){let n=g6(e,u4(r));return n4(e,t,n)}let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else try{i=await M8(e,N4(new w3,r).expression)}catch{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0,Number.isNaN(i)&&(i=0)}if(i<0){let n=_6(e,t);if(n.length===0)return!1;let r=Math.max(...n.map(([e])=>typeof e==`number`?e:0))+1+i;return r<0?!1:n4(e,t,r)}return n4(e,t,i)}if(c6(e,t)){let n=p6(e,t);return n===void 0||n===t?e.state.env.has(t):b6(e,n)}return e.state.env.has(t)?!0:v6(e,t)?n4(e,t,0):!1}async function Wke(e,t){let n=``,r=0;for(;r0;)t[i]===`{`?e++:t[i]===`}`&&e--,i++;n+=t.slice(r,i),r=i;continue}if(t[r+1]===`(`){let e=1,i=r+2;for(;i0;)t[i]===`(`?e++:t[i]===`)`&&e--,i++;n+=t.slice(r,i),r=i;continue}if(/[a-zA-Z_]/.test(t[r+1]||``)){let i=r+1;for(;i0;)n[r]===`(`&&n[r-1]===`$`||n[r]===`(`?t++:n[r]===`)`&&t--,r++;let i=n.slice(o+2,r-1);if(e.execFn){let t=await e.execFn(i,{signal:e.state.signal});a+=t.stdout.replace(/\n+$/,``),t.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||``)+t.stderr)}o=r}else if(n[o+1]===`{`){let t=1,r=o+2;for(;r0;)n[r]===`{`?t++:n[r]===`}`&&t--,r++;let i=await y6(e,n.slice(o+2,r-1));a+=i,o=r}else if(/[a-zA-Z_]/.test(n[o+1]||``)){let t=o+1;for(;t=n.maxResults)return!1;let i=V(t);if(i>n.maxStringBytes-r.value)throw new H(`brace expansion string limit exceeded (${n.maxStringBytes} bytes)`,`string_length`);return e.push(t),r.value+=i,!0}function Gke(e,t,n,r,i,a=C6){let o=n??1;o===0&&(o=1);let s=Math.abs(o),c=[],l=0;if(r?.match(/^-?0\d/)&&(l=Math.max(l,r.replace(/^-/,``).length)),i?.match(/^-?0\d/)&&(l=Math.max(l,i.replace(/^-/,``).length)),l>a.maxStringBytes)throw new H(`brace expansion padding limit exceeded (${a.maxStringBytes} bytes)`,`string_length`);let u={value:0},d=e=>{if(l>0){let t=e<0,n=String(Math.abs(e)).padStart(l,`0`);return t?`-${n}`:n}return String(e)};if(e<=t)for(let n=e,r=0;n<=t&&r=t&&r=`A`&&e<=`Z`&&t>=`a`&&t<=`z`||e>=`a`&&e<=`z`&&t>=`A`&&t<=`Z`){let r=n===void 0?``:`..${n}`;throw new VB(`{${e}..${t}${r}}: invalid sequence`)}let c=[],l={value:0};if(a<=o)for(let e=a,t=0;e<=o&&t=o&&tj6(e,t,n)),c=s.length>0?s.join(`|`):`(?:)`;a===`@`?r+=`(?:${c})`:a===`*`?r+=`(?:${c})*`:a===`+`?r+=`(?:${c})+`:a===`?`?r+=`(?:${c})?`:a===`!`&&(r+=`(?!(?:${c})$).*`),i=o+1;continue}}if(a===`\\`){if(i+10;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return r;r++}return-1}function Yke(e){let t=[],n=``,r=0,i=0;for(;i0&&nnew H(`pattern replacement: string length limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`));n.lastIndex=0;let o=0,s=n.exec(t);for(;s!==null&&(e.executionScope.consumeLimited(`pattern_operations`,1,e.limits.maxGlobOperations,`pattern replacement`),!(i&&s[0].length===0&&s.index===t.length||(a.append(t.slice(o,s.index)),a.append(r),o=s.index+s[0].length,!i)));)s[0].length===0&&(o++,n.lastIndex<=s.index&&(n.lastIndex=s.index+1)),s=n.exec(t);return a.append(t.slice(o)),n.lastIndex=0,a.build()}XB(),U();function F6(e){let t=[],n=0;return{append(r){let i=V(r);if(i>e-n)throw new H(`prompt expansion exceeds string length limit (${e} bytes)`,`string_length`);r&&t.push(r),n+=i},build:()=>t.join(``)}}function eAe(e,t,n){let r=(e,t=2)=>String(e).padStart(t,`0`);if(e===``)return`${r(t.getHours())}:${r(t.getMinutes())}:${r(t.getSeconds())}`;let i=F6(n),a=0;for(;a=e.length){i.append(`%`),a++;continue}let n=e[a+1];switch(n){case`H`:i.append(r(t.getHours()));break;case`M`:i.append(r(t.getMinutes()));break;case`S`:i.append(r(t.getSeconds()));break;case`d`:i.append(r(t.getDate()));break;case`m`:i.append(r(t.getMonth()+1));break;case`Y`:i.append(String(t.getFullYear()));break;case`y`:i.append(r(t.getFullYear()%100));break;case`I`:{let e=t.getHours()%12;e===0&&(e=12),i.append(r(e));break}case`p`:i.append(t.getHours()<12?`AM`:`PM`);break;case`P`:i.append(t.getHours()<12?`am`:`pm`);break;case`%`:i.append(`%`);break;case`a`:i.append([`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`][t.getDay()]);break;case`b`:i.append([`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`][t.getMonth()]);break;default:i.append(`%${n}`)}a+=2}else i.append(e[a]),a++;return i.build()}function I6(e,t){let n=F6(e.limits.maxStringLength),r=0,i=e.state.env.get(`USER`)||e.state.env.get(`LOGNAME`)||`user`,a=e.state.env.get(`HOSTNAME`)||`localhost`,o=a.split(`.`)[0],s=e.state.env.get(`PWD`)||`/`,c=e.state.env.get(`HOME`)||`/`,l=s.startsWith(c)?`~${s.slice(c.length)}`:s,u=s.split(`/`).pop()||s,d=new Date,f=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],p=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],m=e.state.env.get(`__COMMAND_NUMBER`)||`1`;for(;r=t.length){n.append(`\\`),r++;continue}let s=t[r+1];if(s>=`0`&&s<=`7`){let e=``,i=r+1;for(;i=`0`&&t[i]<=`7`;)e+=t[i],i++;let a=Number.parseInt(e,8)%256;n.append(String.fromCharCode(a)),r=i;continue}switch(s){case`\\`:n.append(`\\`),r+=2;break;case`a`:n.append(`\x07`),r+=2;break;case`e`:n.append(`\x1B`),r+=2;break;case`n`:n.append(` +`),r+=2;break;case`r`:n.append(`\r`),r+=2;break;case`$`:n.append(`$`),r+=2;break;case`[`:case`]`:r+=2;break;case`u`:n.append(i),r+=2;break;case`h`:n.append(o),r+=2;break;case`H`:n.append(a),r+=2;break;case`w`:n.append(l),r+=2;break;case`W`:n.append(u),r+=2;break;case`d`:{let e=String(d.getDate()).padStart(2,` `);n.append(`${f[d.getDay()]} ${p[d.getMonth()]} ${e}`),r+=2;break}case`t`:{let e=String(d.getHours()).padStart(2,`0`),t=String(d.getMinutes()).padStart(2,`0`),i=String(d.getSeconds()).padStart(2,`0`);n.append(`${e}:${t}:${i}`),r+=2;break}case`T`:{let e=d.getHours()%12;e===0&&(e=12);let t=String(e).padStart(2,`0`),i=String(d.getMinutes()).padStart(2,`0`),a=String(d.getSeconds()).padStart(2,`0`);n.append(`${t}:${i}:${a}`),r+=2;break}case`@`:{let e=d.getHours()%12;e===0&&(e=12);let t=String(e).padStart(2,`0`),i=String(d.getMinutes()).padStart(2,`0`),a=d.getHours()<12?`AM`:`PM`;n.append(`${t}:${i} ${a}`),r+=2;break}case`A`:{let e=String(d.getHours()).padStart(2,`0`),t=String(d.getMinutes()).padStart(2,`0`);n.append(`${e}:${t}`),r+=2;break}case`D`:if(r+20&&e.state.localScopes[e.state.localScopes.length-1].has(t)&&!n){for(e.state.localExportedVars||(e.state.localExportedVars=[]);e.state.localExportedVars.length0?String(n.length):e.state.env.get(t)===void 0?`0`:`1`}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&v6(e,t)){if(t===`FUNCNAME`){let t=e.state.funcNameStack?.[0]||``;return String([...t].length)}if(t===`BASH_LINENO`){let t=e.state.callLineStack?.[0];return String(t===void 0?0:[...String(t)].length)}let n=t4(e,t,0)||``;return String([...n].length)}return String([...n].length)}async function cAe(e,t,n,r){e.coverage?.hit(`bash:expansion:substring`);let i=await M8(e,r.offset.expression),a=r.length?await M8(e,r.length.expression):void 0;if(t===`@`||t===`*`){let t=Number.parseInt(e.state.env.get(`#`)||`0`,10),n=[];for(let r=1;r<=t;r++)n.push(e.state.env.get(String(r))||``);let r=e.state.env.get(`0`)||`bash`,o,s;if(i<=0){if(o=[r,...n],i<0){if(s=o.length+i,s<0)return``}else s=0}else o=n,s=i-1;if(s<0||s>=o.length)return``;if(a!==void 0){let e=a<0?o.length+a:s+a;return o.slice(s,Math.max(s,e)).join(` `)}return o.slice(s).join(` `)}let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(o){let t=o[1];if(e.state.associativeArrays?.has(t))throw new LB(1,``,`bash: \${${t}[@]: 0: 3}: bad substitution +`);let n=_6(e,t),r=0;if(i<0){if(n.length>0){let e=n[n.length-1][0],t=(typeof e==`number`?e:0)+1+i;if(t<0||(r=n.findIndex(([e])=>typeof e==`number`&&e>=t),r<0))return``}}else if(r=n.findIndex(([e])=>typeof e==`number`&&e>=i),r<0)return``;if(a!==void 0){if(a<0)throw new RB(`${o[1]}[@]: substring expression < 0`);return n.slice(r,r+a).map(([,e])=>e).join(` `)}return n.slice(r).map(([,e])=>e).join(` `)}let s=[...n],c=i;if(c<0&&(c=Math.max(0,s.length+c)),a!==void 0){if(a<0){let e=s.length+a;return s.slice(c,Math.max(c,e)).join(``)}return s.slice(c,c+a).join(``)}return s.slice(c).join(``)}async function lAe(e,t,n,r,i){if(e.coverage?.hit(`bash:expansion:case_modification`),n.pattern){let a=e.state.shoptOptions.extglob,o=``;for(let t of n.pattern.parts)if(t.type===`Glob`)o+=j6(t.pattern,!0,a);else if(t.type===`Literal`)o+=j6(t.value,!0,a);else if(t.type===`SingleQuoted`||t.type===`Escaped`)o+=A6(t.value);else if(t.type===`DoubleQuoted`){let n=await r(e,t.parts);o+=A6(n)}else if(t.type===`ParameterExpansion`){let n=await i(e,t);o+=j6(n,!0,a)}let s=mG(`^(?:${o})$`),c=n.direction===`upper`?e=>e.toUpperCase():e=>e.toLowerCase(),l=``,u=!1;for(let e of t)!n.all&&u?l+=e:s.test(e)?(l+=c(e),u=!0):l+=e;return l}return n.direction===`upper`?n.all?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1):n.all?t.toLowerCase():t.charAt(0).toLowerCase()+t.slice(1)}function uAe(e,t,n,r,i){e.coverage?.hit(`bash:expansion:transform`);let a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(a&&i.operator===`Q`)return _6(e,a[1]).map(([,e])=>L6(e)).join(` `);if(a&&i.operator===`a`)return U6(e,a[1]);let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[.+\]$/);if(o&&i.operator===`a`)return U6(e,o[1]);switch(i.operator){case`Q`:return r?``:L6(n);case`P`:return I6(e,n);case`a`:return U6(e,t);case`A`:return r?``:`${t}=${L6(n)}`;case`E`:return n.replace(/\\([\\abefnrtv'"?])/g,(e,t)=>{switch(t){case`\\`:return`\\`;case`a`:return`\x07`;case`b`:return`\b`;case`e`:return`\x1B`;case`f`:return`\f`;case`n`:return` +`;case`r`:return`\r`;case`t`:return` `;case`v`:return`\v`;case`'`:return`'`;case`"`:return`"`;case`?`:return`?`;default:return t}});case`K`:case`k`:return r?``:L6(n);case`u`:return n.charAt(0).toUpperCase()+n.slice(1);case`U`:return n.toUpperCase();case`L`:return n.toLowerCase();default:return n}}async function dAe(e,t,n,r,i,a,o=!1){if(e.coverage?.hit(`bash:expansion:indirection`),c6(e,t))return m6(e,t)||``;let s=/^[a-zA-Z_][a-zA-Z0-9_]*\[([@*])\]$/.test(t);if(r){if(i.innerOp?.type===`UseAlternative`)return``;throw new zB(`\${!${t}}`)}let c=n;if(s&&(c===``||c.includes(` `)))throw new zB(`\${!${t}}`);let l=c.match(/^[a-zA-Z_][a-zA-Z0-9_]*\[(.+)\]$/);if(l&&l[1].includes(`~`))throw new zB(`\${!${t}}`);return i.innerOp?a(e,{type:`ParameterExpansion`,parameter:c,operation:i.innerOp},o):await y6(e,c)}function fAe(e,t){e.coverage?.hit(`bash:expansion:array_keys`);let n=_6(e,t.array).map(([e])=>String(e));return t.star?n.join(r6(e.state.env)):n.join(` `)}function pAe(e,t){e.coverage?.hit(`bash:expansion:var_name_prefix`);let n=N6(e,t.prefix);return t.star?n.join(r6(e.state.env)):n.join(` `)}function mAe(e,t,n,r){let i=Number.parseInt(e.state.env.get(`#`)||`0`,10),a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(t===`*`)return{isEmpty:i===0,effectiveValue:n};if(t===`@`)return{isEmpty:i===0||i===1&&e.state.env.get(`1`)===``,effectiveValue:n};if(a){let[,t,n]=a,i=_6(e,t);if(i.length===0)return{isEmpty:!0,effectiveValue:``};if(n===`*`){let t=r6(e.state.env),n=i.map(([,e])=>e).join(t);return{isEmpty:r?n===``:!1,effectiveValue:n}}return{isEmpty:i.length===1&&i.every(([,e])=>e===``),effectiveValue:i.map(([,e])=>e).join(` `)}}return{isEmpty:n===``,effectiveValue:n}}U();function hAe(e){let t=0;for(;t0;){let t=e[r];if(t===`\\`&&!i&&r+1q6(e,t)).join(`:`)}U(),U();function Y6(e,t,n,r){if(e.length>n-t.length)throw new H(`${r} element limit exceeded (${n})`,`array_elements`);for(let n of t)e.push(n)}yG();async function yAe(e,t,n,r){let i=``;for(let a of t.parts)if(a.type===`Glob`)i+=j6(a.pattern,!0,e.state.shoptOptions.extglob);else if(a.type===`Literal`)i+=j6(a.value,!0,e.state.shoptOptions.extglob);else if(a.type===`SingleQuoted`||a.type===`Escaped`)i+=A6(a.value);else if(a.type===`DoubleQuoted`){let t=await n(e,a.parts);i+=A6(t)}else if(a.type===`ParameterExpansion`){let t=await r(e,a);i+=j6(t,!0,e.state.shoptOptions.extglob)}else{let t=await r(e,a);i+=A6(t)}return i}async function bAe(e,t,n,r){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let i=t[0];if(i.parts.length!==1||i.parts[0].type!==`ParameterExpansion`||i.parts[0].operation?.type!==`PatternReplacement`)return null;let a=i.parts[0],o=a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!o)return null;let s=o[1],c=o[2]===`*`,l=a.operation,u=_6(e,s),d=u.map(([,e])=>e);if(u.length===0){let t=e.state.env.get(s);t!==void 0&&d.push(t)}if(d.length===0)return{values:[],quoted:!0};let f=``;l.pattern&&(f=await yAe(e,l.pattern,n,r));let p=l.replacement?await n(e,l.replacement.parts):``,m=f;l.anchor===`start`?m=`^${f}`:l.anchor===`end`&&(m=`${f}$`);let h=[];try{let e=mG(m,l.all?`g`:``);for(let t of d)h.push(e.replace(t,p))}catch{h.push(...d)}if(c){let t=r6(e.state.env);return{values:[h.join(t)],quoted:!0}}return{values:h,quoted:!0}}async function xAe(e,t,n,r){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let i=t[0];if(i.parts.length!==1||i.parts[0].type!==`ParameterExpansion`||i.parts[0].operation?.type!==`PatternRemoval`)return null;let a=i.parts[0],o=a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!o)return null;let s=o[1],c=o[2]===`*`,l=a.operation,u=_6(e,s),d=u.map(([,e])=>e);if(u.length===0){let t=e.state.env.get(s);t!==void 0&&d.push(t)}if(d.length===0)return{values:[],quoted:!0};let f=``,p=e.state.shoptOptions.extglob;if(l.pattern)for(let t of l.pattern.parts)if(t.type===`Glob`)f+=j6(t.pattern,l.greedy,p);else if(t.type===`Literal`)f+=j6(t.value,l.greedy,p);else if(t.type===`SingleQuoted`||t.type===`Escaped`)f+=A6(t.value);else if(t.type===`DoubleQuoted`){let r=await n(e,t.parts);f+=A6(r)}else if(t.type===`ParameterExpansion`){let n=await r(e,t);f+=j6(n,l.greedy,p)}else{let n=await r(e,t);f+=A6(n)}let m=[];for(let t of d)m.push(M6(e,t,f,l.side,l.greedy));if(c){let t=r6(e.state.env);return{values:[m.join(t)],quoted:!0}}return{values:m,quoted:!0}}yG();async function SAe(e,t){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!==`ParameterExpansion`||n.parts[0].operation?.type!==`DefaultValue`&&n.parts[0].operation?.type!==`UseAlternative`&&n.parts[0].operation?.type!==`AssignDefault`)return null;let r=n.parts[0],i=r.operation,a=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/),o,s=!1;if(a){let t=a[1];s=a[2]===`*`;let n=_6(e,t),r=n.length>0||e.state.env.has(t),c=n.length===0||n.length===1&&n.every(([,e])=>e===``),l=i.checkEmpty??!1;if(o=i.type===`UseAlternative`?r&&!(l&&c):!r||l&&c,!o){if(n.length>0){let t=n.map(([,e])=>e);if(s){let n=r6(e.state.env);return{values:[t.join(n)],quoted:!0}}return{values:t,quoted:!0}}let r=e.state.env.get(t);return r===void 0?{values:[],quoted:!0}:{values:[r],quoted:!0}}}else{let t=r.parameter,n=await b6(e,t),a=await y6(e,t),s=a===``,c=i.checkEmpty??!1;if(o=i.type===`UseAlternative`?n&&!(c&&s):!n||c&&s,!o)return{values:[a],quoted:!0}}if(o&&i.word){let t=i.word.parts,n=null,r=!1;for(let e of t)if(e.type===`ParameterExpansion`&&!e.operation){let t=e.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(t){n=t[1],r=t[2]===`*`;break}}if(n){let t=_6(e,n);if(t.length>0){let n=t.map(([,e])=>e);if(r||s){let t=r6(e.state.env);return{values:[n.join(t)],quoted:!0}}return{values:n,quoted:!0}}let i=e.state.env.get(n);return i===void 0?{values:[],quoted:!0}:{values:[i],quoted:!0}}}return null}async function CAe(e,t,n,r,i){if(!n||t.length!==1||t[0].type!==`DoubleQuoted`)return null;let a=t[0],o=-1,s=``,c=!1,l=null;for(let e=0;ee);if(f.length===0){let t=e.state.env.get(s);if(t!==void 0)p=[t];else{if(c)return{values:[u+d],quoted:!0};let e=u+d;return{values:e?[e]:[],quoted:!0}}}if(l?.type===`PatternRemoval`){let t=l,n=``,a=e.state.shoptOptions.extglob;if(t.pattern)for(let o of t.pattern.parts)if(o.type===`Glob`)n+=j6(o.pattern,t.greedy,a);else if(o.type===`Literal`)n+=j6(o.value,t.greedy,a);else if(o.type===`SingleQuoted`||o.type===`Escaped`)n+=A6(o.value);else if(o.type===`DoubleQuoted`){let t=await i(e,o.parts);n+=A6(t)}else if(o.type===`ParameterExpansion`){let i=await r(e,o);n+=j6(i,t.greedy,a)}else{let t=await r(e,o);n+=A6(t)}p=p.map(r=>M6(e,r,n,t.side,t.greedy))}else if(l?.type===`PatternReplacement`){let t=l,n=``;if(t.pattern)for(let a of t.pattern.parts)if(a.type===`Glob`)n+=j6(a.pattern,!0,e.state.shoptOptions.extglob);else if(a.type===`Literal`)n+=j6(a.value,!0,e.state.shoptOptions.extglob);else if(a.type===`SingleQuoted`||a.type===`Escaped`)n+=A6(a.value);else if(a.type===`DoubleQuoted`){let t=await i(e,a.parts);n+=A6(t)}else if(a.type===`ParameterExpansion`){let t=await r(e,a);n+=j6(t,!0,e.state.shoptOptions.extglob)}else{let t=await r(e,a);n+=A6(t)}let a=t.replacement?await i(e,t.replacement.parts):``,o=n;t.anchor===`start`?o=`^${n}`:t.anchor===`end`&&(o=`${n}$`);try{let e=mG(o,t.all?`g`:``);p=p.map(t=>e.replace(t,a))}catch{}}if(c){let t=r6(e.state.env);return{values:[u+p.join(t)+d],quoted:!0}}return p.length===1?{values:[u+p[0]+d],quoted:!0}:{values:[u+p[0],...p.slice(1,-1),p[p.length-1]+d],quoted:!0}}async function wAe(e,t,n,r){if(!n||t.length!==1||t[0].type!==`DoubleQuoted`)return null;let i=t[0],a=-1,o=``,s=!1;for(let e=0;ee);if(u.length===0){let t=e.state.env.get(o);if(t!==void 0)return{values:[c+t+l],quoted:!0};if(s)return{values:[c+l],quoted:!0};let n=c+l;return{values:n?[n]:[],quoted:!0}}if(s){let t=r6(e.state.env);return{values:[c+d.join(t)+l],quoted:!0}}return d.length===1?{values:[c+d[0]+l],quoted:!0}:{values:[c+d[0],...d.slice(1,-1),d[d.length-1]+l],quoted:!0}}XB(),U();async function TAe(e,t,n){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!==`ParameterExpansion`||r.parts[0].operation?.type!==`Substring`)return null;let i=r.parts[0],a=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!a)return null;let o=a[1],s=a[2]===`*`,c=i.operation;if(e.state.associativeArrays?.has(o))throw new LB(1,``,`bash: \${${o}[@]: 0: 3}: bad substitution +`);let l=c.offset?await n(e,c.offset.expression):0,u=c.length?await n(e,c.length.expression):void 0,d=_6(e,o);if(d.length>e.limits.maxArrayElements)throw new H(`array transform element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);let f=0;if(l<0){if(d.length>0){let e=d[d.length-1][0],t=(typeof e==`number`?e:0)+1+l;if(t<0)return{values:[],quoted:!0};f=d.findIndex(([e])=>typeof e==`number`&&e>=t),f<0&&(f=d.length)}}else f=d.findIndex(([e])=>typeof e==`number`&&e>=l),f<0&&(f=d.length);let p;if(u!==void 0){if(u<0)throw new RB(`${o}[@]: substring expression < 0`);p=d.slice(f,f+u).map(([,e])=>e)}else p=d.slice(f).map(([,e])=>e);if(p.length===0)return{values:[],quoted:!0};if(s){let t=r6(e.state.env);return{values:[p.join(t)],quoted:!0}}return{values:p,quoted:!0}}function EAe(e,t){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!==`ParameterExpansion`||n.parts[0].operation?.type!==`Transform`)return null;let r=n.parts[0],i=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!i)return null;let a=i[1],o=i[2]===`*`,s=r.operation,c=_6(e,a);if(c.length===0){let t=e.state.env.get(a);if(t!==void 0){let n;switch(s.operator){case`a`:n=``;break;case`P`:n=I6(e,t);break;case`Q`:n=L6(t);break;default:n=t}if(V(n)>e.limits.maxStringLength)throw new H(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);return{values:[n],quoted:!0}}return o?{values:[``],quoted:!0}:{values:[],quoted:!0}}let l=U6(e,a),u=[],d=0;for(let[,t]of c){let n;switch(s.operator){case`a`:n=l;break;case`P`:n=I6(e,t);break;case`Q`:n=L6(t);break;case`u`:n=t.charAt(0).toUpperCase()+t.slice(1);break;case`U`:n=t.toUpperCase();break;case`L`:n=t.toLowerCase();break;default:n=t}let r=V(n);if(r>e.limits.maxStringLength-d)throw new H(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);u.push(n),d+=r}if(o){let t=r6(e.state.env);if(Math.max(0,u.length-1)*V(t)>e.limits.maxStringLength-d)throw new H(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);return{values:[u.join(t)],quoted:!0}}return{values:u,quoted:!0}}function DAe(e,t){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!==`ParameterExpansion`)return null;let r=n.parts[0];if(r.operation)return null;let i=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!i)return null;let a=i[1];if(c6(e,a)){let t=m6(e,a);if(t?.endsWith(`[@]`)||t?.endsWith(`[*]`))return{values:[],quoted:!0}}let o=_6(e,a);if(o.length>0)return{values:o.map(([,e])=>e),quoted:!0};let s=e.state.env.get(a);return s===void 0?{values:[],quoted:!0}:{values:[s],quoted:!0}}function OAe(e,t){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!==`ParameterExpansion`||n.parts[0].operation)return null;let r=n.parts[0].parameter;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)||!c6(e,r))return null;let i=m6(e,r);if(!i)return null;let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!a)return null;let o=a[1],s=_6(e,o);if(s.length>0)return{values:s.map(([,e])=>e),quoted:!0};let c=e.state.env.get(o);return c===void 0?{values:[],quoted:!0}:{values:[c],quoted:!0}}U();async function kAe(e,t,n,r,i){if(!n||t.length!==1||t[0].type!==`DoubleQuoted`)return null;let a=t[0];if(a.parts.length!==1||a.parts[0].type!==`ParameterExpansion`||a.parts[0].operation?.type!==`Indirection`)return null;let o=a.parts[0],s=o.operation,c=await y6(e,o.parameter),l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!l){if(!s.innerOp&&(c===`@`||c===`*`)){let t=Number.parseInt(e.state.env.get(`#`)||`0`,10),n=[];for(let r=1;r<=t;r++)n.push(e.state.env.get(String(r))||``);return c===`*`?{values:[n.join(r6(e.state.env))],quoted:!0}:{values:n,quoted:!0}}return null}let u=l[1],d=l[2]===`*`,f=_6(e,u);if(s.innerOp){if(s.innerOp.type===`Substring`)return AAe(e,f,u,d,s.innerOp);if(s.innerOp.type===`DefaultValue`||s.innerOp.type===`UseAlternative`||s.innerOp.type===`AssignDefault`||s.innerOp.type===`ErrorIfUnset`)return jAe(e,f,u,d,s.innerOp,i);if(s.innerOp.type===`Transform`&&s.innerOp.operator===`a`){let t=U6(e,u),n=f.map(()=>t);return d?{values:[n.join(r6(e.state.env))],quoted:!0}:{values:n,quoted:!0}}let t=[];for(let[,n]of f){let i={type:`ParameterExpansion`,parameter:`_indirect_elem_`,operation:s.innerOp},a=e.state.env.get(`_indirect_elem_`);e.state.env.set(`_indirect_elem_`,n);try{let n=await r(e,i,!0);t.push(n)}finally{a===void 0?e.state.env.delete(`_indirect_elem_`):e.state.env.set(`_indirect_elem_`,a)}}return d?{values:[t.join(r6(e.state.env))],quoted:!0}:{values:t,quoted:!0}}if(f.length>0){let t=f.map(([,e])=>e);return d?{values:[t.join(r6(e.state.env))],quoted:!0}:{values:t,quoted:!0}}let p=e.state.env.get(u);return p===void 0?{values:[],quoted:!0}:{values:[p],quoted:!0}}async function AAe(e,t,n,r,i){let a=i.offset?await M8(e,i.offset.expression):0,o=i.length?await M8(e,i.length.expression):void 0,s=0;if(a<0){if(t.length>0){let e=t[t.length-1][0],n=(typeof e==`number`?e:0)+1+a;if(n<0||(s=t.findIndex(([e])=>typeof e==`number`&&e>=n),s<0))return{values:[],quoted:!0}}}else if(s=t.findIndex(([e])=>typeof e==`number`&&e>=a),s<0)return{values:[],quoted:!0};let c;if(o!==void 0){if(o<0)throw new RB(`${n}[@]: substring expression < 0`);c=t.slice(s,s+o)}else c=t.slice(s);let l=c.map(([,e])=>e);return r?{values:[l.join(r6(e.state.env))],quoted:!0}:{values:l,quoted:!0}}async function jAe(e,t,n,r,i,a){let o=i.checkEmpty??!1,s=t.map(([,e])=>e),c=t.length===0,l=t.length===0;if(i.type===`UseAlternative`)return!l&&!(o&&c)&&i.word?{values:[await a(e,i.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(i.type===`DefaultValue`)return(l||o&&c)&&i.word?{values:[await a(e,i.word.parts,!0)],quoted:!0}:r?{values:[s.join(r6(e.state.env))],quoted:!0}:{values:s,quoted:!0};if(i.type===`AssignDefault`){if((l||o&&c)&&i.word){let t=await a(e,i.word.parts,!0);return r4(e,n,0,t),{values:[t],quoted:!0}}return r?{values:[s.join(r6(e.state.env))],quoted:!0}:{values:s,quoted:!0}}return r?{values:[s.join(r6(e.state.env))],quoted:!0}:{values:s,quoted:!0}}async function MAe(e,t){if(t.length!==1||t[0].type!==`ParameterExpansion`||t[0].operation?.type!==`UseAlternative`&&t[0].operation?.type!==`DefaultValue`)return null;let n=t[0],r=n.operation,i=r?.word;if(!i||i.parts.length!==1||i.parts[0].type!==`DoubleQuoted`)return null;let a=i.parts[0];if(a.parts.length!==1||a.parts[0].type!==`ParameterExpansion`||a.parts[0].operation?.type!==`Indirection`)return null;let o=a.parts[0],s=(await y6(e,o.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!s)return null;let c=await b6(e,n.parameter),l=await y6(e,n.parameter)===``,u=r.checkEmpty??!1,d;if(d=r.type===`UseAlternative`?c&&!(u&&l):!c||u&&l,d){let t=s[1],n=s[2]===`*`,r=_6(e,t);if(r.length>0){let t=r.map(([,e])=>e);return n?{values:[t.join(r6(e.state.env))],quoted:!0}:{values:t,quoted:!0}}let i=e.state.env.get(t);return i===void 0?{values:[],quoted:!0}:{values:[i],quoted:!0}}return{values:[],quoted:!1}}async function NAe(e,t){if(t.length!==1||t[0].type!==`ParameterExpansion`||t[0].operation?.type!==`Indirection`)return null;let n=t[0],r=n.operation.innerOp;if(!r||r.type!==`UseAlternative`&&r.type!==`DefaultValue`)return null;let i=r.word;if(!i||i.parts.length!==1||i.parts[0].type!==`DoubleQuoted`)return null;let a=i.parts[0];if(a.parts.length!==1||a.parts[0].type!==`ParameterExpansion`||a.parts[0].operation?.type!==`Indirection`)return null;let o=a.parts[0],s=(await y6(e,o.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!s)return null;let c=await y6(e,n.parameter),l=await b6(e,n.parameter),u=c===``,d=r.checkEmpty??!1,f;if(f=r.type===`UseAlternative`?l&&!(d&&u):!l||d&&u,f){let t=s[1],n=s[2]===`*`,r=_6(e,t);if(r.length>0){let t=r.map(([,e])=>e);return n?{values:[t.join(r6(e.state.env))],quoted:!0}:{values:t,quoted:!0}}let i=e.state.env.get(t);return i===void 0?{values:[],quoted:!0}:{values:[i],quoted:!0}}return{values:[],quoted:!1}}XB(),yG(),U();function X6(e){let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);if(t>e.limits.maxArrayElements)throw new H(`positional parameter element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);let n=[],r=0;for(let i=1;i<=t;i++){let t=e.state.env.get(String(i))||``,a=V(t);if(a>e.limits.maxStringLength-r)throw new H(`positional parameter string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);n.push(t),r+=a}return n}function Z6(e,t,n){if(V(t)>n-V(e))throw new H(`positional expansion string limit exceeded (${n} bytes)`,`string_length`);return e+t}function Q6(e,t,n,r){if(e.length>=r.limits.maxArrayElements)throw new H(`positional expansion element limit exceeded (${r.limits.maxArrayElements})`,`array_elements`);let i=V(t);if(i>r.limits.maxStringLength-n.value)throw new H(`positional expansion string limit exceeded (${r.limits.maxStringLength} bytes)`,`string_length`);e.push(t),n.value+=i}async function PAe(e,t,n,r){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let i=t[0],a=-1,o=!1;for(let e=0;e=d.length)p=[];else if(l!==void 0){let t=l<0?d.length+l:e+l;p=d.slice(e,Math.max(e,t))}else p=d.slice(e)}let m=``;for(let t=0;t]+>|`|')/g;for(;c.exec(f)!==null;)o++;if(i+r*a+r*o*i>e.limits.maxStringLength-h.value)throw new H(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);Q6(m,t.replace(n,f),h,e)}}catch(t){if(t instanceof H)throw t;for(let t of c)Q6(m,t,h,e)}if(o){let t=r6(e.state.env);if(h.value+Math.max(0,m.length-1)*V(t)+V(l)+V(u)>e.limits.maxStringLength)throw new H(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);return{values:[l+m.join(t)+u],quoted:!0}}if(V(l)+h.value+V(u)>e.limits.maxStringLength)throw new H(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);return m.length===1?{values:[l+m[0]+u],quoted:!0}:{values:[l+m[0],...m.slice(1,-1),m[m.length-1]+u],quoted:!0}}async function IAe(e,t,n,r){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let i=t[0],a=-1,o=!1;for(let e=0;ee.limits.maxStringLength)throw new H(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);return{values:[l+p.join(t)+u],quoted:!0}}if(V(l)+m.value+V(u)>e.limits.maxStringLength)throw new H(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);return p.length===1?{values:[l+p[0]+u],quoted:!0}:{values:[l+p[0],...p.slice(1,-1),p[p.length-1]+u],quoted:!0}}async function LAe(e,t,n){if(t.length!==1||t[0].type!==`DoubleQuoted`)return null;let r=t[0],i=-1,a=!1;for(let e=0;e=e.limits.maxArrayElements)throw new H(`unquoted expansion element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);let i=V(n);if(i>e.limits.maxStringLength-r.value)throw new H(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);t.push(n),r.value+=i}function e8(e,t,n,r){let i=V(n),a=Math.max(0,t.length-1);if(i>0&&a>Math.floor((e.limits.maxStringLength-r)/i))throw new H(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);return t.join(n)}function RAe(e){return new Y3(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited(`glob_operations`,1,e.limits.maxGlobOperations,`glob expansion`)})}async function t8(e,t){if(e.state.options.noglob)return t;let n=RAe(e),r=[];for(let i of t)if(E6(i,e.state.shoptOptions.extglob)){let t=await n.expand(i);if(t.length>0)Y6(r,t,e.limits.maxArrayElements,`unquoted glob expansion`);else{if(n.hasFailglob())throw new BB(i);n.hasNullglob()||r.push(i)}}else r.push(i);return r}async function zAe(e,t,n,r){let i=-1,a=``,o=!1;for(let e=0;ee);if(c.length===0){let t=e.state.env.get(a);t!==void 0&&(l=[t])}if(l.length===0)return{values:[],quoted:!1};let u=``;if(s.pattern)for(let t of s.pattern.parts)if(t.type===`Glob`)u+=j6(t.pattern,!0,e.state.shoptOptions.extglob);else if(t.type===`Literal`)u+=j6(t.value,!0,e.state.shoptOptions.extglob);else if(t.type===`SingleQuoted`||t.type===`Escaped`)u+=A6(t.value);else if(t.type===`DoubleQuoted`){let r=await n(e,t.parts);u+=A6(r)}else if(t.type===`ParameterExpansion`){let n=await r(e,t);u+=j6(n,!0,e.state.shoptOptions.extglob)}else{let n=await r(e,t);u+=A6(n)}let d=s.replacement?await n(e,s.replacement.parts):``,f=u;s.anchor===`start`?f=`^${u}`:s.anchor===`end`&&(f=`${u}$`);let p=[],m={value:0};try{let t=mG(f,s.all?`g`:``);for(let n of l)$6(e,p,P6(e,n,t,d,s.all),m)}catch(t){if(t instanceof H)throw t;for(let t of l)$6(e,p,t,m)}let h=e6(e.state.env),g=t6(e.state.env);if(o){let t=e8(e,p,r6(e.state.env),m.value);return g?{values:t?[t]:[],quoted:!1}:{values:s6(t,h,e.limits.maxArrayElements),quoted:!1}}if(g)return{values:p,quoted:!1};let _=[],v={value:0};for(let t of p)if(t===``)$6(e,_,``,v);else for(let n of s6(t,h,e.limits.maxArrayElements))$6(e,_,n,v);return{values:_,quoted:!1}}async function BAe(e,t,n,r){let i=-1,a=``,o=!1;for(let e=0;ee);if(c.length===0){let t=e.state.env.get(a);t!==void 0&&(l=[t])}if(l.length===0)return{values:[],quoted:!1};let u=``,d=e.state.shoptOptions.extglob;if(s.pattern)for(let t of s.pattern.parts)if(t.type===`Glob`)u+=j6(t.pattern,s.greedy,d);else if(t.type===`Literal`)u+=j6(t.value,s.greedy,d);else if(t.type===`SingleQuoted`||t.type===`Escaped`)u+=A6(t.value);else if(t.type===`DoubleQuoted`){let r=await n(e,t.parts);u+=A6(r)}else if(t.type===`ParameterExpansion`){let n=await r(e,t);u+=j6(n,s.greedy,d)}else{let n=await r(e,t);u+=A6(n)}let f=[],p={value:0};for(let t of l)$6(e,f,M6(e,t,u,s.side,s.greedy),p);let m=e6(e.state.env),h=t6(e.state.env);if(o){let t=e8(e,f,r6(e.state.env),p.value);return h?{values:t?[t]:[],quoted:!1}:{values:s6(t,m,e.limits.maxArrayElements),quoted:!1}}if(h)return{values:f,quoted:!1};let g=[],_={value:0};for(let t of f)if(t===``)$6(e,g,``,_);else for(let n of s6(t,m,e.limits.maxArrayElements))$6(e,g,n,_);return{values:g,quoted:!1}}async function VAe(e,t,n,r){let i=-1,a=!1;for(let e=0;e=u.length)f=[];else if(c!==void 0){let t=c<0?u.length+c:e+c;f=u.slice(e,Math.max(e,t))}else f=u.slice(e)}let p=``;for(let n=0;ne!==``);else{let t=r6(e.state.env);c=s6(i.join(t),a,e.limits.maxArrayElements)}}else if(o)c=i.filter(e=>e!==``);else if(s){c=[];for(let t of i){if(t===``)continue;let n=s6(t,a,e.limits.maxArrayElements);Y6(c,n,e.limits.maxArrayElements,`unquoted expansion`)}}else{c=[];for(let t of i)if(t===``)c.push(``);else{let n=s6(t,a,e.limits.maxArrayElements);Y6(c,n,e.limits.maxArrayElements,`unquoted expansion`)}for(;c.length>0&&c[c.length-1]===``;)c.pop()}return{values:await t8(e,c),quoted:!1}}async function WAe(e,t){if(t.length!==1||t[0].type!==`ParameterExpansion`||t[0].operation)return null;let n=t[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!n)return null;let r=n[1],i=n[2]===`*`,a=_6(e,r),o;if(a.length===0){let t=e.state.env.get(r);if(t!==void 0)o=[t];else return{values:[],quoted:!1}}else o=a.map(([,e])=>e);let s=e6(e.state.env),c=t6(e.state.env),l=n6(e.state.env),u;if(i){if(c)u=o.filter(e=>e!==``);else{let t=r6(e.state.env);u=s6(o.join(t),s,e.limits.maxArrayElements)}}else if(c)u=o.filter(e=>e!==``);else if(l){u=[];for(let t of o){if(t===``)continue;let n=s6(t,s,e.limits.maxArrayElements);Y6(u,n,e.limits.maxArrayElements,`unquoted expansion`)}}else{u=[];for(let t of o)if(t===``)u.push(``);else{let n=s6(t,s,e.limits.maxArrayElements);Y6(u,n,e.limits.maxArrayElements,`unquoted expansion`)}for(;u.length>0&&u[u.length-1]===``;)u.pop()}return{values:await t8(e,u),quoted:!1}}function GAe(e,t){if(t.length!==1||t[0].type!==`ParameterExpansion`||t[0].operation?.type!==`VarNamePrefix`)return null;let n=t[0].operation,r=N6(e,n.prefix);if(r.length===0)return{values:[],quoted:!1};let i=e6(e.state.env),a=t6(e.state.env),o;if(n.star){if(a)o=r;else{let t=r6(e.state.env);o=s6(r.join(t),i,e.limits.maxArrayElements)}}else if(a)o=r;else{o=[];for(let t of r){let n=s6(t,i,e.limits.maxArrayElements);Y6(o,n,e.limits.maxArrayElements,`unquoted expansion`)}}return{values:o,quoted:!1}}function KAe(e,t){if(t.length!==1||t[0].type!==`ParameterExpansion`||t[0].operation?.type!==`ArrayKeys`)return null;let n=t[0].operation,r=_6(e,n.array).map(([e])=>String(e));if(r.length===0)return{values:[],quoted:!1};let i=e6(e.state.env),a=t6(e.state.env),o;if(n.star){if(a)o=r;else{let t=r6(e.state.env);o=s6(r.join(t),i,e.limits.maxArrayElements)}}else if(a)o=r;else{o=[];for(let t of r){let n=s6(t,i,e.limits.maxArrayElements);Y6(o,n,e.limits.maxArrayElements,`unquoted expansion`)}}return{values:o,quoted:!1}}async function qAe(e,t,n){let r=-1;for(let e=0;ee!==``);else if(u){d=[];for(let n of t){if(n===``)continue;let t=s6(n,c,e.limits.maxArrayElements);Y6(d,t,e.limits.maxArrayElements,`unquoted expansion`)}}else{d=[];for(let n of t)if(n===``)d.push(``);else{let t=s6(n,c,e.limits.maxArrayElements);Y6(d,t,e.limits.maxArrayElements,`unquoted expansion`)}for(;d.length>0&&d[d.length-1]===``;)d.pop()}}return d.length===0?{values:[],quoted:!1}:{values:await t8(e,d),quoted:!1}}async function JAe(e,t,n){e.coverage?.hit(`bash:expansion:word_glob`);let r=t.parts,{hasQuoted:i,hasCommandSub:a,hasArrayVar:o,hasArrayAtExpansion:s,hasParamExpansion:c,hasVarNamePrefixExpansion:l,hasIndirection:u}=Z3(r),d=n.hasBraceExpansion(r)?await n.expandWordWithBracesAsync(e,t):null;if(d&&d.length>1)return YAe(e,d,i);let f=await XAe(e,r,s,l,u,n);if(f!==null)return f;let p=await QAe(e,r,n);if(p!==null)return p;let m=await $Ae(e,r,n);if(m!==null)return m;let h=await tje(e,r,n.expandPart);if(h!==null)return r8(e,h);if((a||o||c)&&!t6(e.state.env)){let t=e6(e.state.env),i=n.buildIfsCharClassPattern(t);return r8(e,await n.smartWordSplit(e,r,t,i,n.expandPart))}return nje(e,t,r,await n.expandWordAsync(e,t),i,n.expandWordForGlobbing)}async function YAe(e,t,n){let r=[];for(let i of t)(n||i!==``)&&(!n&&!e.state.options.noglob&&E6(i,e.state.shoptOptions.extglob)?Y6(r,await i8(e,i),e.limits.maxArrayElements,`brace/glob expansion`):r.push(i));return{values:r,quoted:!1}}async function XAe(e,t,n,r,i,a){if(n){let n=DAe(e,t);if(n!==null)return n}{let n=OAe(e,t);if(n!==null)return n}{let n=await SAe(e,t);if(n!==null)return n}{let r=await CAe(e,t,n,a.expandPart,a.expandWordPartsAsync);if(r!==null)return r}{let r=await wAe(e,t,n,a.expandPart);if(r!==null)return r}{let n=await TAe(e,t,a.evaluateArithmetic);if(n!==null)return n}{let n=EAe(e,t);if(n!==null)return n}{let n=await bAe(e,t,a.expandWordPartsAsync,a.expandPart);if(n!==null)return n}{let n=await xAe(e,t,a.expandWordPartsAsync,a.expandPart);if(n!==null)return n}if(r&&t.length===1&&t[0].type===`DoubleQuoted`){let n=ZAe(e,t);if(n!==null)return n}{let n=await kAe(e,t,i,a.expandParameterAsync,a.expandWordPartsAsync);if(n!==null)return n}{let n=await MAe(e,t);if(n!==null)return n}{let n=await NAe(e,t);if(n!==null)return n}return null}function ZAe(e,t){let n=t[0];if(n.type!==`DoubleQuoted`)return null;if(n.parts.length===1&&n.parts[0].type===`ParameterExpansion`&&n.parts[0].operation?.type===`VarNamePrefix`){let t=n.parts[0].operation,r=N6(e,t.prefix);return t.star?{values:[r.join(r6(e.state.env))],quoted:!0}:{values:r,quoted:!0}}if(n.parts.length===1&&n.parts[0].type===`ParameterExpansion`&&n.parts[0].operation?.type===`ArrayKeys`){let t=n.parts[0].operation,r=_6(e,t.array).map(([e])=>String(e));return t.star?{values:[r.join(r6(e.state.env))],quoted:!0}:{values:r,quoted:!0}}return null}async function QAe(e,t,n){{let r=await PAe(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await FAe(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await IAe(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await LAe(e,t,n.expandPart);if(r!==null)return r}return null}async function $Ae(e,t,n){{let r=await zAe(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await BAe(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await VAe(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await HAe(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let n=await UAe(e,t);if(n!==null)return n}{let n=await WAe(e,t);if(n!==null)return n}{let n=GAe(e,t);if(n!==null)return n}{let n=KAe(e,t);if(n!==null)return n}{let r=await qAe(e,t,n.expandPart);if(r!==null)return r}return null}function n8(e){if(e.type!==`DoubleQuoted`)return null;for(let t=0;te),o.length===0){let t=e.state.env.get(n.name);t!==void 0&&(o=[t])}}else{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);o=[];for(let n=1;n<=t;n++)o.push(e.state.env.get(String(n))||``)}if(n.isStar){let t=r6(e.state.env),n=o.join(t);return[i+n+a]}if(o.length===0){let e=i+a;return e?[e]:[]}return o.length===1?[i+o[0]+a]:[i+o[0],...o.slice(1,-1),o[o.length-1]+a]}async function tje(e,t,n){if(t.length<2)return null;let r=!1;for(let e of t)if(n8(e)){r=!0;break}if(!r)return null;let i=e6(e.state.env),a=t6(e.state.env),o=[];for(let r of t){let t=n8(r);if(t&&r.type===`DoubleQuoted`){let i=await eje(e,r,t,n);o.push(i)}else if(r.type===`DoubleQuoted`||r.type===`SingleQuoted`){let t=await n(e,r);o.push([t])}else if(r.type===`Literal`)o.push([r.value]);else if(r.type===`ParameterExpansion`){let t=await n(e,r);if(a)o.push(t?[t]:[]);else{let n=s6(t,i,e.limits.maxArrayElements);o.push(n)}}else{let t=await n(e,r);if(a)o.push(t?[t]:[]);else{let n=s6(t,i,e.limits.maxArrayElements);o.push(n)}}}let s=[];for(let t of o)if(t.length!==0){if(s.length===0)Y6(s,t,e.limits.maxArrayElements,`word expansion`);else{let e=s.length-1;s[e]=s[e]+t[0];for(let e=1;ee.executionScope.consumeLimited(`glob_operations`,1,e.limits.maxGlobOperations,`glob expansion`)}),r=await n.expand(t);if(r.length>0)return r;if(n.hasFailglob())throw new BB(t);return n.hasNullglob()?[]:[t]}async function nje(e,t,n,r,i,a){let o=n.some(e=>e.type===`Glob`);if(!e.state.options.noglob&&o){let n=await a(e,t);if(E6(n,e.state.shoptOptions.extglob)){let t=await i8(e,n);if(t.length>0&&t[0]!==n)return{values:t,quoted:!1};if(t.length===0)return{values:[],quoted:!1}}let i=D6(r);return t6(e.state.env)?{values:[i],quoted:!1}:{values:s6(i,e6(e.state.env),e.limits.maxArrayElements),quoted:!1}}if(!i&&!e.state.options.noglob&&E6(r,e.state.shoptOptions.extglob)){let n=await a(e,t);if(E6(n,e.state.shoptOptions.extglob)){let t=await i8(e,n);if(t.length>0&&t[0]!==n)return{values:t,quoted:!1}}}if(r===``&&!i)return{values:[],quoted:!1};if(o&&!i){let t=D6(r);return t6(e.state.env)?{values:[t],quoted:!1}:{values:s6(t,e6(e.state.env),e.limits.maxArrayElements),quoted:!1}}return{values:[r],quoted:i}}U();function a8(e,t,n){if(t.length>=e.limits.maxArrayElements)throw new H(`word splitting element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);t.push(n)}async function o8(e,t){let n=t.operation;if(!n||n.type!==`DefaultValue`&&n.type!==`AssignDefault`&&n.type!==`UseAlternative`)return null;let r=n.word;if(!r||r.parts.length===0)return null;let i=await b6(e,t.parameter),a=await y6(e,t.parameter,!1)===``,o=n.checkEmpty??!1,s;return s=n.type===`UseAlternative`?i&&!(o&&a):!i||o&&a,s?r.parts:null}function rje(e){return e.type===`SingleQuoted`||e.type===`DoubleQuoted`&&e.parts.every(e=>e.type===`Literal`)}async function ije(e,t){if(t.type!==`ParameterExpansion`)return null;let n=await o8(e,t);if(!n||n.length<=1)return null;let r=n.some(e=>rje(e)),i=n.some(e=>e.type===`Literal`||e.type===`ParameterExpansion`||e.type===`CommandSubstitution`||e.type===`ArithmeticExpansion`);return r&&i?n:null}function aje(e){return e.type===`DoubleQuoted`||e.type===`SingleQuoted`||e.type===`Literal`?!1:e.type===`Glob`?X3(e.pattern):!(e.type!==`ParameterExpansion`&&e.type!==`CommandSubstitution`&&e.type!==`ArithmeticExpansion`||e.type===`ParameterExpansion`&&Fke(e))}async function oje(e,t,n,r,i){if(e.coverage?.hit(`bash:expansion:word_split`),t.length===1&&t[0].type===`ParameterExpansion`){let a=t[0],o=await o8(e,a);if(o&&o.length>0&&o.length>1&&o.some(e=>e.type===`DoubleQuoted`||e.type===`SingleQuoted`)&&o.some(e=>e.type===`Literal`||e.type===`ParameterExpansion`||e.type===`CommandSubstitution`||e.type===`ArithmeticExpansion`))return s8(e,o,n,r,i)}let a=[],o=!1;for(let n of t){let t=aje(n),r=n.type===`DoubleQuoted`||n.type===`SingleQuoted`,s=t?await ije(e,n):null,c=await i(e,n);a.push({value:c,isSplittable:t,isQuoted:r,mixedDefaultParts:s??void 0}),t&&(o=!0)}if(!o){let e=a.map(e=>e.value).join(``);return e?[e]:[]}let s=[],c=``,l=!1,u=!1,d=!1;for(let t of a)if(!t.isSplittable)u?t.isQuoted&&t.value===``?(c!==``&&a8(e,s,c),a8(e,s,``),l=!0,c=``,u=!1,d=!0):t.value===``?(c+=t.value,d=!1):(c!==``&&a8(e,s,c),c=t.value,u=!1,d=!1):(c+=t.value,d=t.isQuoted&&t.value===``);else if(t.mixedDefaultParts){let a=await s8(e,t.mixedDefaultParts,n,r,i);if(a.length!==0){if(a.length===1)c+=a[0],l=!0;else{c+=a[0],a8(e,s,c),l=!0;for(let t=1;t0&&t.includes(e[0])}async function s8(e,t,n,r,i){let a=[];for(let n of t){let t=n.type!==`DoubleQuoted`&&n.type!==`SingleQuoted`,r=await i(e,n);a.push({value:r,isSplittable:t})}let o=[],s=``,c=!1,l=!1;for(let t of a)if(!t.isSplittable)l&&t.value!==``?(s!==``&&a8(e,o,s),s=t.value,l=!1):s+=t.value;else{sje(t.value,n)&&s!==``&&(a8(e,o,s),s=``,c=!0);let{words:r,hadTrailingDelimiter:i}=o6(t.value,n,e.limits.maxArrayElements);if(r.length===0)i&&(l=!0);else if(r.length===1)s+=r[0],c=!0,l=i;else{s+=r[0],a8(e,o,s),c=!0;for(let t=1;t({mountPoint:e.mountPoint,filesystem:e.filesystem}))}isMountPoint(e){let t=cH(e);return this.mounts.has(t)}validateMountPath(e){let t=e.split(`/`);for(let n of t)if(n===`.`||n===`..`)throw Error(`Invalid mount point '${e}': contains '.' or '..' segments`)}validateMount(e){if(e===`/`)throw Error(`Cannot mount at root '/'`);for(let t of this.mounts.keys())if(t!==e){if(e.startsWith(`${t}/`))throw Error(`Cannot mount at '${e}': inside existing mount '${t}'`);if(t.startsWith(`${e}/`))throw Error(`Cannot mount at '${e}': would contain existing mount '${t}'`)}}routePath(e){uH(e,`access`);let t=cH(e),n=null,r=0;for(let e of this.mounts.values()){let i=e.mountPoint;if(t===i)return{fs:e.filesystem,relativePath:`/`};t.startsWith(`${i}/`)&&i.length>r&&(n=e,r=i.length)}if(n){let e=t.slice(r);return{fs:n.filesystem,relativePath:e||`/`}}return{fs:this.baseFs,relativePath:t}}getChildMountPoints(e){let t=cH(e),n=t===`/`?`/`:`${t}/`,r=[];for(let e of this.mounts.keys())if(e.startsWith(n)){let t=e.slice(n.length).split(`/`)[0];t&&!r.includes(t)&&r.push(t)}return r}async readFile(e,t){let{fs:n,relativePath:r}=this.routePath(e);return n.readFile(r,t)}async readFileBytes(e){let{fs:t,relativePath:n}=this.routePath(e);return xB(t,n)}async readFileBuffer(e){let{fs:t,relativePath:n}=this.routePath(e);return t.readFileBuffer(n)}async writeFile(e,t,n){let{fs:r,relativePath:i}=this.routePath(e);return r.writeFile(i,t,n)}async appendFile(e,t,n){let{fs:r,relativePath:i}=this.routePath(e);return r.appendFile(i,t,n)}async exists(e){let t=cH(e);if(this.mounts.has(t)||this.getChildMountPoints(t).length>0)return!0;let{fs:n,relativePath:r}=this.routePath(e);return n.exists(r)}async stat(e){let t=cH(e),n=this.mounts.get(t);if(n)try{return await n.filesystem.stat(`/`)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(t).length>0)try{return await this.baseFs.stat(t)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:r,relativePath:i}=this.routePath(e);return r.stat(i)}async lstat(e){let t=cH(e),n=this.mounts.get(t);if(n)try{return await n.filesystem.lstat(`/`)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(t).length>0)try{return await this.baseFs.lstat(t)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:r,relativePath:i}=this.routePath(e);return r.lstat(i)}async mkdir(e,t){let n=cH(e);if(this.mounts.has(n)){if(t?.recursive)return;throw Error(`EEXIST: directory already exists, mkdir '${e}'`)}if(this.getChildMountPoints(n).length>0&&t?.recursive)return;let{fs:r,relativePath:i}=this.routePath(e);return r.mkdir(i,t)}async readdir(e){let t=cH(e),n=new Set,r=null,{fs:i,relativePath:a}=this.routePath(e);try{let e=await i.readdir(a);for(let t of e)n.add(t)}catch(e){let t=e.code,n=e.message||``;if(t!==`ENOENT`&&!n.includes(`ENOENT`))throw e;r=e}let o=this.getChildMountPoints(t);for(let e of o)n.add(e);if(n.size===0&&r&&!this.mounts.has(t))throw r;return Array.from(n).sort()}async rm(e,t){let n=cH(e);if(this.mounts.has(n))throw Error(`EBUSY: mount point, cannot remove '${e}'`);if(this.getChildMountPoints(n).length>0)throw Error(`EBUSY: contains mount points, cannot remove '${e}'`);let{fs:r,relativePath:i}=this.routePath(e);return r.rm(i,t)}async cp(e,t,n){if((await this.stat(e)).isDirectory&&lH(e,t))throw Error(`EINVAL: cannot copy '${e}' into itself, '${t}'`);let r=this.routePath(e),i=this.routePath(t);return r.fs===i.fs?r.fs.cp(r.relativePath,i.relativePath,n):this.crossMountCopy(e,t,n)}async mv(e,t){let n=cH(e);if((await this.stat(e)).isDirectory&&lH(e,t))throw Error(`EINVAL: cannot move '${e}' into itself, '${t}'`);if(this.mounts.has(n))throw Error(`EBUSY: mount point, cannot move '${e}'`);let r=this.routePath(e),i=this.routePath(t);if(r.fs===i.fs)return r.fs.mv(r.relativePath,i.relativePath);await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,t){return fH(e,t)}getAllPaths(){let e=new Set;for(let t of this.baseFs.getAllPaths())e.add(t);for(let t of this.mounts.keys()){let n=t.split(`/`).filter(Boolean),r=``;for(let t of n)r=`${r}/${t}`,e.add(r);let i=this.mounts.get(t);if(i)for(let n of i.filesystem.getAllPaths())n===`/`?e.add(t):e.add(`${t}${n}`)}return Array.from(e).sort()}async chmod(e,t){let n=cH(e),r=this.mounts.get(n);if(r)return r.filesystem.chmod(`/`,t);let{fs:i,relativePath:a}=this.routePath(e);return i.chmod(a,t)}async symlink(e,t){let{fs:n,relativePath:r}=this.routePath(t);return n.symlink(e,r)}async link(e,t){let n=this.routePath(e),r=this.routePath(t);if(n.fs!==r.fs)throw Error(`EXDEV: cross-device link not permitted, link '${e}' -> '${t}'`);return n.fs.link(n.relativePath,r.relativePath)}async readlink(e){let{fs:t,relativePath:n}=this.routePath(e);return t.readlink(n)}async realpath(e){let t=cH(e);if(this.mounts.get(t))return t;let{fs:n,relativePath:r}=this.routePath(e),i=await n.realpath(r);for(let[e,n]of this.mounts)if(t===e||t.startsWith(`${e}/`))return i===`/`?e:`${e}${i}`;return i}async crossMountCopy(e,t,n){let r=await this.lstat(e);if(r.isFile){let n=await this.readFileBuffer(e);await this.writeFile(t,n),await this.chmod(t,r.mode)}else if(r.isDirectory){if(!n?.recursive)throw Error(`cp: ${e} is a directory (not copied)`);await this.mkdir(t,{recursive:!0});let r=await this.readdir(e);for(let i of r){let r=pH(e,i),a=pH(t,i);await this.crossMountCopy(r,a,n)}}else if(r.isSymbolicLink){let n=await this.readlink(e);await this.symlink(n,t)}}async utimes(e,t,n){let{fs:r,relativePath:i}=this.routePath(e);return r.utimes(i,t,n)}};U();var c8=`/dev/fd`,l8=63,u8=l8-10+1,dje=class extends q2{isLiveDescriptor;constructor(e){super(),this.isLiveDescriptor=e}assertLiveDescriptor(e,t){this.isLiveDescriptor(e)||this.refuse(e,t)}refuse(e,t){throw Error(`EROFS: read-only file system, ${t} '${c8}${e}'`)}async writeFile(e,t,n){return this.assertLiveDescriptor(e,`write`),super.writeFile(e,t,n)}async appendFile(e,t,n){return this.assertLiveDescriptor(e,`append`),super.appendFile(e,t,n)}async rm(e,t){return this.assertLiveDescriptor(e,`rm`),super.rm(e,t)}async mkdir(e,t){this.refuse(e,`mkdir`)}async cp(e,t){this.refuse(t,`cp`)}async mv(e,t){this.refuse(t,`mv`)}async symlink(e,t){this.refuse(t,`symlink`)}async link(e,t){this.refuse(t,`link`)}async chmod(e,t){this.refuse(e,`chmod`)}async utimes(e,t,n){this.refuse(e,`utimes`)}};function fje(e){let t=new dje(t=>d8(e).some(e=>e.path===`${c8}${t}`));e.fs=new uje({base:e.fs,mounts:[{mountPoint:c8,filesystem:t}]}),e.state.processSubstitutionFsMounted=!0}async function pje(e,t,n){try{await e.fs.writeFile(t,n,`binary`);return}catch(t){if(e.state.processSubstitutionFsMounted)throw t;fje(e)}await e.fs.writeFile(t,n,`binary`)}async function mje(e,t){try{await e.fs.rm(t,{force:!0})}catch{}}function d8(e){let t=e.state.processSubstitutions;if(t)return t;let n=[];return e.state.processSubstitutions=n,n}async function f8(e,t,n){let r=e.substitutionDepth??0,i=e.limits.maxSubstitutionDepth;if(r>=i)throw new H(`Process substitution nesting limit exceeded (${i})`,`substitution_depth`);let a=e.substitutionDepth,o=new Map(e.state.env),s=X2(e.state.arrays),c=e.state.cwd,l=e.state.bashPid,u=e.state.suppressVerbose,d=e.state.groupStdin,f=e.state.lastExitCode,p=e.state.env.get(`?`);e.substitutionDepth=r+1,e.state.bashPid=e.state.nextVirtualPid++,e.state.suppressVerbose=!0,n!==void 0&&(e.state.groupStdin=n);let m;try{m=await e.executeScript(t)}catch(e){if(e instanceof H)throw e;if(e instanceof LB)return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode};throw e}finally{e.substitutionDepth=a,e.state.env=o,e.state.arrays=s,e.state.cwd=c,e.state.bashPid=l,e.state.suppressVerbose=u,e.state.groupStdin=d,e.state.lastExitCode=f,p===void 0?e.state.env.delete(`?`):e.state.env.set(`?`,p)}return m}async function hje(e,t){let n=d8(e);if(n.length>=u8)throw new H(`Process substitution limit exceeded (${u8} concurrent)`,`file_descriptors`);let r=``;if(t.direction===`input`){let n=await f8(e,t.body,void 0);if(n.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||``)+n.stderr),r=CB(n),r.length>e.limits.maxStringLength)throw new H(`process substitution: string length limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`)}let i=l8-n.length,a=`${c8}/${i}`;n.push({fd:i,path:a,direction:t.direction,body:t.body});try{await pje(e,a,r)}catch(e){throw n.pop(),e}return a}function gje(e){return e.state.processSubstitutions?.length??0}var _je={stdout:``,stderr:``};async function p8(e,t){let n=e.state.processSubstitutions;if(!n||n.length<=t)return _je;let r=``,i=``;for(;n.length>t;){let t=n[n.length-1],a=``;if(t.direction===`output`)try{a=await xB(e.fs,t.path)}catch{}if(await mje(e,t.path),n.pop(),t.direction===`output`){let n=await f8(e,t.body,a);r+=CB(n),i+=n.stderr}}return{stdout:r,stderr:i}}function m8(e,t,n){if(e.length>t)throw new H(`${n}: string length limit exceeded (${t} bytes)`,`string_length`)}async function h8(e,t,n=!1){let r=[];for(let i of t)r.push(await T8(e,i,n));return r.join(``)}function vje(e){return lje(e)}function yje(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!vje(t))return!1;return!0}function bje(e,t,n=!1){let r=cje(t);if(r!==null)return r;switch(t.type){case`TildeExpansion`:return n?t.user===null?`~`:`~${t.user}`:(e.coverage?.hit(`bash:expansion:tilde`),t.user===null?e.state.env.get(`HOME`)??`/home/user`:t.user===`root`?`/root`:`~${t.user}`);case`Glob`:return K6(e,t.pattern);default:return null}}async function g8(e,t){return w8(e,t)}async function xje(e,t){let n=[];for(let r of t.parts)if(r.type===`Escaped`)n.push(k6(r.value));else if(r.type===`SingleQuoted`)n.push(r.value);else if(r.type===`DoubleQuoted`){let t=await h8(e,r.parts);n.push(t)}else if(r.type===`TildeExpansion`){let t=await T8(e,r);n.push(k6(t))}else n.push(await T8(e,r));return n.join(``)}async function Sje(e,t){let n=[];for(let r of t.parts)if(r.type===`Escaped`){let e=r.value;`()|*?[]`.includes(e)?n.push(`\\${e}`):n.push(e)}else if(r.type===`SingleQuoted`)n.push(O6(r.value));else if(r.type===`DoubleQuoted`){let t=await h8(e,r.parts);n.push(O6(t))}else n.push(await T8(e,r));return n.join(``)}async function _8(e,t){let n=[];for(let r of t.parts)if(r.type===`SingleQuoted`)n.push(O6(r.value));else if(r.type===`Escaped`){let e=r.value;`*?[]\\()|`.includes(e)?n.push(`\\${e}`):n.push(e)}else if(r.type===`DoubleQuoted`){let t=await h8(e,r.parts);n.push(O6(t))}else r.type===`Glob`?hAe(r.pattern)?n.push(await _Ae(e,r.pattern)):n.push(K6(e,r.pattern)):r.type===`Literal`?n.push(r.value):n.push(await T8(e,r));return n.join(``)}function v8(e){for(let t of e)if(t.type===`BraceExpansion`||t.type===`DoubleQuoted`&&v8(t.parts))return!0;return!1}var y8=1e5;async function b8(e,t,n={count:0}){let r=()=>{n.count++,e.executionScope.consumeLimited(`brace_operations`,1,Math.min(y8,e.limits.maxBraceExpansionResults),`brace expansion`)},i=(t,n)=>{if(t.length>=e.limits.maxBraceExpansionResults)throw new H(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,`array_elements`);r(),t.push(n)},a=[[]];for(let o of t)if(o.type===`BraceExpansion`){let t=[],s=!1,c=``;for(let r of o.items)if(r.type===`Range`){let n=T6(r.start,r.end,r.step,r.startStr,r.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(n.expanded)for(let e of n.expanded)i(t,e);else{s=!0,c=n.literal;break}}else{let a=await b8(e,r.word.parts,n);for(let n of a){let r=[];for(let t of n)typeof t==`string`?r.push(t):r.push(await T8(e,t));i(t,r.join(``))}}if(s){for(let e of a)r(),e.push(c);continue}if(a.length*t.length>e.limits.maxBraceExpansionResults||n.count>y8)throw new H(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,`array_elements`);let l=[];for(let n of a)for(let i of t){if(l.length>=e.limits.maxBraceExpansionResults)throw new H(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,`array_elements`);r(),l.push([...n,i])}a=l}else for(let e of a)r(),e.push(o);return a}async function x8(e,t){let n=t.parts;if(!v8(n))return[await g8(e,t)];let r=await b8(e,n),i=[];for(let t of r){let n=[];for(let r of t)typeof r==`string`?n.push(r):n.push(await T8(e,r));i.push(q6(e,n.join(``)))}return i}function Cje(){return{expandWordAsync:w8,expandWordForGlobbing:_8,expandWordWithBracesAsync:x8,expandWordPartsAsync:h8,expandPart:T8,expandParameterAsync:E8,hasBraceExpansion:v8,evaluateArithmetic:M8,buildIfsCharClassPattern:Lke,smartWordSplit:oje}}async function S8(e,t){return JAe(e,t,Cje())}function wje(e){for(let t of e){if(t.type===`ParameterExpansion`)return t.parameter;if(t.type===`Literal`)return t.value}return``}function C8(e,t){if(Number.parseInt(e.state.env.get(`#`)||`0`,10)<2)return!1;function n(e){for(let t of e)if(t.type===`DoubleQuoted`){for(let e of t.parts)if(e.type===`ParameterExpansion`&&e.parameter===`@`&&!e.operation)return!0}return!1}return n(t.parts)}async function Tje(e,t){if(C8(e,t))return{error:`bash: $@: ambiguous redirect +`};let n=t.parts,{hasQuoted:r}=Z3(n);if(v8(n)&&(await x8(e,t)).length>1)return{error:`bash: ${n.map(e=>e.type===`Literal`?e.value:e.type===`BraceExpansion`?`{${e.items.map(e=>{if(e.type===`Range`){let t=e.step?`..${e.step}`:``;return`${e.startStr??e.start}..${e.endStr??e.end}${t}`}return e.word.parts.map(e=>e.type===`Literal`?e.value:``).join(``)}).join(`,`)}}`:``).join(``)}: ambiguous redirect +`};let i=await w8(e,t),{hasParamExpansion:a,hasCommandSub:o}=Z3(n);if((a||o)&&!r&&!t6(e.state.env)&&s6(i,e6(e.state.env),e.limits.maxArrayElements).length>1)return{error:`bash: $${wje(n)}: ambiguous redirect +`};if(r||e.state.options.noglob||n.some(e=>e.type===`ProcessSubstitution`))return{target:i};let s=await _8(e,t);if(!E6(s,e.state.shoptOptions.extglob))return{target:i};let c=new Y3(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited(`glob_operations`,1,e.limits.maxGlobOperations,`glob expansion`)}),l=await c.expand(s);return l.length===0?c.hasFailglob()?{error:`bash: no match: ${i} +`}:{target:i}:l.length===1?{target:l[0]}:{error:`bash: ${i}: ambiguous redirect +`}}async function w8(e,t){let n=t.parts,r=n.length;if(r===1){let t=await T8(e,n[0]);return m8(t,e.limits.maxStringLength,`word expansion`),t}let i=[];for(let t=0;t=i)throw new H(`Command substitution nesting limit exceeded (${i})`,`substitution_depth`);let a=e.substitutionDepth;e.substitutionDepth=r+1;let o=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let s=new Map(e.state.env),c=X2(e.state.arrays),l=e.state.cwd,u=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let n=await e.executeScript(t.body),r=n.exitCode;e.state.env=s,e.state.arrays=c,e.state.cwd=l,e.state.suppressVerbose=u,e.state.lastExitCode=r,e.state.env.set(`?`,String(r)),n.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||``)+n.stderr),e.state.bashPid=o,e.substitutionDepth=a;let i=n.stdout.replace(/\n+$/,``);return m8(i,e.limits.maxStringLength,`command substitution`),i}catch(t){if(e.state.env=s,e.state.arrays=c,e.state.cwd=l,e.state.bashPid=o,e.substitutionDepth=a,e.state.suppressVerbose=u,t instanceof H)throw t;if(t instanceof LB){e.state.lastExitCode=t.exitCode,e.state.env.set(`?`,String(t.exitCode)),t.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||``)+t.stderr);let n=t.stdout.replace(/\n+$/,``);return m8(n,e.limits.maxStringLength,`command substitution`),n}throw t}}case`ProcessSubstitution`:return hje(e,t);case`ArithmeticExpansion`:{let n=t.expression.originalText;if(n&&/\$[a-zA-Z_][a-zA-Z0-9_]*(?![{[(])/.test(n)){let t=await Wke(e,n),r=N4(new w3,t);return String(await M8(e,r.expression,!0))}return String(await M8(e,t.expression.expression,!0))}case`BraceExpansion`:{let n=[];for(let r of t.items)if(r.type===`Range`){let t=T6(r.start,r.end,r.step,r.startStr,r.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(t.expanded)n.push(...t.expanded);else return t.literal}else n.push(await g8(e,r.word));return n.join(` `)}default:return``}}async function E8(e,t,n=!1){let{parameter:r}=t,{operation:i}=t,a=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let[,t,n]=a;(e.state.associativeArrays?.has(t)||n.includes(`$(`)||n.includes("`")||n.includes("${"))&&(r=`${t}[${await x6(e,n)}]`)}else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&c6(e,r)){let t=p6(e,r);if(t&&t!==r){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let[,t,i]=n;(e.state.associativeArrays?.has(t)||i.includes(`$(`)||i.includes("`")||i.includes("${"))&&(r=`${t}[${await x6(e,i)}]`)}}}let o=i&&(i.type===`DefaultValue`||i.type===`AssignDefault`||i.type===`UseAlternative`||i.type===`ErrorIfUnset`),s=await y6(e,r,!o);if(!i)return s;let c=!await b6(e,r),{isEmpty:l,effectiveValue:u}=mAe(e,r,s,n),d={value:s,isUnset:c,isEmpty:l,effectiveValue:u,inDoubleQuotes:n};switch(i.type){case`DefaultValue`:return tAe(e,i,d,h8);case`AssignDefault`:return nAe(e,r,i,d,h8);case`ErrorIfUnset`:return rAe(e,r,i,d,h8);case`UseAlternative`:return iAe(e,i,d,h8);case`PatternRemoval`:{let t=await aAe(e,s,i,h8,T8);return m8(t,e.limits.maxStringLength,`pattern removal`),t}case`PatternReplacement`:{let t=await oAe(e,s,i,h8,T8);return m8(t,e.limits.maxStringLength,`pattern replacement`),t}case`Length`:return sAe(e,r,s);case`LengthSliceError`:throw new zB(r);case`BadSubstitution`:throw new zB(i.text);case`Substring`:return cAe(e,r,s,i);case`CaseModification`:{let t=await lAe(e,s,i,h8,E8);return m8(t,e.limits.maxStringLength,`case modification`),t}case`Transform`:return uAe(e,r,s,c,i);case`Indirection`:return dAe(e,r,s,c,i,E8,n);case`ArrayKeys`:return fAe(e,i);case`VarNamePrefix`:return pAe(e,i);default:return s}}function D8(){return{visited:new Set,depth:0}}function Eje(e,t,n){switch(n){case`+`:return e+t;case`-`:return e-t;case`*`:return e*t;case`/`:if(t===0)throw new RB(`division by 0`);return Math.trunc(e/t);case`%`:if(t===0)throw new RB(`division by 0`);return e%t;case`**`:if(t<0)throw new RB(`exponent less than 0`);return e**t;case`<<`:return e<>`:return e>>t;case`<`:return+(e`:return+(e>t);case`>=`:return+(e>=t);case`==`:return+(e===t);case`!=`:return e===t?0:1;case`&`:return e&t;case`|`:return e|t;case`^`:return e^t;case`,`:return t;default:return 0}}function O8(e,t,n){switch(n){case`=`:return t;case`+=`:return e+t;case`-=`:return e-t;case`*=`:return e*t;case`/=`:return t===0?0:Math.trunc(e/t);case`%=`:return t===0?0:e%t;case`<<=`:return e<>=`:return e>>t;case`&=`:return e&t;case`|=`:return e|t;case`^=`:return e^t;default:return t}}function Dje(e,t){switch(t){case`-`:return-e;case`+`:return+e;case`!`:return+(e===0);case`~`:return~e;default:return e}}async function Oje(e,t){let n=e.state.env.get(t);if(n!==void 0)return n;let r=t4(e,t,0);return r===void 0?await y6(e,t):r}async function kje(e,t,n){if(!t)return 0;let r=Number.parseInt(t,10);if(!Number.isNaN(r)&&/^-?\d+$/.test(t.trim()))return r;let i=t.trim();if(!i)return 0;let{expr:a,pos:o}=I4(new w3,i,0);if(o100)throw new RB(`maximum variable indirection depth exceeded`);if(r.visited.has(t))throw new RB(`arithmetic variable cycle detected at ${t}`);r.visited.add(t),r.depth++;try{return await kje(e,n,r)}finally{r.depth--,r.visited.delete(t)}}async function A8(e,t,n){if(n.depth>100)throw new RB(`maximum variable indirection depth exceeded`);if(n.visited.has(t))throw new RB(`arithmetic variable cycle detected at ${t}`);n.visited.add(t),n.depth++;try{let r=await Oje(e,t);if(!r)return 0;let i=Number.parseInt(r,10);if(!Number.isNaN(i)&&/^-?\d+$/.test(r.trim()))return i;let a=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))return await A8(e,a,n);let{expr:o,pos:s}=I4(new w3,a,0);if(s0&&(r===-1||nN8(e,t,i,r);switch(t.type){case`ArithNumber`:if(Number.isNaN(t.value))throw new RB(`value too great for base`);return t.value;case`ArithVariable`:return await A8(e,t.name,r);case`ArithSpecialVar`:{let n=(await y6(e,t.name)).trim();if(!n)return 0;let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&/^-?\d+$/.test(n))return r;let{expr:a}=I4(new w3,n,0);return await i(a)}case`ArithNested`:return await i(t.expression);case`ArithCommandSubst`:if(e.execFn){let n=await e.execFn(t.command,{signal:e.state.signal});n.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||``)+n.stderr);let r=n.stdout.trim();return Number.parseInt(r,10)||0}return 0;case`ArithBracedExpansion`:{let n=await j8(e,t.content);return Number.parseInt(n,10)||0}case`ArithDynamicBase`:{let n=await j8(e,t.baseExpr),r=Number.parseInt(n,10);return r<2||r>64?0:M4(`${r}#${t.value}`)}case`ArithDynamicNumber`:return M4(await j8(e,t.prefix)+t.suffix);case`ArithArrayElement`:{let n=e.state.associativeArrays?.has(t.array),a=async n=>{let i=t4(e,t.array,n);return i===void 0?0:await k8(e,`${t.array}[${n}]`,i,r)};if(t.stringKey!==void 0)return await a(t.stringKey);if(n&&t.index?.type===`ArithVariable`&&!t.index.hasDollarPrefix)return await a(t.index.name);if(n&&t.index?.type===`ArithVariable`&&t.index.hasDollarPrefix)return await a(await y6(e,t.index.name));if(t.index){let n=await i(t.index);if(n<0){let r=_6(e,t.array),i=e.state.currentLine;if(r.length===0)return e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${i}: ${t.array}: bad array subscript +`,0;let a=Math.max(...r.map(([e])=>typeof e==`number`?e:0))+1+n;if(a<0)return e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${i}: ${t.array}: bad array subscript +`,0;n=a}let a=`${t.array}[${n}]`,o=t4(e,t.array,n);if(o!==void 0)return k8(e,a,o,r);if(n===0){let n=e.state.env.get(t.array);if(n!==void 0)return k8(e,t.array,n,r)}if(e.state.options.nounset&&!(e.state.env.has(t.array)||e4(e,t.array)))throw new IB(`${t.array}[${n}]`);return 0}return 0}case`ArithDoubleSubscript`:throw new RB(`double subscript`,``,``);case`ArithNumberSubscript`:throw new RB(`${t.number}${t.errorToken}: syntax error: invalid arithmetic operator (error token is "${t.errorToken}")`);case`ArithSyntaxError`:throw new RB(t.message,``,``,!0);case`ArithSingleQuote`:if(n)throw new RB(`syntax error: operand expected (error token is "'${t.content}'")`);return t.value;case`ArithBinary`:return t.operator===`||`?await i(t.left)||await i(t.right)?1:0:t.operator===`&&`?await i(t.left)&&await i(t.right)?1:0:Eje(await i(t.left),await i(t.right),t.operator);case`ArithUnary`:{let a=await i(t.operand);if(t.operator===`++`||t.operator===`--`){if(t.operand.type===`ArithVariable`){let n=t.operand.name,r=Number.parseInt(await y6(e,n),10)||0,i=t.operator===`++`?r+1:r-1;return e.state.env.set(n,String(i)),t.prefix?i:r}if(t.operand.type===`ArithArrayElement`){let n=t.operand.array,r=e.state.associativeArrays?.has(n),o;if(t.operand.stringKey!==void 0)o=t.operand.stringKey;else if(r&&t.operand.index?.type===`ArithVariable`&&!t.operand.index.hasDollarPrefix)o=t.operand.index.name;else if(r&&t.operand.index?.type===`ArithVariable`&&t.operand.index.hasDollarPrefix)o=await y6(e,t.operand.index.name);else if(t.operand.index){let e=await i(t.operand.index);o=String(e)}else return a;let s=Number.parseInt(t4(e,n,o)||`0`,10)||0,c=t.operator===`++`?s+1:s-1;return r4(e,n,o,String(c),r?`associative`:`indexed`),t.prefix?c:s}if(t.operand.type===`ArithConcat`){let i=``;for(let a of t.operand.parts)i+=await P8(e,a,n,r);if(i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)){let n=Number.parseInt(e.state.env.get(i)||`0`,10)||0,r=t.operator===`++`?n+1:n-1;return e.state.env.set(i,String(r)),t.prefix?r:n}}if(t.operand.type===`ArithDynamicElement`){let a=``;if(t.operand.nameExpr.type===`ArithConcat`)for(let i of t.operand.nameExpr.parts)a+=await P8(e,i,n,r);else t.operand.nameExpr.type===`ArithVariable`&&(a=t.operand.nameExpr.hasDollarPrefix?await y6(e,t.operand.nameExpr.name):t.operand.nameExpr.name);if(a&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){let n=await i(t.operand.subscript),r=Number.parseInt(t4(e,a,n)||`0`,10)||0,o=t.operator===`++`?r+1:r-1;return r4(e,a,n,String(o)),t.prefix?o:r}}return a}return Dje(a,t.operator)}case`ArithTernary`:return await i(t.condition)?await i(t.consequent):await i(t.alternate);case`ArithAssignment`:{let n=t.variable,r=n,a;if(t.stringKey!==void 0)a=t.stringKey;else if(t.subscript){let r=e.state.associativeArrays?.has(n);if(r&&t.subscript.type===`ArithVariable`&&!t.subscript.hasDollarPrefix)a=t.subscript.name;else if(r&&t.subscript.type===`ArithVariable`&&t.subscript.hasDollarPrefix)a=await y6(e,t.subscript.name)||`\\`;else if(r){let e=await i(t.subscript);a=String(e)}else{let r=await i(t.subscript);if(r<0){let t=_6(e,n);t.length>0&&(r=Math.max(...t.map(([e])=>typeof e==`number`?e:0))+1+r)}a=String(r)}}let o=a===void 0?e.state.env.get(r):t4(e,n,a),s=O8(Number.parseInt(o||`0`,10)||0,await i(t.value),t.operator);return a===void 0?e.state.env.set(r,String(s)):r4(e,n,a,String(s),e.state.associativeArrays?.has(n)?`associative`:`indexed`),s}case`ArithGroup`:return await i(t.expression);case`ArithConcat`:{let i=``;for(let a of t.parts)i+=await P8(e,a,n,r);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)?await A8(e,i,r):Number.parseInt(i,10)||0}case`ArithDynamicAssignment`:{let a=``;if(t.target.type===`ArithConcat`)for(let i of t.target.parts)a+=await P8(e,i,n,r);else t.target.type===`ArithVariable`&&(a=t.target.hasDollarPrefix?await y6(e,t.target.name):t.target.name);if(!a||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))return 0;let o=a;if(t.subscript){let e=await i(t.subscript);o=`${a}_${e}`}let s=O8(Number.parseInt(e.state.env.get(o)||`0`,10)||0,await i(t.value),t.operator);return e.state.env.set(o,String(s)),s}case`ArithDynamicElement`:{let a=``;if(t.nameExpr.type===`ArithConcat`)for(let i of t.nameExpr.parts)a+=await P8(e,i,n,r);else t.nameExpr.type===`ArithVariable`&&(a=t.nameExpr.hasDollarPrefix?await y6(e,t.nameExpr.name):t.nameExpr.name);if(!a||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))return 0;let o=await i(t.subscript),s=`${a}_${o}`,c=e.state.env.get(s);return c===void 0?0:k8(e,s,c,r)}default:return 0}}async function P8(e,t,n=!1,r=D8()){switch(t.type){case`ArithNumber`:return String(t.value);case`ArithSingleQuote`:return String(await N8(e,t,n,r));case`ArithVariable`:return t.hasDollarPrefix?await y6(e,t.name):t.name;case`ArithSpecialVar`:return await y6(e,t.name);case`ArithBracedExpansion`:return await j8(e,t.content);case`ArithCommandSubst`:return e.execFn?(await e.execFn(t.command,{signal:e.state.signal})).stdout.trim():`0`;case`ArithConcat`:{let i=``;for(let a of t.parts)i+=await P8(e,a,n,r);return i}default:return String(await N8(e,t,n,r))}}XB(),U();async function Aje(e,t){let n=``,r=0;for(let i of t.parts){let t=i.type===`Literal`?i.value:`\0`,a=V(t);if(a>e.limits.maxStringLength-r)throw new H(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);n+=t,r+=a}let i=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!i||!n.endsWith(`)`))return null;let a=i[1],o=[],s=[],c=!1,l=``,u=0,d=0,f=!1,p=!0,m=t=>{let n=V(t);if(n>e.limits.maxStringLength-d-u)throw new H(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);l+=t,u+=n},h=(t,n=!1)=>{if(o.length>=e.limits.maxArrayElements)throw new H(`array assignment element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);let r=V(t);if(r>e.limits.maxStringLength-d)throw new H(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);o.push(t),s.push(n),d+=r},g=()=>{h(l,p),l=``,u=0,f=!1,p=!0};for(let n of t.parts)if(n.type===`Literal`){let e=n.value;if(!c){let t=e.indexOf(`=(`);t!==-1&&(c=!0,e=e.slice(t+2))}if(c){e.endsWith(`)`)&&(e=e.slice(0,-1));for(let t of e)/\s/.test(t)?(l||f)&&g():m(t)}}else if(c){if(n.type===`BraceExpansion`){if(/^\[.+\]=/.test(l))m(f4({type:`Word`,parts:[n]}));else{(l||f)&&g();let t=await S8(e,{type:`Word`,parts:[n]});for(let e of t.values)h(e)}}else(n.type===`SingleQuoted`||n.type===`DoubleQuoted`||n.type===`Escaped`)&&(f=!0),p=!1,m(await g8(e,{type:`Word`,parts:[n]}))}(l||f)&&g();let _=o.splice(0),v=s.splice(0);d=0;for(let t=0;t<_.length;t++){let n=_[t];if(!v[t]){h(n);continue}let r=n.match(/^(\[[^\]]+\]=)(.*)$/s);if(r){let t=J6(e,r[2]);n=r[1]+t}if(n.includes(`{`)&&n.includes(`}`)){let t=new w3().parseWordFromString(n,!1,!1);if(t.parts.some(e=>e.type===`BraceExpansion`)){let n=await S8(e,t);for(let e of n.values)h(e);continue}}h(n)}let y=[`${a}=(`],b=V(y[0]);for(let t=0;t()]/.test(n)&&!n.startsWith(`'`)&&!n.startsWith(`"`)?`'${n.replace(/'/g,`'\\''`)}'`:n;let i=`${t>0?` `:``}${r}`,a=V(i);if(a+1>e.limits.maxStringLength-b)throw new H(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);y.push(i),b+=a}return y.push(`)`),y.join(``)}async function jje(e,t){let n=-1,r=-1,i=!1;for(let e=0;e0?await g8(e,f):``;return`${d}${i?`+=`:`=`}${p}`}var Mje=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function Nje(e){return Mje.includes(e)}kB(),vH(),AK(),aB(),m$(),mB(),U(),U();var F8=Object.freeze({stdout:``,stderr:``,exitCode:0,internalStdinConsumed:0});function I8(e=``){return{stdout:e,stderr:``,exitCode:0}}function Q(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function $(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function L8(e){return{stdout:``,stderr:``,exitCode:+!e,internalStdinConsumed:0}}function R8(e,t,n=``,r=``){throw new H(e,t,n,r)}function Pje(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new H(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function Fje(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new UB;return F8}if(t.length>1)throw new LB(1,``,`bash: break: too many arguments +`);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new LB(128,``,`bash: break: ${t[0]}: numeric argument required +`);n=e}throw new MB(n)}async function Ije(e,t){let n,r=!1,i=!1,a=0;for(;ae);for(let t of i){let i=t.startsWith(`/`)?`${t}/${n}`:`${e.state.cwd}/${t}/${n}`;try{if((await e.fs.stat(i)).isDirectory){n=i,r=!0;break}}catch{}}}}let s=(n.startsWith(`/`)?n:`${e.state.cwd}/${n}`).split(`/`).filter(e=>e&&e!==`.`),c=``;for(let t of s)if(t===`..`)c=c.split(`/`).slice(0,-1).join(`/`)||`/`;else{c=c?`${c}/${t}`:`/${t}`;try{if(!(await e.fs.stat(c)).isDirectory)return Q(`bash: cd: ${n}: Not a directory +`)}catch{return Q(`bash: cd: ${n}: No such file or directory +`)}}let l=c||`/`;if(i)try{l=await e.fs.realpath(l)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=l,e.state.env.set(`PWD`,e.state.cwd),e.state.env.set(`OLDPWD`,e.state.previousDir),I8(r?`${l} +`:``)}sH(),kB(),yG(),U();function z8(e,t){return e.fs.resolvePath(e.state.cwd,t)}var Lje=[`-e`,`-a`,`-f`,`-d`,`-r`,`-w`,`-x`,`-s`,`-L`,`-h`,`-k`,`-g`,`-u`,`-G`,`-O`,`-b`,`-c`,`-p`,`-S`,`-t`,`-N`];function B8(e){return Lje.includes(e)}async function V8(e,t,n){let r=z8(e,n);switch(t){case`-e`:case`-a`:return e.fs.exists(r);case`-f`:return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case`-d`:return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case`-r`:return await e.fs.exists(r)?!!((await e.fs.stat(r)).mode&256):!1;case`-w`:return await e.fs.exists(r)?!!((await e.fs.stat(r)).mode&128):!1;case`-x`:return await e.fs.exists(r)?!!((await e.fs.stat(r)).mode&64):!1;case`-s`:return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case`-L`:case`-h`:try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case`-k`:return await e.fs.exists(r)?!!((await e.fs.stat(r)).mode&512):!1;case`-g`:return await e.fs.exists(r)?!!((await e.fs.stat(r)).mode&1024):!1;case`-u`:return await e.fs.exists(r)?!!((await e.fs.stat(r)).mode&2048):!1;case`-G`:case`-O`:return e.fs.exists(r);case`-b`:return!1;case`-c`:return[`/dev/null`,`/dev/zero`,`/dev/random`,`/dev/urandom`,`/dev/tty`,`/dev/stdin`,`/dev/stdout`,`/dev/stderr`].includes(r);case`-p`:return!1;case`-S`:return!1;case`-t`:return!1;case`-N`:return e.fs.exists(r);default:return!1}}var Rje=[`-nt`,`-ot`,`-ef`];function H8(e){return Rje.includes(e)}async function U8(e,t,n,r){let i=z8(e,n),a=z8(e,r);switch(t){case`-nt`:{let[t,n]=await Promise.all([e.fs.stat(i).catch(()=>null),e.fs.stat(a).catch(()=>null)]);return t!==null&&(n===null||t.mtime>n.mtime)}case`-ot`:{let[t,n]=await Promise.all([e.fs.stat(i).catch(()=>null),e.fs.stat(a).catch(()=>null)]);return n!==null&&(t===null||t.mtimen;case`-ge`:return t>=n}}function K8(e){return e===`=`||e===`==`||e===`!=`}function q8(e,t,n,r=!1,i=!1,a=!1,o=256){if(r){let r=n5(t,n,i,a,o);return e===`!=`?!r:r}if(i){let r=t.toLowerCase()===n.toLowerCase();return e===`!=`?!r:r}let s=t===n;return e===`!=`?!s:s}var Bje=new Set([`-z`,`-n`]);function J8(e){return Bje.has(e)}function Y8(e,t){switch(e){case`-z`:return t===``;case`-n`:return t!==``}}async function X8(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let t=n[1],r=n[2];if(e.state.associativeArrays?.has(t)){let n=r;return(n.startsWith(`'`)&&n.endsWith(`'`)||n.startsWith(`"`)&&n.endsWith(`"`))&&(n=n.slice(1,-1)),n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n)=>e.state.env.get(n)||``),n4(e,t,n)}let i;try{i=await M8(e,N4(new w3,r).expression)}catch{if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}}if(i<0){let n=s4(e,t),r=e.state.currentLine;if(n.length===0||(i=Math.max(...n)+1+i,i<0))return e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${r}: ${t}: bad array subscript +`,!1}return n4(e,t,i)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?l4(e,t).length>0:s4(e,t).length>0}async function Z8(e,t){switch(t.type){case`CondBinary`:{let n=await g8(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(e=>e.type===`SingleQuoted`||e.type===`DoubleQuoted`||e.type===`Escaped`&&t.operator!==`=~`),i;if(i=t.operator===`=~`?r?k6(await g8(e,t.right)):await xje(e,t.right):K8(t.operator)&&!r?await Sje(e,t.right):await g8(e,t.right),K8(t.operator)){let a=e.state.shoptOptions.nocasematch;return q8(t.operator,n,i,!r,a,!0,e.limits.maxCallDepth)}if(W8(t.operator))return G8(t.operator,await c5(e,n),await c5(e,i));if(H8(t.operator))return U8(e,t.operator,n,i);switch(t.operator){case`=~`:try{let t=e.state.shoptOptions.nocasematch,r=mG(Gje(i),t?`i`:``).match(n);if(c4(e,`BASH_REMATCH`),r)for(let t=0;t`:return n>i;default:return!1}}case`CondUnary`:{let n=await g8(e,t.operand);return B8(t.operator)?V8(e,t.operator,n):J8(t.operator)?Y8(t.operator,n):t.operator===`-v`?await X8(e,n):t.operator===`-o`&&s5(e,n)}case`CondNot`:return e.state.shoptOptions.extglob&&t.operand.type===`CondGroup`&&t.operand.expression.type===`CondWord`?`!(${await g8(e,t.operand.expression.word)})`!=``:!await Z8(e,t.operand);case`CondAnd`:return await Z8(e,t.left)?await Z8(e,t.right):!1;case`CondOr`:return await Z8(e,t.left)?!0:await Z8(e,t.right);case`CondGroup`:return await Z8(e,t.expression);case`CondWord`:return await g8(e,t.word)!==``;default:return!1}}async function Q8(e,t){if(t.length===0)return $(``,``,1);if(t.length===1)return L8(!!t[0]);if(t.length===2){let n=t[0],r=t[1];return n===`(`?Q(`test: '(' without matching ')' +`,2):B8(n)?L8(await V8(e,n,r)):J8(n)?L8(Y8(n,r)):n===`!`?L8(!r):n===`-v`?L8(await X8(e,r)):n===`-o`?L8(s5(e,r)):n===`=`||n===`==`||n===`!=`||n===`<`||n===`>`||n===`-eq`||n===`-ne`||n===`-lt`||n===`-le`||n===`-gt`||n===`-ge`||n===`-nt`||n===`-ot`||n===`-ef`?Q(`test: ${n}: unary operator expected +`,2):$(``,``,1)}if(t.length===3){let n=t[0],r=t[1],i=t[2];if(K8(r))return L8(q8(r,n,i));if(W8(r)){let e=u5(n),t=u5(i);return!e.valid||!t.valid?$(``,``,2):L8(G8(r,e.value,t.value))}if(H8(r))return L8(await U8(e,r,n,i));switch(r){case`-a`:return L8(n!==``&&i!==``);case`-o`:return L8(n!==``||i!==``);case`>`:return L8(n>i);case`<`:return L8(n0&&`@*+?!`.includes(e[i-1]);if(r.push(a),a&&n++,n>t)throw new H(`extglob maximum depth (${t}) exceeded`,`recursion`)}else e[i]===`)`&&r.length>0&&r.pop()&&n--}}function r5(e,t){let n=``;for(let r=0;rr5(e,t)),c=s.length>0?s.join(`|`):`(?:)`;if(i===`@`)n+=`(?:${c})`;else if(i===`*`)n+=`(?:${c})*`;else if(i===`+`)n+=`(?:${c})+`;else if(i===`?`)n+=`(?:${c})?`;else if(i===`!`){if(ao5(e,t));if(e.every(e=>e!==null)&&e.every(t=>t===e[0])&&e[0]!==null){let t=e[0];if(t===0)n+=`(?:.+)`;else{let e=[];t>0&&e.push(`.{0,${t-1}}`),e.push(`.{${t+1},}`),e.push(`(?!(?:${c})).{${t}}`),n+=`(?:${e.join(`|`)})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`}r=a;continue}}if(i===`\\`){if(r+10;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return r;r++}return-1}function a5(e){let t=[],n=``,r=0,i=0;for(;io5(e,t));if(i.every(e=>e!==null)&&i.every(e=>e===i[0])){n+=i[0],r=a+1;continue}return null}return null}}if(i===`*`)return null;if(i===`?`){n+=1,r++;continue}if(i===`[`){let t=e.indexOf(`]`,r+1);if(t!==-1){n+=1,r=t+1;continue}n+=1,r++;continue}if(i===`\\`){n+=1,r+=2;continue}n+=1,r++}return n}function s5(e,t){let n=new Map([[`errexit`,()=>e.state.options.errexit===!0],[`nounset`,()=>e.state.options.nounset===!0],[`pipefail`,()=>e.state.options.pipefail===!0],[`xtrace`,()=>e.state.options.xtrace===!0],[`e`,()=>e.state.options.errexit===!0],[`u`,()=>e.state.options.nounset===!0],[`x`,()=>e.state.options.xtrace===!0]]).get(t);return n?n():!1}async function c5(e,t){if(t=t.trim(),t===``)return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return l5(t);try{return await M8(e,N4(new w3,t).expression)}catch{return l5(t)}}function Wje(e,t){let n=0;for(let r of e){let e;if(r>=`0`&&r<=`9`)e=r.charCodeAt(0)-48;else if(r>=`a`&&r<=`z`)e=r.charCodeAt(0)-97+10;else if(r>=`A`&&r<=`Z`)e=r.charCodeAt(0)-65+36;else if(r===`@`)e=62;else if(r===`_`)e=63;else return NaN;if(e>=t)return NaN;n=n*t+e}return n}function l5(e){if(e=e.trim(),e===``)return 0;let t=!1;e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1));let n,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let e=Number.parseInt(r[1],10);n=e>=2&&e<=64?Wje(r[2],e):0}else n=/^0[xX][0-9a-fA-F]+$/.test(e)?Number.parseInt(e,16):/^0[0-7]+$/.test(e)?Number.parseInt(e,8):Number.parseInt(e,10);return Number.isNaN(n)&&(n=0),t?-n:n}function u5(e){if(e=e.trim(),e===``)return{value:0,valid:!0};let t=!1;if(e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let n=Number.parseInt(e,10);return Number.isNaN(n)?{value:0,valid:!1}:{value:t?-n:n,valid:!0}}function Gje(e){let t=``,n=0;for(;n=n.maxElements)throw new H(`array element limit exceeded (${n.maxElements})`,`array_elements`);e.push(t)}function f5(e,t){if(t&&V(e)>t.maxStringBytes)throw new H(`array assignment string limit exceeded (${t.maxStringBytes} bytes)`,`string_length`);let n=[],r=``,i=!1,a=!1,o=!1,s=!1;for(let c of e){if(o){r+=c,o=!1,s=!0;continue}if(c===`\\`){o=!0;continue}if(c===`'`&&!a){i||(s=!0),i=!i;continue}if(c===`"`&&!i){a||(s=!0),a=!a;continue}if((c===` `||c===` `||c===` +`)&&!i&&!a){s&&=(d5(n,r,t),r=``,!1);continue}r+=c,s=!0}return s&&d5(n,r,t),n}function p5(e,t){if(t&&V(e)>t.maxStringBytes)throw new H(`array assignment string limit exceeded (${t.maxStringBytes} bytes)`,`string_length`);let n=[],r=0;for(;r=e.length)break;if(e[r]!==`[`){r++;continue}r++;let i=``;if(e[r]===`'`||e[r]===`"`){let t=e[r];for(r++;r0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(n)}}U();var v5=new Set([`:`,`.`,`break`,`continue`,`eval`,`exec`,`exit`,`export`,`readonly`,`return`,`set`,`shift`,`trap`,`unset`]);function $je(e){return v5.has(e)}var y5=new Set([`if`,`then`,`else`,`elif`,`fi`,`case`,`esac`,`for`,`select`,`while`,`until`,`do`,`done`,`in`,`function`,`{`,`}`,`time`,`[[`,`]]`,`!`]),b5=new Set(`:,true,false,cd,export,unset,exit,local,set,break,continue,return,eval,shift,getopts,compgen,complete,compopt,pushd,popd,dirs,source,.,read,mapfile,readarray,declare,typeset,readonly,let,command,shopt,exec,test,[,echo,printf,pwd,alias,unalias,type,hash,ulimit,umask,trap,times,wait,kill,jobs,fg,bg,disown,suspend,fc,history,help,enable,builtin,caller`.split(`,`));kB(),U();var x5=`__file__:`,S5=`__file_append__:`,C5=`__rw__:`,w5=`__dupout__:`,T5=`__dupin__:`,E5=3;function eMe(e){let t=e.slice(C5.length),n=t.indexOf(`:`);if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let i=n+1,a=t.slice(i,i+r),o=t.slice(i+r+1),s=o.indexOf(`:`);if(s===-1)return null;let c=Number.parseInt(o.slice(0,s),10);return Number.isNaN(c)||c<0?null:{path:a,position:c,content:o.slice(s+1)}}function D5(e,t){let n=Number.parseInt(e.slice(t.length),10);return Number.isNaN(n)?null:n}function tMe(e){if(e.startsWith(x5))return{kind:`output`,path:e.slice(x5.length),append:!1};if(e.startsWith(S5))return{kind:`output`,path:e.slice(S5.length),append:!0};if(e.startsWith(C5)){let t=eMe(e);if(t)return{kind:`readwrite`,...t}}if(e.startsWith(w5)){let t=D5(e,w5);if(t!==null)return{kind:`dup-out`,sourceFd:t}}if(e.startsWith(T5)){let t=D5(e,T5);if(t!==null)return{kind:`dup-in`,sourceFd:t}}return{kind:`input`,content:e}}function O5(e){switch(e.kind){case`input`:return e.content;case`output`:return`${e.append?S5:x5}${e.path}`;case`readwrite`:return`${C5}${e.path.length}:${e.path}:${e.position}:${e.content}`;case`dup-out`:return`${w5}${e.sourceFd}`;case`dup-in`:return`${T5}${e.sourceFd}`;case`closed`:throw Error(`Closed descriptors have no table encoding`)}}function nMe(e){return e.state.fileDescriptors??=new Map,e.state.fileDescriptors}function rMe(e,t,n){n?(e.state.inputFds??=new Set,e.state.inputFds.add(t)):e.state.inputFds?.delete(t)}function k5(e,t){return e.state.fdAliases?.get(t)}function A5(e,t){return[...k5(e,t)??[t]]}function j5(e,t){let n=k5(e,t);if(n&&(n.delete(t),e.state.fdAliases?.delete(t),n.size<2))for(let t of n)e.state.fdAliases?.delete(t)}function M5(e,t,n){if(t===n)return;e.state.fdAliases??=new Map;let r=k5(e,n)??new Set([n]);r.add(t);for(let t of r)e.state.fdAliases.set(t,r)}function N5(e,t){return e.state.fileDescriptors?.get(t)}function P5(e,t){let n=N5(e,t);if(n!==void 0)return e.state.inputFds?.has(t)?{kind:`input`,content:n}:tMe(n)}function F5(e,t){return e.state.fileDescriptors?.has(t)===!0}function I5(e,t,n,r){let i=nMe(e);i.has(t)||Pje(e),i.set(t,n),rMe(e,t,r)}function L5(e,t,n,r=!1){j5(e,t),I5(e,t,n,r)}function R5(e,t,n){L5(e,t,O5(n),n.kind===`input`)}function z5(e,t){e.state.fileDescriptors?.delete(t),e.state.inputFds?.delete(t),j5(e,t)}function B5(e,t,n){let r=N5(e,n);return r!==void 0&&(L5(e,t,r,e.state.inputFds?.has(n)===!0),M5(e,t,n),!0)}function V5(e,t,n){let r=N5(e,n);if(r===void 0)return!1;if(t===n)return!0;let i=e.state.inputFds?.has(n)===!0,a=[...k5(e,n)??[]].filter(e=>e!==n);z5(e,n),L5(e,t,r,i);let o=a.find(t=>F5(e,t));return o!==void 0&&M5(e,t,o),!0}function H5(e,t){let n=P5(e,t);if(n===void 0)return{error:`not-open`};switch(n.kind){case`input`:return{content:n.content};case`readwrite`:return{content:n.content.slice(n.position)};case`output`:case`dup-out`:return{error:`write-only`};case`dup-in`:return{error:`not-open`};case`closed`:return{error:`not-open`}}}function U5(e,t,n){let r=P5(e,t);if(r===void 0)return;let i;if(r.kind===`input`)i={kind:`input`,content:r.content.slice(n)};else if(r.kind===`readwrite`)i={...r,position:r.position+n};else return;let a=O5(i),o=i.kind===`input`;for(let n of k5(e,t)??[t])I5(e,n,a,o)}async function W5(e,t,n,r,i){if(t.kind===`output`)return await e.fs.appendFile(t.path,r,i),!0;let a=n.map(t=>P5(e,t)).find(e=>e?.kind===`readwrite`)??t;if(a.kind!==`readwrite`)return!1;let o=a.content.slice(0,a.position)+r+a.content.slice(a.position+r.length),s={...a,position:a.position+r.length,content:o};await e.fs.writeFile(a.path,o,i);let c=O5(s);for(let t of n)F5(e,t)&&I5(e,t,c,!1);return!0}function G5(e,t,n){if(t.has(n))return;let r=k5(e,n);t.set(n,{raw:N5(e,n),isInput:e.state.inputFds?.has(n)===!0,aliases:r?[...r].filter(e=>e!==n):[]})}function K5(e,t){let n=e.state.fileDescriptors;if(n)for(let[r,{raw:i,isInput:a,aliases:o}]of t){if(i===void 0){z5(e,r);continue}L5(e,r,i,a);let t=o.find(e=>n.has(e));t!==void 0&&M5(e,r,t)}}function q5(e){switch(e.operator){case`<`:case`<>`:case`<<`:case`<<-`:case`<<<`:case`<&`:return e.fd??0;case`>`:case`>>`:case`>|`:case`>&`:return e.fd??1;default:return null}}function iMe(e){if(e.fdVariable)return!1;let t=q5(e);return t!==null&&t>=E5}async function aMe(e,t,n,r){try{if(!await e.fs.exists(t))return null;if((await e.fs.stat(t)).isDirectory)return`bash: ${n}: Is a directory +`;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&n!==`/dev/null`)return`bash: ${n}: cannot overwrite existing file +`}catch{return`bash: ${n}: cannot open redirect target +`}return null}function J5(e){let t=Math.min(e.length,8192);for(let n=0;n127)return`utf8`;return`binary`}var Y5=`scoped`,oMe=`bare`,sMe=`persistent`,cMe=e=>new H(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`),lMe=(e,t)=>F5(e,t)||(e.state.fileDescriptors?.size??0){let t=Math.max(e.state.nextFd??10,10);for(;F5(e,t);)t+=1;return t},Z5=e=>{let t=e.endsWith(`-`),n=t?e.slice(0,-1):e;return/^\d+$/.test(n)?{sourceFd:Number.parseInt(n,10),move:t}:null},uMe=(e,t,n)=>{let r=P5(e,t);return t{let n=await g8(e,t.content);return t.stripTabs?n.split(` +`).map(e=>e.replace(/^\t+/,``)).join(` +`):n};async function fMe(e,t,n,r){let i=new Map,a=new Map,o=(t,n)=>e.state.closedStandardFds?.has(t)?{kind:`closed`}:P5(e,t)??n,s=new Map([[0,o(0,{kind:`dup-in`,sourceFd:0})],[1,o(1,{kind:`dup-out`,sourceFd:1})],[2,o(2,{kind:`dup-out`,sourceFd:2})]]),c=r.numericSnapshot,l,u=-1,d=s.get(0);d?.kind===`input`?(l=d.content,u=0):d?.kind===`readwrite`&&(l=d.content.slice(d.position),u=0);let f=()=>({targets:i,dupSources:a,standardRoutes:s,stdin:l,stdinSourceFd:u,error:null}),p=async(n,r,o)=>{let c={...f(),error:await i7(e,n,t.slice(0,r),i,a,s)};return o?{...c,errorCause:o}:c},m=async(t,n)=>{if(lMe(e,t))return null;let r=cMe(e);return p($(``,r.stderr,H.EXIT_CODE),n,r)},h=(t,n)=>{t!==null&&t{s.set(t,n),G5(e,r.standardSnapshot,t),r.standardClosedSnapshot.has(t)||r.standardClosedSnapshot.set(t,e.state.closedStandardFds?.has(t)===!0),e.state.closedStandardFds?.delete(t),R5(e,t,n)},_=(t,n)=>{if(t=E5){let n=await m(f,o);if(n)return n;G5(e,c,f),R5(e,f,{kind:`input`,content:t})}else if(f===0||f===null)l=yB(t),u=-1,h(f,{kind:`input`,content:l});else{let e={kind:`input`,content:t};r.policy===`persistent`?h(f,e):g(f,e)}continue}let v,y=d.operator===`>&`||d.operator===`<&`;if(y){if(C8(e,d.target))return p($(``,`bash: $@: ambiguous redirect +`,1),o);v=await g8(e,d.target)}else if(d.operator===`<<<`)v=await g8(e,d.target);else{let t=await Tje(e,d.target);if(`error`in t)return p($(``,t.error,1),o);v=t.target}if(i.set(o,v),v.includes(`\0`))return p($(``,`bash: ${v.replace(/\0/g,``)}: No such file or directory +`,1),o);if(d.fdVariable){try{B6(e,d.fdVariable)}catch(e){if(!(e instanceof LB))throw e;return p($(e.stdout,e.stderr,e.exitCode),o,e)}if(y&&v===`-`){let t=Number.parseInt(e.state.env.get(d.fdVariable)??``,10);Number.isNaN(t)||(G5(e,r.fdVariableSnapshot,t),z5(e,t));continue}let t=X5(e),n=y?Z5(v):null;if(n&&!_(n.sourceFd,d.operator===`<&`))return p($(``,`bash: ${n.sourceFd}: Bad file descriptor +`,1),o);if(!(n?.move===!0&&n.sourceFd>=E5)){let e=await m(t,o);if(e)return e}G5(e,r.fdVariableSnapshot,t),r.fdVariableEnv.has(d.fdVariable)||r.fdVariableEnv.set(d.fdVariable,e.state.env.get(d.fdVariable));let i,a;if(y){let t=n;if(t){let e=_(t.sourceFd,d.operator===`<&`);if(!e)return p($(``,`bash: ${t.sourceFd}: Bad file descriptor +`,1),o);a=t,e.kind===`standard`?i={kind:d.operator===`<&`?`dup-in`:`dup-out`,sourceFd:e.fd}:t.sourceFd`||d.operator===`>|`||d.operator===`>>`||d.operator===`&>`||d.operator===`&>>`){let t=d.operator===`>>`||d.operator===`&>>`,n=await Q5(e,v,t,d.operator===`>|`);if(n.error)return p(n.error,o);i=n.entry}else if(d.operator===`<<<`)i={kind:`input`,content:`${v} +`};else if(d.operator===`<`||d.operator===`<>`){let t=await $5(e,v,d.operator===`<>`);if(t.error)return p(t.error,o);i=t.entry}if(a&&a.sourceFd>=E5){if(!(a.move?V5(e,t,a.sourceFd):B5(e,t,a.sourceFd)))return p($(``,`bash: ${a.sourceFd}: Bad file descriptor +`,1),o)}else i&&R5(e,t,i);a?.move&&a.sourceFd!==t&&a.sourceFd=E5)){let e=await m(t,o);if(e)return e}if(G5(e,c,t),y){let r=n;if(!r){if(d.operator===`<&`)return p($(``,`bash: ${v}: ambiguous redirect +`,1),o);let n=await Q5(e,v,!1,!1);if(n.error)return p(n.error,o);R5(e,t,n.entry);continue}let i=_(r.sourceFd,d.operator===`<&`);if(!i)return p($(``,`bash: ${r.sourceFd}: Bad file descriptor +`,1),o);if(i.kind===`standard`)R5(e,t,{kind:d.operator===`<&`?`dup-in`:`dup-out`,sourceFd:i.fd});else if(r.sourceFd`||d.operator===`>|`||d.operator===`>>`){let n=await Q5(e,v,d.operator===`>>`,d.operator===`>|`);if(n.error)return p(n.error,o);R5(e,t,n.entry)}else if(d.operator===`<<<`)R5(e,t,{kind:`input`,content:`${v} +`});else if(d.operator===`<`||d.operator===`<>`){let n=await $5(e,v,d.operator===`<>`);if(n.error)return p(n.error,o);R5(e,t,n.entry)}continue}if(y){if(v===`-`){f===0&&(l=``,u=-1),f!==null&&f=E5){if(!B5(e,f,t.sourceFd))return p($(``,`bash: ${t.sourceFd}: Bad file descriptor +`,1),o);s.set(f,P5(e,f)),e.state.closedStandardFds?.delete(f)}else i.kind===`standard`?h(f,{kind:d.operator===`<&`?`dup-in`:`dup-out`,sourceFd:i.fd}):h(f,i.entry);if(d.operator===`<&`&&f===0){if(i.kind===`standard`)l=i.fd===0?n:``,u=-1;else if(i.entry.kind===`input`||i.entry.kind===`readwrite`){let n=t.sourceFd=E5?z5(e,t.sourceFd):(s.set(t.sourceFd,{kind:`closed`}),r.policy===`persistent`&&(z5(e,t.sourceFd),e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(t.sourceFd))));continue}if(d.operator===`>`||d.operator===`>|`||d.operator===`>>`||d.operator===`&>`||d.operator===`&>>`){let t=await Q5(e,v,d.operator===`>>`||d.operator===`&>>`,d.operator===`>|`,!1);if(t.error)return p(t.error,o);let n=t.entry;d.operator===`&>`||d.operator===`&>>`?(h(1,n),h(2,n)):h(f,n);continue}if(d.operator===`<<<`)l=yB(`${v} +`),u=-1,h(f,{kind:`input`,content:l});else if(d.operator===`<`){let t=e.fs.resolvePath(e.state.cwd,v);try{l=await xB(e.fs,t),u=-1,h(f,{kind:`input`,content:l})}catch{return p($(``,`bash: ${v}: No such file or directory +`,1),o)}}else if(d.operator===`<>`){let t=await $5(e,v,!0);if(t.error)return p(t.error,o);let n=t.entry;h(f,n),f===0&&n.kind===`readwrite`&&(l=n.content,u=-1)}}return f()}function e7(e,t,n){let r={numericSnapshot:new Map,fdVariableSnapshot:new Map,standardSnapshot:new Map,standardClosedSnapshot:new Map,fdVariableEnv:new Map,nextFd:e.state.nextFd,policy:n},i=!1;return{prepare:(n=``)=>fMe(e,t,n,r),finish:()=>{if(!i){if(i=!0,n!==`persistent`&&K5(e,r.numericSnapshot),n!==`persistent`){K5(e,r.standardSnapshot);for(let[t,n]of r.standardClosedSnapshot)n?(e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(t)):e.state.closedStandardFds?.delete(t)}if(n===`bare`){K5(e,r.fdVariableSnapshot);for(let[t,n]of r.fdVariableEnv)n===void 0?e.state.env.delete(t):e.state.env.set(t,n);e.state.nextFd=r.nextFd}}}}}function t7(e){if(!e.error)throw Error(`Expected a redirection error`);if(e.errorCause)throw e.errorCause.stdout=e.error.stdout,e.errorCause.stderr=e.error.stderr,e.errorCause;return e.error}async function n7(e,t,n,r){let i=t instanceof LB||t instanceof PB||t instanceof FB?t.exitCode:t instanceof H?H.EXIT_CODE:0,a=await i7(e,$(t.stdout,t.stderr,i),n,r.targets,r.dupSources,r.standardRoutes);t.stdout=a.stdout,t.stderr=a.stderr,t.internalOutputAccounting=a.internalOutputAccounting??{stdout:V(a.stdout),stderr:V(a.stderr)}}async function r7(e,t,n,r){let i=e7(e,t,Y5),a;try{if(a=await i.prepare(n),a.error)return t7(a);let o=e.state.groupStdin,s=e.state.groupStdinSourceFd;a.stdin!==void 0&&(e.state.groupStdin=a.stdin,e.state.groupStdinSourceFd=a.stdinSourceFd);try{return await i7(e,await r(a),t,a.targets,a.dupSources,a.standardRoutes)}finally{a.stdin!==void 0&&(e.state.groupStdin=o,e.state.groupStdinSourceFd=s)}}catch(n){throw!(n instanceof jB)||!a||await n7(e,n,t,a),n}finally{i.finish()}}async function i7(e,t,n,r,i=new Map,a=new Map,o=`bash`,s=!1){n.length>0&&(t=e.executionScope.accountResult(t,`redirection`));let{stdout:c,stderr:l,exitCode:u}=t,d=t.stdoutKind===`bytes`||t.stdoutKind===void 0&&t.stdoutEncoding===`binary`?`binary`:`utf8`,f=e=>d,p={kind:`live-stdout`},m={kind:`live-stderr`},h=e=>{if(!e)return null;if(e.kind===`entry`){if(e.entry.kind===`dup-out`){if(e.entry.sourceFd===1)return{kind:`live-stdout`};if(e.entry.sourceFd===2)return{kind:`live-stderr`}}return e.entry.kind===`output`||e.entry.kind===`readwrite`?{kind:`descriptor`,source:e}:null}return e.fd===1?p:e.fd===2?m:null},g=t=>{let n=a.get(t)??P5(e,t);return n?n.kind===`closed`||n.kind===`input`||n.kind===`dup-in`?{kind:`invalid-output`,fd:t}:n.kind===`dup-out`?n.sourceFd===1?{kind:`live-stdout`}:n.sourceFd===2?{kind:`live-stderr`}:null:n.kind===`output`||n.kind===`readwrite`?{kind:`descriptor`,source:{kind:`entry`,entry:n,descriptors:A5(e,t)}}:null:null};p=g(1)??p,m=g(2)??m;for(let t=0;t`:case`>|`:case`>>`:{let t=a.fd??1;if(t!==1&&t!==2)break;let n=a.operator===`>>`;if(o===`/dev/stdout`){t===2&&(m=p);break}if(o===`/dev/stderr`){t===1&&(p=m);break}if(o===`/dev/full`){l+=`bash: echo: write error: No space left on device +`,u=1,t===1&&(c=``);break}if(o===`/dev/null`&&t===2){m={kind:`discard`};break}let r=e.fs.resolvePath(e.state.cwd,o);t===1?p={kind:`file`,path:r,append:n}:m={kind:`file`,path:r,append:n};break}case`>&`:case`<&`:{let e=a.fd??(a.operator===`<&`?0:1);if(e>=E5||e===0)break;if(o===`-`){e===1?p={kind:`discard`}:m={kind:`discard`};break}let n=h(i.get(t));if(!n)break;a.fd==null&&Z5(o)===null?(p=n,m=n):e===1?p=n:e===2&&(m=n);break}case`&>`:p={kind:`file`,path:e.fs.resolvePath(e.state.cwd,o),append:!1},m=p;break;case`&>>`:p={kind:`file`,path:e.fs.resolvePath(e.state.cwd,o),append:!0},m=p}}if(c!==``||l!==``){let t=c,n=l;c=``,l=``,p.kind===`invalid-output`&&t!==``&&(t=``,n+=`${s?``:`bash: `}${o}: write error: Bad file descriptor +`,u=1),m.kind===`invalid-output`&&(n=``);let r=async(t,n,r)=>{t.append?await e.fs.appendFile(t.path,n,r):await e.fs.writeFile(t.path,n,r)};if(p===m&&(p.kind===`file`||p.kind===`descriptor`)){let i=t+n;i!==``&&(p.kind===`file`?await r(p,i,f(i)):await W5(e,p.source.entry,p.source.descriptors,i,f(i)))}else for(let[i,a,o]of[[t,p,!0],[n,m,!1]])if(i!==``)switch(a.kind){case`live-stdout`:c+=i;break;case`live-stderr`:l+=i;break;case`file`:await r(a,i,o?f(i):J5(i));break;case`descriptor`:await W5(e,a.source.entry,a.source.descriptors,i,o?f(i):J5(i))}}let _=$(c,l,u);if(t.stdoutKind&&(_.stdoutKind=t.stdoutKind),t.stdoutEncoding===`binary`&&(_.stdoutEncoding=`binary`),t.internalPipeStatusOverride&&(_.internalPipeStatusOverride=t.internalPipeStatusOverride),n.length>0||e.state.fileDescriptors?.has(1)===!0||e.state.fileDescriptors?.has(2)===!0){let n=(t.internalOutputAccounting?.stdout??0)+(t.internalOutputAccounting?.stderr??0),r=V(_.stdout),i=V(_.stderr),a=Math.min(r,n);_.internalOutputAccounting={stdout:a,stderr:Math.min(i,n-a)},e.executionScope.accountResult(_,`redirection`)}else t.internalOutputAccounting&&(_.internalOutputAccounting=t.internalOutputAccounting);return _}function pMe(e,t){if(e.state.options.posix&&v5.has(t.name)){let n=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin +`;throw new LB(2,``,n)}let n={...t,sourceFile:t.sourceFile??e.state.currentSource??`main`};return e.state.functions.set(t.name,n),F8}async function a7(e,t,n,r=``,i,a=!1){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,R8(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,`recursion`)),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(i??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??`main`),e.state.localScopes.push(new Map),e.state.localArrayScopes??=[],e.state.localArrayScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let o=new Map,s=Number.parseInt(e.state.env.get(`#`)??`0`,10),c=Math.max(n.length,s);for(let t=0;t{if(l)return;l=!0;let t=e.state.localScopes.length-1,n=e.state.localScopes.pop(),r=e.state.localArrayScopes?.pop();if(n)for(let[t,r]of n)r===void 0?e.state.env.delete(t):e.state.env.set(t,r);if(r){e.state.arrays??=new Map;for(let[t,n]of r)n===void 0?(e.state.arrays.delete(t),e.state.associativeArrays?.delete(t)):(e.state.arrays.set(t,Y2(n)),e.state.associativeArrays??=new Set,n.kind===`associative`?e.state.associativeArrays.add(t):e.state.associativeArrays.delete(t))}if(Qje(e,t),e.state.fullyUnsetLocals)for(let[n,r]of e.state.fullyUnsetLocals.entries())r===t&&e.state.fullyUnsetLocals.delete(n);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let t=e.state.localExportedVars.pop();if(t)for(let n of t)e.state.exportedVars?.delete(n)}for(let[t,n]of o)n===void 0?e.state.env.delete(t):e.state.env.set(t,n);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},d=null,f=e7(e,t.redirections,Y5);try{if(d=await f.prepare(r),d.error)return t7(d);let n=d.stdin??r,i=a||d.stdin!==void 0||r!==``;return i7(e,await e.executeCommand(t.body,n,i),t.redirections,d.targets,d.dupSources,d.standardRoutes)}catch(n){if(n instanceof jB&&d&&(await n7(e,n,t.redirections,d),n instanceof PB))return $(n.stdout,n.stderr,n.exitCode);throw n}finally{f.finish(),u()}}var o7=e=>e.type===`Escaped`?X.literal(`\\${e.value}`):e.type===`DoubleQuoted`?{...e,parts:e.parts.map(o7)}:e,s7=[`!`,`[[`,`]]`,`case`,`do`,`done`,`elif`,`else`,`esac`,`fi`,`for`,`function`,`if`,`in`,`then`,`time`,`until`,`while`,`{`,`}`],c7=`.,:,[,alias,bg,bind,break,builtin,caller,cd,command,compgen,complete,compopt,continue,declare,dirs,disown,echo,enable,eval,exec,exit,export,false,fc,fg,getopts,hash,help,history,jobs,kill,let,local,logout,mapfile,popd,printf,pushd,pwd,read,readarray,readonly,return,set,shift,shopt,source,suspend,test,times,trap,true,type,typeset,ulimit,umask,unalias,unset,wait`.split(`,`),mMe=`autocd.assoc_expand_once.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.dotglob.execfail.expand_aliases.extdebug.extglob.extquote.failglob.force_fignore.globasciiranges.globstar.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lastpipe.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.nocaseglob.nocasematch.nullglob.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath.xpg_echo`.split(`.`),hMe=c7;async function gMe(e,t){let n=[],r=null,i=``,a=``,o=null,s=!1,c=!1,l=!1,u=null,d=null,f=null,p=[],m=[`alias`,`arrayvar`,`binding`,`builtin`,`command`,`directory`,`disabled`,`enabled`,`export`,`file`,`function`,`group`,`helptopic`,`hostname`,`job`,`keyword`,`running`,`service`,`setopt`,`shopt`,`signal`,`stopped`,`user`,`variable`];for(let e=0;e=t.length)return Q(`compgen: -A: option requires an argument +`,2);let r=t[e];if(!m.includes(r))return Q(`compgen: ${r}: invalid action name +`,2);n.push(r)}else if(o===`-W`){if(e++,e>=t.length)return Q(`compgen: -W: option requires an argument +`,2);r=t[e]}else if(o===`-P`){if(e++,e>=t.length)return Q(`compgen: -P: option requires an argument +`,2);i=t[e]}else if(o===`-S`){if(e++,e>=t.length)return Q(`compgen: -S: option requires an argument +`,2);a=t[e]}else if(o===`-o`){if(e++,e>=t.length)return Q(`compgen: -o: option requires an argument +`,2);let n=t[e];if(n===`plusdirs`)s=!0;else if(n===`dirnames`)c=!0;else if(n==="default")l=!0;else if(n!==`filenames`&&n!==`nospace`&&n!==`bashdefault`&&n!==`noquote`)return Q(`compgen: ${n}: invalid option name +`,2)}else if(o===`-F`){if(e++,e>=t.length)return Q(`compgen: -F: option requires an argument +`,2);d=t[e]}else if(o===`-C`){if(e++,e>=t.length)return Q(`compgen: -C: option requires an argument +`,2);f=t[e]}else if(o===`-X`){if(e++,e>=t.length)return Q(`compgen: -X: option requires an argument +`,2);u=t[e]}else if(o===`-G`){if(e++,e>=t.length)return Q(`compgen: -G: option requires an argument +`,2)}else if(o===`--`){p.push(...t.slice(e+1));break}else o.startsWith(`-`)||p.push(o)}o=p[0]??null;let h=[],g=new Set,_=()=>e.limits.maxArrayElements-h.length,v=t=>{for(let n of t){if(h.length>=e.limits.maxArrayElements)throw new H(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);if(V(n)>e.limits.maxStringLength)throw new H(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);e.executionScope.consumeWork(1,`compgen completion`),h.push(n),g.add(n)}};c&&v(await l7(e,o,_())),l&&v(await u7(e,o,_()));for(let t of n)t===`variable`?v(_Me(e,o,_())):t===`export`?v(vMe(e,o,_())):t===`function`?v(yMe(e,o,_())):t===`builtin`?v(bMe(e,o,_())):t===`keyword`?v(xMe(e,o,_())):t===`alias`?v(SMe(e,o,_())):t===`shopt`?v(CMe(e,o,_())):t===`helptopic`?v(wMe(e,o,_())):t===`directory`?v(await l7(e,o,_())):t===`file`?v(await u7(e,o,_())):t===`user`?v(TMe(e,o,_())):t===`command`&&v(await EMe(e,o,_()));if(r!==null)try{let t=OMe(e,await DMe(e,r),_(),o);for(let e of t)v([e])}catch(e){if(e instanceof H)throw e;return $(``,``,1)}if(s){let t=await l7(e,o,_(),g);for(let e of t)g.has(e)||v([e])}let y=``;if(d!==null){let t=e.state.functions.get(d);if(t){let n=new Map,r=Z2(e,`COMP_WORDS`),i=r?Y2(r):void 0;c4(e,`COMP_WORDS`),Q2(e,`COMP_WORDS`),n.set(`COMP_CWORD`,e.state.env.get(`COMP_CWORD`)),e.state.env.set(`COMP_CWORD`,`-1`),n.set(`COMP_LINE`,e.state.env.get(`COMP_LINE`)),e.state.env.set(`COMP_LINE`,``),n.set(`COMP_POINT`,e.state.env.get(`COMP_POINT`)),e.state.env.set(`COMP_POINT`,`0`);let a=Z2(e,`COMPREPLY`),o=a?Y2(a):void 0,s=e.state.env.get(`COMPREPLY`);c4(e,`COMPREPLY`),e.state.env.delete(`COMPREPLY`);let c=[`compgen`,p[0]??``,``];try{let r=await a7(e,t,c,``);if(r.exitCode!==0)return f7(e,n),p7(e,`COMP_WORDS`,i),p7(e,`COMPREPLY`,o),s!==void 0&&e.state.env.set(`COMPREPLY`,s),$(``,r.stderr,1);y=r.stdout,v(kMe(e,_()))}catch(t){if(t instanceof H)throw t;return f7(e,n),p7(e,`COMP_WORDS`,i),p7(e,`COMPREPLY`,o),s!==void 0&&e.state.env.set(`COMPREPLY`,s),$(``,``,1)}f7(e,n),p7(e,`COMP_WORDS`,i),p7(e,`COMPREPLY`,o),s!==void 0&&e.state.env.set(`COMPREPLY`,s)}}if(f!==null)try{let t=T3(f),n=await e.executeScript(t);if(n.exitCode!==0)return $(``,n.stderr,n.exitCode);if(n.stdout)for(let e of AMe(n.stdout))e.length>0&&v([e])}catch(e){if(e.name===`ParseException`)return Q(`compgen: -C: ${e.message} +`,2);throw e}let b=h;if(u!==null){let t=u.startsWith(`!`),n=t?u.slice(1):u;b=h.filter(r=>{let i=n5(r,n,!1,!0,e.limits.maxCallDepth);return t?i:!i})}if(b.length===0&&o!==null)return $(y,``,1);let x=new oH(e.limits.maxOutputSize,`compgen`);x.append(y);for(let e of b)x.append(i).append(e).append(a).append(` +`);return I8(x.build())}function _Me(e,t,n){let r=d7(e,t,n);for(let t of e.state.env.keys())/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&r.add(t);for(let t of e.state.arrays?.keys()??[])r.add(t);return r.build()}function vMe(e,t,n){let r=d7(e,t,n),i=e.state.exportedVars??new Set;for(let t of i)e.state.env.has(t)&&r.add(t);return r.build()}function yMe(e,t,n){let r=d7(e,t,n);for(let t of e.state.functions.keys())r.add(t);return r.build()}function bMe(e,t,n){let r=d7(e,t,n);for(let e of c7)r.add(e);return r.build()}function xMe(e,t,n){let r=d7(e,t,n);for(let e of s7)r.add(e);return r.build()}function SMe(e,t,n){let r=d7(e,t,n);for(let t of e.state.env.keys())if(t.startsWith(`BASH_ALIAS_`)){let e=t.slice(11);r.add(e)}return r.build()}function CMe(e,t,n){let r=d7(e,t,n);for(let e of mMe)r.add(e);return r.build()}function wMe(e,t,n){let r=d7(e,t,n);for(let e of hMe)r.add(e);return r.build()}async function l7(e,t,n=e.limits.maxArrayElements,r){let i=d7(e,null,n,r);try{let n=e.state.cwd,r=t??``;if(t){let i=t.lastIndexOf(`/`);if(i!==-1){let a=t.slice(0,i)||`/`;r=t.slice(i+1),n=a.startsWith(`/`)?a:`${e.state.cwd}/${a}`}}let a=await e.fs.readdir(n);for(let o of a){e.executionScope.consumeWork(1,`compgen directory scan`);let a=`${n}/${o}`;try{if((await e.fs.stat(a)).isDirectory&&(!r||o.startsWith(r))){if(t?.includes(`/`)){let e=t.lastIndexOf(`/`),n=t.slice(0,e+1);i.add(n+o)}else i.add(o)}}catch(e){if(e instanceof H)throw e}}}catch(e){if(e instanceof H)throw e}return i.build()}async function u7(e,t,n=e.limits.maxArrayElements){let r=d7(e,null,n);try{let n=e.state.cwd,i=t??``;if(t){let r=t.lastIndexOf(`/`);if(r!==-1){let a=t.slice(0,r)||`/`;i=t.slice(r+1),n=a.startsWith(`/`)?a:`${e.state.cwd}/${a}`}}let a=await e.fs.readdir(n);for(let n of a)if(e.executionScope.consumeWork(1,`compgen file scan`),!i||n.startsWith(i)){if(t?.includes(`/`)){let e=t.lastIndexOf(`/`),i=t.slice(0,e+1);r.add(i+n)}else r.add(n)}}catch(e){if(e instanceof H)throw e}return r.build()}function TMe(e,t,n){let r=d7(e,t,n);return r.add(`root`),r.add(`nobody`),r.build()}async function EMe(e,t,n){let r=d7(e,t,n);for(let e of c7)r.add(e);for(let t of e.state.functions.keys())r.add(t);for(let t of e.state.env.keys())t.startsWith(`BASH_ALIAS_`)&&r.add(t.slice(11));for(let e of s7)r.add(e);let i=e.state.env.get(`PATH`)??`/usr/bin:/bin`;for(let t of i.split(`:`))if(t)try{let n=await e.fs.readdir(t);for(let e of n)r.add(e)}catch(e){if(e instanceof H)throw e}return r.build()}function d7(e,t,n,r){let i=new Set;return{add(a){if(e.executionScope.consumeWork(1,`compgen candidate collection`),(t===null||a.startsWith(t))&&!r?.has(a)&&!i.has(a)){if(i.size>=n)throw new H(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);if(V(a)>e.limits.maxStringLength)throw new H(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);i.add(a)}},build(){return Array.from(i).sort()}}}async function DMe(e,t){let n=new w3().parseWordFromString(t,!1,!1);return await g8(e,X.word(n.parts.map(o7)))}function OMe(e,t,n,r){let i=e.state.env.get(`IFS`)??` +`;if(i.length===0){if(r!==null&&!t.startsWith(r))return[];if(n===0)throw new H(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);return[t]}let a=new Set(i.split(``)),o=[],s=t=>{if(r===null||t.startsWith(r)){if(o.length>=n)throw new H(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);o.push(t)}},c=``,l=0;for(;l0&&(s(c),c=``),l++):(c+=e,l++)}return c.length>0&&s(c),o}function f7(e,t){for(let[n,r]of t)r===void 0?e.state.env.delete(n):e.state.env.set(n,r)}function p7(e,t,n){e.state.arrays??=new Map,n?e.state.arrays.set(t,Y2(n)):e.state.arrays.delete(t)}function kMe(e,t){let n=[],r=r=>{if(n.length>=t)throw new H(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);n.push(r)};if(e4(e,`COMPREPLY`)){let t=_6(e,`COMPREPLY`);for(let[,e]of t)r(e)}else{let t=e.state.env.get(`COMPREPLY`);t!==void 0&&r(t)}return n}function*AMe(e){let t=0;for(;t<=e.length;){let n=e.indexOf(` +`,t),r=n===-1?e.length:n;if(r>t&&(yield e.slice(t,r)),n===-1)return;t=n+1}}kB();function m7(e){for(let t=0;t=t.length)return Q(`complete: -W: option requires an argument +`,2);a=t[e]}else if(d===`-F`){if(e++,e>=t.length)return Q(`complete: -F: option requires an argument +`,2);o=t[e]}else if(d===`-o`){if(e++,e>=t.length)return Q(`complete: -o: option requires an argument +`,2);let n=t[e];if(!MMe.includes(n))return Q(`complete: ${n}: invalid option name +`,2);c.push(n)}else if(d===`-A`){if(e++,e>=t.length)return Q(`complete: -A: option requires an argument +`,2);l.push(t[e])}else if(d===`-C`){if(e++,e>=t.length)return Q(`complete: -C: option requires an argument +`,2);s=t[e]}else if(d===`-G`){if(e++,e>=t.length)return Q(`complete: -G: option requires an argument +`,2)}else if(d===`-P`){if(e++,e>=t.length)return Q(`complete: -P: option requires an argument +`,2)}else if(d===`-S`){if(e++,e>=t.length)return Q(`complete: -S: option requires an argument +`,2)}else if(d===`-X`){if(e++,e>=t.length)return Q(`complete: -X: option requires an argument +`,2)}else if(d===`--`){u.push(...t.slice(e+1));break}else d.startsWith(`-`)||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),e.state.defaultCompletionSpec=void 0,e.state.emptyCompletionSpec=void 0,I8(``);for(let t of u)e.state.completionSpecs.delete(t);return I8(``)}if(n)return u.length===0?x7(e):x7(e,u);if(t.length===0||u.length===0&&!a&&!o&&!s&&c.length===0&&l.length===0&&!i)return x7(e);if(o&&u.length===0&&!i)return Q(`complete: -F: option requires a command name +`,2);if(i){let t={isDefault:!0};return a!==void 0&&(t.wordlist=a),o!==void 0&&(t.function=o),s!==void 0&&(t.command=s),c.length>0&&(t.options=c),l.length>0&&(t.actions=l),e.state.defaultCompletionSpec=t,I8(``)}for(let t of u){let n=Object.create(null);a!==void 0&&(n.wordlist=a),o!==void 0&&(n.function=o),s!==void 0&&(n.command=s),c.length>0&&(n.options=c),l.length>0&&(n.actions=l),e.state.completionSpecs.set(t,n)}return I8(``)}function x7(e,t){let n=e.state.completionSpecs??new Map;if(n.size===0&&!e.state.defaultCompletionSpec){if(t&&t.length>0){let e=``;for(let n of t)e+=`complete: ${n}: no completion specification +`;return $(``,e,1)}return I8(``)}let r=[],i=t||Array.from(n.keys());for(let e of i){let i=n.get(e);if(!i){if(t)return $(r.join(` +`)+(r.length>0?` +`:``),`complete: ${e}: no completion specification +`,1);continue}let a=`complete`;if(i.options)for(let e of i.options)a+=` -o ${g7(e)}`;if(i.actions)for(let e of i.actions)a+=` -A ${g7(e)}`;i.wordlist!==void 0&&(i.wordlist.includes(` `)||i.wordlist.includes(`'`),a+=` -W ${g7(i.wordlist)}`),i.function!==void 0&&(a+=` -F ${g7(i.function)}`),i.command!==void 0&&(a+=` -C ${g7(i.command)}`),i.isDefault&&(a+=` -D`),a+=`${e.startsWith(`-`)?` -- `:` `}${g7(e)}`,r.push(a)}if(!t&&e.state.defaultCompletionSpec){let t=e.state.defaultCompletionSpec,n=`complete`;for(let e of t.options??[])n+=` -o ${g7(e)}`;for(let e of t.actions??[])n+=` -A ${g7(e)}`;t.wordlist!==void 0&&(n+=` -W ${g7(t.wordlist)}`),t.function!==void 0&&(n+=` -F ${g7(t.function)}`),t.command!==void 0&&(n+=` -C ${g7(t.command)}`),n+=` -D`,r.push(n)}return r.length===0?I8(``):I8(`${r.join(` +`)} +`)}var S7=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function PMe(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,i=[],a=[],o=[];for(let e=0;e=t.length)return Q(`compopt: -o: option requires an argument +`,2);let n=t[e];if(!S7.includes(n))return Q(`compopt: ${n}: invalid option name +`,2);i.push(n)}else if(s===`+o`){if(e++,e>=t.length)return Q(`compopt: +o: option requires an argument +`,2);let n=t[e];if(!S7.includes(n))return Q(`compopt: ${n}: invalid option name +`,2);a.push(n)}else if(s===`--`){o.push(...t.slice(e+1));break}else!s.startsWith(`-`)&&!s.startsWith(`+`)&&o.push(s)}if(n){let t=e.state.defaultCompletionSpec??{isDefault:!0},n=new Set(t.options??[]);for(let e of i)n.add(e);for(let e of a)n.delete(e);return t.options=n.size>0?Array.from(n):void 0,e.state.defaultCompletionSpec=t,I8(``)}if(r){let t=e.state.emptyCompletionSpec??Object.create(null),n=new Set(t.options??[]);for(let e of i)n.add(e);for(let e of a)n.delete(e);return t.options=n.size>0?Array.from(n):void 0,e.state.emptyCompletionSpec=t,I8(``)}if(o.length>0){for(let t of o){let n=e.state.completionSpecs.get(t)??{},r=new Set(n.options??[]);for(let e of i)r.add(e);for(let e of a)r.delete(e);n.options=r.size>0?Array.from(r):void 0,e.state.completionSpecs.set(t,n)}return I8(``)}return Q(`compopt: not currently executing completion function +`,1)}U();function FMe(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new UB;return F8}if(t.length>1)throw new LB(1,``,`bash: continue: too many arguments +`);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new LB(1,``,`bash: continue: ${t[0]}: numeric argument required +`);n=e}throw new NB(n)}sH();function C7(e,t){let n=``;return e.state.integerVars?.has(t)&&(n+=`i`),e.state.lowercaseVars?.has(t)&&(n+=`l`),c6(e,t)&&(n+=`n`),e.state.readonlyVars?.has(t)&&(n+=`r`),e.state.uppercaseVars?.has(t)&&(n+=`u`),e.state.exportedVars?.has(t)&&(n+=`x`),n===``?`--`:`-${n}`}function w7(e){return g7(e)}function T7(e){return`'${e.replace(/'/g,`'\\''`)}'`}function IMe(e,t){let n=``,r=``,i=!1;for(let a of t){let t=C7(e,a);if(e.state.associativeArrays?.has(a)){let t=l4(e,a);if(t.length===0)n+=`declare -A ${a}=() +`;else{let r=t.map(t=>{let n=w7(t4(e,a,t)??``);return`[${T7(t)}]=${n}`});n+=`declare -A ${a}=(${r.join(` `)}) +`}continue}let o=s4(e,a);if(o.length>0){let t=o.map(t=>`[${t}]=${v7(t4(e,a,t)??``)}`);n+=`declare -a ${a}=(${t.join(` `)}) +`;continue}if(e4(e,a)){n+=`declare -a ${a}=() +`;continue}let s=e.state.env.get(a);if(s!==void 0)n+=`declare ${t} ${a}=${b7(s)} +`;else{let o=e.state.declaredVars?.has(a),s=e.state.localVarDepth?.has(a);o||s?n+=`declare ${t} ${a} +`:(r+=`bash: declare: ${a}: not found +`,i=!0)}}return $(n,r,+!!i)}function LMe(e,t){let{filterExport:n,filterReadonly:r,filterNameref:i,filterIndexedArray:a,filterAssocArray:o}=t,s=n||r||i||a||o,c=``,l=new Set;for(let t of e.state.env.keys())t.startsWith(`BASH_`)||l.add(t);for(let t of e.state.arrays?.keys()??[])l.add(t);if(e.state.localVarDepth)for(let t of e.state.localVarDepth.keys())l.add(t);if(e.state.associativeArrays)for(let t of e.state.associativeArrays)l.add(t);let u=Array.from(l).sort();for(let t of u){let l=C7(e,t),u=e.state.associativeArrays?.has(t),d=s4(e,t),f=!u&&e4(e,t);if(s&&(o&&!u||a&&!f||n&&!e.state.exportedVars?.has(t)||r&&!e.state.readonlyVars?.has(t)||i&&!c6(e,t)))continue;if(u){let n=l4(e,t);if(n.length===0)c+=`declare -A ${t}=() +`;else{let r=n.map(n=>{let r=w7(t4(e,t,n)??``);return`[${T7(n)}]=${r}`});c+=`declare -A ${t}=(${r.join(` `)}) +`}continue}if(d.length>0){let n=d.map(n=>`[${n}]=${v7(t4(e,t,n)??``)}`);c+=`declare -a ${t}=(${n.join(` `)}) +`;continue}if(e4(e,t)){c+=`declare -a ${t}=() +`;continue}let p=e.state.env.get(t);p!==void 0&&(c+=`declare ${l} ${t}=${b7(p)} +`)}return I8(c)}function RMe(e){let t=``,n=Array.from(e.state.associativeArrays??[]).sort();for(let r of n){let n=l4(e,r);if(n.length===0)t+=`declare -A ${r}=() +`;else{let i=n.map(t=>{let n=w7(t4(e,r,t)??``);return`[${T7(t)}]=${n}`});t+=`declare -A ${r}=(${i.join(` `)}) +`}}return I8(t)}function zMe(e){let t=``,n=new Set(Array.from(e.state.arrays??[]).filter(([,e])=>e.kind===`indexed`).map(([e])=>e)),r=Array.from(n).sort();for(let n of r){let r=s4(e,n);if(r.length===0)t+=`declare -a ${n}=() +`;else{let i=r.map(t=>`[${t}]=${v7(t4(e,n,t)??``)}`);t+=`declare -a ${n}=(${i.join(` `)}) +`}}return I8(t)}function BMe(e){let t=``,n=new Set;for(let t of e.state.env.keys())t.startsWith(`BASH_`)||n.add(t);let r=Array.from(n).sort();for(let n of r){if(e.state.associativeArrays?.has(n)||s4(e,n).length>0||e4(e,n))continue;let r=e.state.env.get(n);r!==void 0&&(t+=`${n}=${g7(r)} +`)}return I8(t)}function E7(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function D7(e,t){return e.state.integerVars?.has(t)??!1}function O7(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function VMe(e,t){return e.state.lowercaseVars?.has(t)??!1}function k7(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function HMe(e,t){return e.state.uppercaseVars?.has(t)??!1}function A7(e,t,n){return VMe(e,t)?n.toLowerCase():HMe(e,t)?n.toUpperCase():n}async function j7(e,t){try{let n=await M8(e,N4(new w3,t).expression);return String(n)}catch{return`0`}}function UMe(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let n=t[0],r=n.length;if(e[r]!==`[`)return null;let i=0,a=r+1;for(;r0&&!_,b=t=>{if(!y)return;let n=e.state.localScopes[e.state.localScopes.length-1];n.has(t)||n.set(t,e.state.env.get(t))},x=t=>{if(!y)return;let n=e.state.localScopes[e.state.localScopes.length-1];for(n.has(t)||n.set(t,e.state.env.get(t)),e.state.localArrayScopes??=[];e.state.localArrayScopes.length{y&&m5(e,t)};if(g){if(v.length===0){let t=Array.from(e.state.functions.keys()).sort(),n=``;for(let e of t)n+=`declare -f ${e} +`;return I8(n)}let t=!0,n=``;for(let r of v)e.state.functions.has(r)?n+=`${r} +`:t=!1;return $(n,``,+!t)}if(h){if(v.length===0){let t=``,n=Array.from(e.state.functions.keys()).sort();for(let e of n)t+=`${e} () +{ + # function body +} +`;return I8(t)}let t=!0;for(let n of v)e.state.functions.has(n)||(t=!1);return $(``,``,+!t)}if(s&&v.length>0)return IMe(e,v);if(s&&v.length===0)return LMe(e,{filterExport:o,filterReadonly:a,filterNameref:c,filterIndexedArray:r,filterAssocArray:i});if(v.length===0&&i&&!s)return RMe(e);if(v.length===0&&r&&!s)return zMe(e);if(v.length===0&&!s)return BMe(e);let C=``,w=0;for(let t of v){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(s&&!u){let t=s[1],c=s[2],l=B6(e,t);if(l)return l;if(i&&s4(e,t).length>0){C+=`bash: declare: ${t}: cannot convert indexed to associative array +`,w=1;continue}if((r||!i&&!r)&&e.state.associativeArrays?.has(t)){C+=`bash: declare: ${t}: cannot convert associative to indexed array +`,w=1;continue}let u=i&&c.includes(`[`)?p5(c,n):void 0,d=u===void 0?f5(c,{...n,maxElements:i?n.maxElements*2:n.maxElements}):void 0;if(e.executionScope.consumeWork(u?.length??d?.length??0,`declare array assignment`),x(t),i?(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(t),$2(e,t,`associative`)):$2(e,t,`indexed`),c4(e,t),e.state.env.delete(t),i&&c.includes(`[`))for(let[n,r]of u??[])r4(e,t,n,J6(e,r),`associative`);else if(i){let n=d??[];for(let r=0;r/^\[[^\]]+\]=/.test(e))){let r=0;for(let i of n){let n=i.match(/^\[([^\]]+)\]=(.*)$/);if(n){let i=n[1],a=n[2],o;if(/^-?\d+$/.test(i))o=Number.parseInt(i,10);else try{o=await M8(e,N4(new w3,i).expression)}catch{o=0}r4(e,t,o,J6(e,a)),r=o+1}else r4(e,t,r,i),r++}}else for(let r=0;re));for(let[n,r]of i)r4(e,t,n,r,`associative`)}else{e.executionScope.consumeWork(s.length,`declare array append`);let n=s4(e,t),r=0,i=e.state.env.get(t);n.length===0&&i!==void 0?(r4(e,t,0,i),e.state.env.delete(t),r=1):n.length>0&&(r=Math.max(...n)+1),i4(e,t,Array.from({length:s.length},(e,t)=>r+t));for(let n=0;n0||e.state.associativeArrays?.has(t);if(D7(e,t)){let r=e.state.env.get(t)??`0`,i=parseInt(r,10)||0,a=parseInt(await j7(e,n),10)||0;n=String(i+a),e.state.env.set(t,n)}else if(i)n=A7(e,t,n),r4(e,t,0,aH([t4(e,t,0)??``,n],``,e.limits.maxStringLength,`declare append`));else{n=A7(e,t,n);let r=e.state.env.get(t)??``;e.state.env.set(t,aH([r,n],``,e.limits.maxStringLength,`declare append`))}S(t),a&&R6(e,t),o&&V6(e,t),e.state.options.allexport&&!d&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t));continue}if(t.includes(`=`)){let n=t.indexOf(`=`),r=t.slice(0,n),i=t.slice(n+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)){C+=`bash: typeset: \`${r}': not a valid identifier +`,w=1;continue}let s=B6(e,r);if(s)return s;if(b(r),c){if(i!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(i)){C+=`bash: declare: \`${i}': invalid variable name for name reference +`,w=1;continue}e.state.env.set(r,i),l6(e,r),i!==``&&f6(e,i)&&d6(e,r),S(r),a&&R6(e,r),o&&V6(e,r);continue}if(f&&E7(e,r),p&&O7(e,r),m&&k7(e,r),D7(e,r)&&(i=await j7(e,i)),i=A7(e,r,i),c6(e,r)){let t=p6(e,r);t&&t!==r?e.state.env.set(t,i):e.state.env.set(r,i)}else e.state.env.set(r,i);S(r),a&&R6(e,r),o&&V6(e,r),e.state.options.allexport&&!d&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(r))}else{let n=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){C+=`bash: typeset: \`${n}': not a valid identifier +`,w=1;continue}if(r||i?x(n):b(n),c){l6(e,n);let t=e.state.env.get(n);t!==void 0&&t!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(t)?Uke(e,n):t&&f6(e,t)&&d6(e,n),S(n),a&&R6(e,n),o&&V6(e,n);continue}if(f&&E7(e,n),p&&O7(e,n),m&&k7(e,n),i){if(s4(e,n).length>0){C+=`bash: declare: ${n}: cannot convert indexed to associative array +`,w=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(n),$2(e,n,`associative`)}let s=e4(e,n);!e.state.env.has(n)&&!s&&(r||i?$2(e,n,i?`associative`:`indexed`):(e.state.declaredVars??=new Set,e.state.declaredVars.add(n))),S(n),a&&R6(e,n),o&&V6(e,n)}}return $(``,C,w)}async function GMe(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=[];for(let e=0;ee));for(let[n,i]of r)r4(e,t,n,i,`associative`)}else{e.executionScope.consumeWork(o.length,`readonly array append`);let n=s4(e,t),r=0,i=e.state.env.get(t);n.length===0&&i!==void 0?(r4(e,t,0,i),e.state.env.delete(t),r=1):n.length>0&&(r=Math.max(...n)+1),i4(e,t,Array.from({length:o.length},(e,t)=>r+t));for(let n=0;ne&&e!==`.`),n=[];for(let e of t)e===`..`?n.pop():n.push(e);return`/${n.join(`/`)}`}async function qMe(e,t){let n=M7(e),r;for(let e=0;ee);t.pop(),i=`/${t.join(`/`)}`}else i=r===`.`?e.state.cwd:r.startsWith(`~`)?(e.state.env.get(`HOME`)||`/`)+r.slice(1):`${e.state.cwd}/${r}`;i=KMe(i);try{if(!(await e.fs.stat(i)).isDirectory)return Q(`bash: pushd: ${r}: Not a directory +`,1)}catch{return Q(`bash: pushd: ${r}: No such file or directory +`,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=i,e.state.env.set(`PWD`,i),e.state.env.set(`OLDPWD`,e.state.previousDir);let a=e.state.env.get(`HOME`)||``;return I8(`${[i,...n].map(e=>N7(e,a)).join(` `)} +`)}function JMe(e,t){let n=M7(e);for(let e of t)if(e!==`--`)return e.startsWith(`-`)&&e!==`-`?Q(`bash: popd: ${e}: invalid option +`,2):Q(`bash: popd: too many arguments +`,2);if(n.length===0)return Q(`bash: popd: directory stack empty +`,1);let r=n.shift();if(!r)return Q(`bash: popd: directory stack empty +`,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set(`PWD`,r),e.state.env.set(`OLDPWD`,e.state.previousDir);let i=e.state.env.get(`HOME`)||``;return I8(`${[r,...n].map(e=>N7(e,i)).join(` `)} +`)}function YMe(e,t){let n=M7(e),r=!1,i=!1,a=!1,o=!1;for(let e of t)if(e!==`--`){if(e.startsWith(`-`))for(let t of e.slice(1))if(t===`c`)r=!0;else if(t===`l`)i=!0;else if(t===`p`)a=!0;else if(t===`v`)a=!0,o=!0;else return Q(`bash: dirs: -${t}: invalid option +`,2);else return Q(`bash: dirs: too many arguments +`,1)}if(r)return e.state.directoryStack=[],F8;let s=[e.state.cwd,...n],c=e.state.env.get(`HOME`)||``,l;return o?(l=s.map((e,t)=>` ${t} ${i?e:N7(e,c)}`).join(` +`),l+=` +`):l=a?s.map(e=>i?e:N7(e,c)).join(` +`)+` +`:s.map(e=>i?e:N7(e,c)).join(` `)+` +`,I8(l)}U();async function P7(e,t,n,r=!1){let i=t;if(i.length>0){let e=i[0];if(e===`--`)i=i.slice(1);else if(e.startsWith(`-`)&&e!==`-`&&e.length>1)return Q(`bash: eval: ${e}: invalid option +eval: usage: eval [arg ...] +`,2)}if(i.length===0)return F8;let a=i.join(` `);if(a.trim()===``)return F8;let o=e.state.groupStdin,s=r||n!==void 0&&n!==``;s&&(e.state.groupStdin=n??``);try{let t=T3(a);return await e.executeScript(t)}catch(e){if(e instanceof MB||e instanceof NB||e instanceof PB||e instanceof LB)throw e;if(e.name===`ParseException`)return Q(`bash: eval: ${e.message} +`);throw e}finally{(s||o!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=o)}}U();function XMe(e,t){let n,r=``;if(t.length===0)n=e.state.lastExitCode;else{let e=t[0];if(e===``||!/^-?\d+$/.test(e))r=`bash: exit: ${e}: numeric argument required +`,n=2;else{let t=BigInt(e);n=Number((t%256n+256n)%256n)}}throw new LB(n,``,r)}function ZMe(e,t){let n=!1,r=[];for(let e of t)e===`-n`?n=!0:e===`-p`||e===`--`||r.push(e);if(r.length===0&&!n){let t=``,n=e.state.exportedVars??new Set,r=Array.from(n).sort();for(let n of r){let r=e.state.env.get(n);r!==void 0&&(t+=`declare -x ${n}=${b7(r)} +`)}return I8(t)}if(n){for(let t of r){let n,r;if(t.includes(`=`)){let e=t.indexOf(`=`);n=t.slice(0,e),r=t.slice(e+1)}else n=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n))return $(``,`bash: export: \`${t}': not a valid identifier +`,1);r!==void 0&&(B6(e,n),e.state.env.set(n,r)),H6(e,n)}return F8}let i=``,a=0;for(let t of r){let n,r,o=!1,s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(s)n=s[1],r=s[2],o=!0;else if(t.includes(`=`)){let e=t.indexOf(`=`);n=t.slice(0,e),r=t.slice(e+1)}else n=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){i+=`bash: export: \`${t}': not a valid identifier +`,a=1;continue}if(r!==void 0){if(B6(e,n),o){let t=e.state.env.get(n)??``;e.state.env.set(n,t+r)}else e.state.env.set(n,r)}else e.state.env.has(n)||e.state.env.set(n,``);V6(e,n)}return $(``,i,a)}function F7(e,t){if(t.length<2)return Q(`bash: getopts: usage: getopts optstring name [arg ...] +`);let n=t[0],r=t[1],i=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),a=n.startsWith(`:`),o=a?n.slice(1):n,s;if(t.length>2)s=t.slice(2);else{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);s=[];for(let n=1;n<=t;n++)s.push(e.state.env.get(String(n))||``)}let c=Number.parseInt(e.state.env.get(`OPTIND`)||`1`,10);c<1&&(c=1);let l=Number.parseInt(e.state.env.get(`__GETOPTS_CHARINDEX`)||`0`,10);if(e.state.env.set(`OPTARG`,``),c>s.length)return i||e.state.env.set(r,`?`),e.state.env.set(`OPTIND`,String(s.length+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:1,stdout:``,stderr:``};let u=s[c-1];if(!u||u===`-`||!u.startsWith(`-`))return i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};if(u===`--`)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),i||e.state.env.set(r,`?`),{exitCode:i?2:1,stdout:``,stderr:``};let d=l===0?1:l,f=u[d];if(!f)return e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),F7(e,t);let p=o.indexOf(f);if(p===-1){let t=``;return a?e.state.env.set(`OPTARG`,f):t=`bash: illegal option -- ${f} +`,i||e.state.env.set(r,`?`),d+1=s.length){let t=``;return a?(e.state.env.set(`OPTARG`,f),i||e.state.env.set(r,`:`)):(t=`bash: option requires an argument -- ${f} +`,i||e.state.env.set(r,`?`)),e.state.env.set(`OPTIND`,String(c+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:i?2:0,stdout:``,stderr:t}}e.state.env.set(`OPTARG`,s[c]),e.state.env.set(`OPTIND`,String(c+2)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)}}else d+1=t.length)return Q(`bash: hash: -p: option requires an argument +`,1);s=t[l],l++}else if(e.startsWith(`-`)&&e.length>1){for(let t of e.slice(1))if(t===`r`)n=!0;else if(t===`d`)r=!0;else if(t===`l`)i=!0;else if(t===`t`)o=!0;else return Q(t===`p`?`bash: hash: -p: option requires an argument +`:`bash: hash: -${t}: invalid option +`,1);l++}else c.push(e),l++}if(n)return e.state.hashTable.clear(),F8;if(r){if(c.length===0)return Q(`bash: hash: -d: option requires an argument +`,1);let t=!1,n=``;for(let r of c)e.state.hashTable.has(r)?e.state.hashTable.delete(r):(n+=`bash: hash: ${r}: not found +`,t=!0);return t?Q(n,1):F8}if(o){if(c.length===0)return Q(`bash: hash: -t: option requires an argument +`,1);let t=``,n=!1,r=``;for(let i of c){let a=e.state.hashTable.get(i);a?c.length>1?t+=`${i} ${a} +`:t+=`${a} +`:(r+=`bash: hash: ${i}: not found +`,n=!0)}return n?{exitCode:1,stdout:t,stderr:r}:I8(t)}if(a){if(c.length===0)return Q(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...] +`,1);let t=c[0];return e.state.hashTable.set(t,s),F8}if(c.length===0){if(e.state.hashTable.size===0)return I8(`hash: hash table empty +`);let t=``;if(i)for(let[n,r]of e.state.hashTable){let e=n.startsWith(`-`)?` --`:``;t+=`builtin hash -p ${g7(r)}${e} ${g7(n)} +`}else{t=`hits command +`;for(let[,n]of e.state.hashTable)t+=` 1 ${n} +`}return I8(t)}let u=!1,d=``,f=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let t of c){if(t.includes(`/`)){d+=`bash: hash: ${t}: cannot use / in name +`,u=!0;continue}let n=!1;for(let r of f){if(!r)continue;let i=`${r}/${t}`;if(await e.fs.exists(i)){e.state.hashTable.set(t,i),n=!0;break}}n||(d+=`bash: hash: ${t}: not found +`,u=!0)}return u?Q(d,1):F8}yG();var I7=new Map([[`:`,[`: [arguments]`,`Null command. + No effect; the command does nothing. + Exit Status: + Always succeeds.`]],[`.`,[`. filename [arguments]`,`Execute commands from a file in the current shell. + Read and execute commands from FILENAME in the current shell. + The entries in $PATH are used to find the directory containing FILENAME. + Exit Status: + Returns the status of the last command executed in FILENAME.`]],[`[`,[`[ arg... ]`,`Evaluate conditional expression. + This is a synonym for the "test" builtin, but the last argument must + be a literal \`]', to match the opening \`['.`]],[`alias`,[`alias [-p] [name[=value] ... ]`,`Define or display aliases. + Without arguments, \`alias' prints the list of aliases in the reusable + form \`alias NAME=VALUE' on standard output. + Exit Status: + alias returns true unless a NAME is supplied for which no alias has been + defined.`]],[`bg`,[`bg [job_spec ...]`,`Move jobs to the background. + Place the jobs identified by each JOB_SPEC in the background, as if they + had been started with \`&'.`]],[`break`,[`break [n]`,`Exit for, while, or until loops. + Exit a FOR, WHILE or UNTIL loop. If N is specified, break N enclosing + loops. + Exit Status: + The exit status is 0 unless N is not greater than or equal to 1.`]],[`builtin`,[`builtin [shell-builtin [arg ...]]`,`Execute shell builtins. + Execute SHELL-BUILTIN with arguments ARGs without performing command + lookup. This is useful when you wish to reimplement a shell builtin + as a shell function, but need to execute the builtin within the function. + Exit Status: + Returns the exit status of SHELL-BUILTIN, or false if SHELL-BUILTIN is + not a shell builtin.`]],[`caller`,[`caller [expr]`,`Return the context of the current subroutine call. + Without EXPR, returns "$line $filename". With EXPR, returns + "$line $subroutine $filename"; this extra information can be used to + provide a stack trace. + Exit Status: + Returns 0 unless the shell is not executing a subroutine call or + EXPR is invalid.`]],[`cd`,[`cd [-L|-P] [dir]`,`Change the shell working directory. + Change the current directory to DIR. The default DIR is the value of the + HOME shell variable. + + The variable CDPATH defines the search path for the directory containing + DIR. Alternative directory names in CDPATH are separated by a colon (:). + A null directory name is the same as the current directory. If DIR begins + with a slash (/), then CDPATH is not used. + + If the directory is not found, and the shell option \`cdable_vars' is set, + the word is assumed to be a variable name. If that variable has a value, + its value is used for DIR. + + Options: + -L force symbolic links to be followed + -P use the physical directory structure without following symbolic + links + + The default is to follow symbolic links, as if \`-L' were specified. + + Exit Status: + Returns 0 if the directory is changed; non-zero otherwise.`]],[`command`,[`command [-pVv] command [arg ...]`,`Execute a simple command or display information about commands. + Runs COMMAND with ARGS suppressing shell function lookup, or display + information about the specified COMMANDs. + + Options: + -p use a default value for PATH that is guaranteed to find all of + the standard utilities + -v print a description of COMMAND similar to the \`type' builtin + -V print a more verbose description of each COMMAND + + Exit Status: + Returns exit status of COMMAND, or failure if COMMAND is not found.`]],[`compgen`,[`compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word]`,`Display possible completions depending on the options. + Intended to be used from within a shell function generating possible + completions. If the optional WORD argument is supplied, matches against + WORD are generated. + Exit Status: + Returns success unless an invalid option is supplied or an error occurs.`]],[`complete`,[`complete [-abcdefgjksuv] [-pr] [-DEI] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [name ...]`,`Specify how arguments are to be completed. + For each NAME, specify how arguments are to be completed. + Exit Status: + Returns success unless an invalid option is supplied or an error occurs.`]],[`continue`,[`continue [n]`,`Resume for, while, or until loops. + Resumes the next iteration of the enclosing FOR, WHILE or UNTIL loop. + If N is specified, resumes the Nth enclosing loop. + Exit Status: + The exit status is 0 unless N is not greater than or equal to 1.`]],[`declare`,[`declare [-aAfFgilnrtux] [-p] [name[=value] ...]`,`Set variable values and attributes. + Declare variables and give them attributes. If no NAMEs are given, + display the attributes and values of all variables. + + Options: + -a to make NAMEs indexed arrays (if supported) + -A to make NAMEs associative arrays (if supported) + -i to make NAMEs have the \`integer' attribute + -l to convert the value of each NAME to lower case on assignment + -n make NAME a reference to the variable named by its value + -r to make NAMEs readonly + -t to make NAMEs have the \`trace' attribute + -u to convert the value of each NAME to upper case on assignment + -x to make NAMEs export + + Exit Status: + Returns success unless an invalid option is supplied or a variable + assignment error occurs.`]],[`dirs`,[`dirs [-clpv] [+N] [-N]`,`Display directory stack. + Display the list of currently remembered directories. Directories + find their way onto the list with the \`pushd' command; you can get + back up through the list with the \`popd' command. + Exit Status: + Returns success unless an invalid option is supplied or an error occurs.`]],[`disown`,[`disown [-h] [-ar] [jobspec ...]`,`Remove jobs from current shell. + Without any JOBSPECs, remove the current job.`]],[`echo`,[`echo [-neE] [arg ...]`,`Write arguments to the standard output. + Display the ARGs, separated by a single space character and followed by a + newline, on the standard output. + + Options: + -n do not append a newline + -e enable interpretation of the following backslash escapes + -E explicitly suppress interpretation of backslash escapes + + Exit Status: + Returns success unless a write error occurs.`]],[`enable`,[`enable [-a] [-dnps] [-f filename] [name ...]`,`Enable and disable shell builtins. + Enables and disables builtin shell commands. + Exit Status: + Returns success unless NAME is not a shell builtin or an error occurs.`]],[`eval`,[`eval [arg ...]`,`Execute arguments as a shell command. + Combine ARGs into a single string, use the result as input to the shell, + and execute the resulting commands. + Exit Status: + Returns exit status of command or success if command is null.`]],[`exec`,[`exec [-cl] [-a name] [command [arguments ...]] [redirection ...]`,`Replace the shell with the given command. + Execute COMMAND, replacing this shell with the specified program. + ARGUMENTS become the arguments to COMMAND. If COMMAND is not specified, + any redirections take effect in the current shell. + Exit Status: + Returns success unless COMMAND is not found or a redirection error occurs.`]],[`exit`,[`exit [n]`,`Exit the shell. + Exits the shell with a status of N. If N is omitted, the exit status + is that of the last command executed.`]],[`export`,[`export [-fn] [name[=value] ...] or export -p`,`Set export attribute for shell variables. + Marks each NAME for automatic export to the environment of subsequently + executed commands. If VALUE is supplied, assign VALUE before exporting. + + Options: + -f refer to shell functions + -n remove the export property from each NAME + -p display a list of all exported variables and functions + + Exit Status: + Returns success unless an invalid option is given or NAME is invalid.`]],[`false`,[`false`,`Return an unsuccessful result. + Exit Status: + Always fails.`]],[`fc`,[`fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command]`,`Display or execute commands from the history list. + Exit Status: + Returns success or status of executed command.`]],[`fg`,[`fg [job_spec]`,`Move job to the foreground. + Place the job identified by JOB_SPEC in the foreground, making it the + current job.`]],[`getopts`,[`getopts optstring name [arg]`,`Parse option arguments. + Getopts is used by shell procedures to parse positional parameters + as options. + + OPTSTRING contains the option letters to be recognized; if a letter + is followed by a colon, the option is expected to have an argument, + which should be separated from it by white space. + Exit Status: + Returns success if an option is found; fails if the end of options is + encountered or an error occurs.`]],[`hash`,[`hash [-lr] [-p pathname] [-dt] [name ...]`,`Remember or display program locations. + Determine and remember the full pathname of each command NAME. + Exit Status: + Returns success unless NAME is not found or an invalid option is given.`]],[`help`,[`help [-s] [pattern ...]`,`Display information about builtin commands. + Displays brief summaries of builtin commands. If PATTERN is + specified, gives detailed help on all commands matching PATTERN, + otherwise the list of help topics is printed. + + Options: + -s output only a short usage synopsis for each topic matching + PATTERN + + Exit Status: + Returns success unless PATTERN is not found.`]],[`history`,[`history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]`,`Display or manipulate the history list. + Display the history list with line numbers, prefixing each modified + entry with a \`*'. + Exit Status: + Returns success unless an invalid option is given or an error occurs.`]],[`jobs`,[`jobs [-lnprs] [jobspec ...] or jobs -x command [args]`,`Display status of jobs. + Lists the active jobs. + Exit Status: + Returns success unless an invalid option is given or an error occurs.`]],[`kill`,[`kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]`,`Send a signal to a job. + Send the processes identified by PID or JOBSPEC the signal named by + SIGSPEC or SIGNUM. + Exit Status: + Returns success unless an invalid option is given or an error occurs.`]],[`let`,[`let arg [arg ...]`,`Evaluate arithmetic expressions. + Evaluate each ARG as an arithmetic expression. Evaluation is done in + fixed-width integers with no check for overflow, though division by 0 + is trapped and flagged as an error. + Exit Status: + If the last ARG evaluates to 0, let returns 1; 0 is returned otherwise.`]],[`local`,[`local [option] name[=value] ...`,`Define local variables. + Create a local variable called NAME, and give it VALUE. OPTION can + be any option accepted by \`declare'. + + Local can only be used within a function; it makes the variable NAME + have a visible scope restricted to that function and its children. + Exit Status: + Returns success unless an invalid option is supplied, a variable + assignment error occurs, or the shell is not executing a function.`]],[`logout`,[`logout [n]`,`Exit a login shell. + Exits a login shell with exit status N. Returns an error if not executed + in a login shell.`]],[`mapfile`,[`mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]`,`Read lines from the standard input into an indexed array variable. + Read lines from the standard input into the indexed array variable ARRAY, + or from file descriptor FD if the -u option is supplied. + + Options: + -d delim Use DELIM to terminate lines, instead of newline + -n count Copy at most COUNT lines + -O origin Begin assigning to ARRAY at index ORIGIN + -s count Discard the first COUNT lines read + -t Remove a trailing DELIM from each line read (default newline) + -u fd Read lines from file descriptor FD instead of standard input + + Exit Status: + Returns success unless an invalid option is given or ARRAY is readonly.`]],[`popd`,[`popd [-n] [+N | -N]`,`Remove directories from stack. + Removes entries from the directory stack. + Exit Status: + Returns success unless an invalid argument is supplied or the directory + change fails.`]],[`printf`,[`printf [-v var] format [arguments]`,`Formats and prints ARGUMENTS under control of the FORMAT. + + Options: + -v var assign the output to shell variable VAR rather than + display it on the standard output + + FORMAT is a character string which contains three types of objects: plain + characters, which are simply copied to standard output; character escape + sequences, which are converted and copied to the standard output; and + format specifications, each of which causes printing of the next successive + argument. + Exit Status: + Returns success unless an invalid option is given or a write or assignment + error occurs.`]],[`pushd`,[`pushd [-n] [+N | -N | dir]`,`Add directories to stack. + Adds a directory to the top of the directory stack, or rotates + the stack, making the new top of the stack the current working + directory. + Exit Status: + Returns success unless an invalid argument is supplied or the directory + change fails.`]],[`pwd`,[`pwd [-LP]`,`Print the name of the current working directory. + + Options: + -L print the value of $PWD if it names the current working + directory + -P print the physical directory, without any symbolic links + + By default, \`pwd' behaves as if \`-L' were specified. + Exit Status: + Returns 0 unless an invalid option is given or the current directory + cannot be read.`]],[`read`,[`read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]`,`Read a line from the standard input and split it into fields. + Reads a single line from the standard input, or from file descriptor FD + if the -u option is supplied. The line is split into fields as with word + splitting, and the first word is assigned to the first NAME, the second + word to the second NAME, and so on, with any leftover words assigned to + the last NAME. + Exit Status: + The return code is zero, unless end-of-file is encountered, read times out, + or an invalid file descriptor is supplied as the argument to -u.`]],[`readarray`,[`readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]`,`Read lines from a file into an array variable. + A synonym for \`mapfile'.`]],[`readonly`,[`readonly [-aAf] [name[=value] ...] or readonly -p`,`Mark shell variables as unchangeable. + Mark each NAME as read-only; the values of these NAMEs may not be + changed by subsequent assignment. + Exit Status: + Returns success unless an invalid option is given or NAME is invalid.`]],[`return`,[`return [n]`,`Return from a shell function. + Causes a function or sourced script to exit with the return value + specified by N. If N is omitted, the return status is that of the + last command executed within the function or script. + Exit Status: + Returns N, or failure if the shell is not executing a function or script.`]],[`set`,[`set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]`,`Set or unset values of shell options and positional parameters. + Change the value of shell attributes and positional parameters, or + display the names and values of shell variables. + + Options: + -e Exit immediately if a command exits with a non-zero status. + -u Treat unset variables as an error when substituting. + -x Print commands and their arguments as they are executed. + -o option-name + Set the variable corresponding to option-name + + Exit Status: + Returns success unless an invalid option is given.`]],[`shift`,[`shift [n]`,`Shift positional parameters. + Rename the positional parameters $N+1,$N+2 ... to $1,$2 ... If N is + not given, it is assumed to be 1. + Exit Status: + Returns success unless N is negative or greater than $#.`]],[`shopt`,[`shopt [-pqsu] [-o] [optname ...]`,`Set and unset shell options. + Change the setting of each shell option OPTNAME. Without any option + arguments, list each supplied OPTNAME, or all shell options if no + OPTNAMEs are given, with an indication of whether or not each is set. + + Options: + -o restrict OPTNAMEs to those defined for use with \`set -o' + -p print each shell option with an indication of its status + -q suppress output + -s enable (set) each OPTNAME + -u disable (unset) each OPTNAME + + Exit Status: + Returns success if OPTNAME is enabled; fails if an invalid option is + given or OPTNAME is disabled.`]],[`source`,[`source filename [arguments]`,`Execute commands from a file in the current shell. + Read and execute commands from FILENAME in the current shell. + The entries in $PATH are used to find the directory containing FILENAME. + Exit Status: + Returns the status of the last command executed in FILENAME.`]],[`suspend`,[`suspend [-f]`,`Suspend shell execution. + Suspend the execution of this shell until it receives a SIGCONT signal.`]],[`test`,[`test [expr]`,`Evaluate conditional expression. + Exits with a status of 0 (true) or 1 (false) depending on + the evaluation of EXPR. Expressions may be unary or binary. + Exit Status: + Returns success if EXPR evaluates to true; fails if EXPR evaluates to + false or an invalid argument is given.`]],[`times`,[`times`,`Display process times. + Prints the accumulated user and system times for the shell and all of its + child processes. + Exit Status: + Always succeeds.`]],[`trap`,[`trap [-lp] [[arg] signal_spec ...]`,`Trap signals and other events. + Defines and activates handlers to be run when the shell receives signals + or other conditions. + Exit Status: + Returns success unless a SIGSPEC is invalid or an invalid option is given.`]],[`true`,[`true`,`Return a successful result. + Exit Status: + Always succeeds.`]],[`type`,[`type [-afptP] name [name ...]`,`Display information about command type. + For each NAME, indicate how it would be interpreted if used as a + command name. + + Options: + -a display all locations containing an executable named NAME + -f suppress shell function lookup + -P force a PATH search for each NAME, even if it is an alias, + builtin, or function, and returns the name of the disk file + that would be executed + -p returns either the name of the disk file that would be executed, + or nothing if \`type -t NAME' would not return \`file' + -t output a single word which is one of \`alias', \`keyword', + \`function', \`builtin', \`file' or \`', if NAME is an alias, + shell reserved word, shell function, shell builtin, disk file, + or not found, respectively + + Exit Status: + Returns success if all of the NAMEs are found; fails if any are not found.`]],[`typeset`,[`typeset [-aAfFgilnrtux] [-p] name[=value] ...`,`Set variable values and attributes. + A synonym for \`declare'.`]],[`ulimit`,[`ulimit [-SHabcdefiklmnpqrstuvxPT] [limit]`,`Modify shell resource limits. + Provides control over the resources available to the shell and processes + it creates, on systems that allow such control. + Exit Status: + Returns success unless an invalid option is supplied or an error occurs.`]],[`umask`,[`umask [-p] [-S] [mode]`,`Display or set file mode mask. + Sets the user file-creation mask to MODE. If MODE is omitted, prints + the current value of the mask. + Exit Status: + Returns success unless MODE is invalid or an invalid option is given.`]],[`unalias`,[`unalias [-a] name [name ...]`,`Remove each NAME from the list of defined aliases. + Exit Status: + Returns success unless a NAME is not an existing alias.`]],[`unset`,[`unset [-f] [-v] [-n] [name ...]`,`Unset values and attributes of shell variables and functions. + For each NAME, remove the corresponding variable or function. + + Options: + -f treat each NAME as a shell function + -v treat each NAME as a shell variable + -n treat each NAME as a name reference and unset the variable itself + rather than the variable it references + + Without options, unset first tries to unset a variable, and if that fails, + tries to unset a function. + Exit Status: + Returns success unless an invalid option is given or a NAME is read-only.`]],[`wait`,[`wait [-fn] [id ...]`,`Wait for job completion and return exit status. + Waits for each process identified by an ID, which may be a process ID or a + job specification, and reports its termination status. + Exit Status: + Returns the status of the last ID; fails if ID is invalid or an invalid + option is given.`]]]),L7=[...I7.keys()].sort();function $Me(e,t){let n=!1,r=[],i=0;for(;i1){for(let t=1;tt.test(e))}function tNe(){let e=[];e.push(`just-bash shell builtins`),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push(``);let t=L7.slice(),n=Math.ceil(t.length/2);for(let r=0;r0&&n.pipelines[0].commands.length>0){let t=n.pipelines[0].commands[0];t.type===`ArithmeticCommand`&&(r=await M8(e,t.expression.expression))}}catch(e){return Q(`bash: let: ${t}: ${e.message} +`)}return $(``,``,+(r===0))}sH();async function iNe(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength};if(e.state.localScopes.length===0)return Q(`bash: local: can only be used in a function +`);let r=e.state.localScopes[e.state.localScopes.length-1];for(e.state.localArrayScopes??=[];e.state.localArrayScopes.length{if(r.has(t)||r.set(t,e.state.env.get(t)),i&&!i.has(t)){let n=Z2(e,t);i.set(t,n?Y2(n):void 0)}},o=``,s=0,c=!1,l=!1,u=[];for(let e of t)if(e===`-n`)c=!0;else if(e===`-a`)l=!0;else if(e!==`-p`){if(e.startsWith(`-`)&&!e.includes(`=`))for(let t of e.slice(1))t===`n`?c=!0:t===`a`&&(l=!0);else u.push(e)}if(u.length===0){let t=``,n=Array.from(r.keys()).sort();for(let r of n){let n=e.state.env.get(r);n!==void 0&&(t+=`${r}=${n} +`)}return $(t,``,0)}for(let t of u){let i,u,d=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(d){i=d[1];let r=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)){o+=`bash: local: \`${t}': not a valid identifier +`,s=1;continue}B6(e,i,`bash`);let l=f5(r,n);e.executionScope.consumeWork(l.length,`local array assignment`),a(i),c4(e,i),$2(e,i,`indexed`);for(let t=0;t0&&(s=Math.max(...o)+1),i4(e,i,Array.from({length:r.length},(e,t)=>s+t));for(let t=0;t=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(i)){t=r.get(i);break}}}Zje(e,i,t)}if(!h){let t=e.state.env.get(i);if(e.state.tempEnvBindings)for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(i)){t=r.get(i);break}}r.set(i,t),l&&a(i)}if(l&&u===void 0)c4(e,i),$2(e,i,`indexed`);else if(u!==void 0){if(B6(e,i,`bash`),c&&u!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(u)){o+=`bash: local: \`${u}': invalid variable name for name reference +`,s=1;continue}e.state.env.set(i,u),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(i))}else{let t=e.state.tempEnvBindings?.some(e=>e.has(i));!h&&!t&&e.state.env.delete(i)}m5(e,i),c&&l6(e,i)}return $(``,o,s)}kB(),U();function aNe(e,t,n){let r=` +`,i=0,a=0,o=0,s=!1,c=`MAPFILE`,l=0;for(;l{if(V(t)>e.limits.maxStringLength)throw new H(`mapfile: string length limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);d.push(t)};for(;f=h)return $(``,`mapfile: array element limit exceeded (${h}) +`,1);g(e),p++}}break}let n=u.slice(f,t),a=n.indexOf(`\0`);if(a!==-1&&(n=n.substring(0,a)),!s&&r!==`\0`&&(n+=r),f=t+r.length,m0&&p>=i)break;if(d.length>=h)return $(``,`mapfile: array element limit exceeded (${h}) +`,1);g(n),p++}let _=new Set(a===0?[]:e.state.arrays?.get(c)?.elements.keys()??[]);for(let e=0;eh)return $(``,`mapfile: array element limit exceeded (${h}) +`,1);a===0&&c4(e,c);for(let t=0;t{let r=1;for(;r1&&e!==`--`){let t=m(e,f);if(t.nextArgIndex===-1)return{stdout:``,stderr:``,exitCode:2};if(t.nextArgIndex===-2)return{stdout:``,stderr:``,exitCode:1};f=t.nextArgIndex}else if(e===`--`)for(f++;f=0&&d.length===0&&h.add(`REPLY`);for(let t of h){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))return $(``,`bash: read: \`${t}': not a valid identifier +`,1);B6(e,t,`bash`)}if(u===0){if(c)c4(e,c);else{for(let t of d)e.state.env.set(t,``);d.length===0&&e.state.env.set(`REPLY`,``)}return $(``,``,0)}if(u<0&&u!==-1)return $(``,``,1);let g=n,_=P5(e,l),v=l>0&&(_?.kind!==`dup-in`||_.sourceFd!==0);if(v){let t=H5(e,l);if(`error`in t)return $(``,t.error===`write-only`||l===1||l===2?`bash: read: read error: ${l}: Bad file descriptor +`:`bash: read: ${l}: invalid file descriptor: Bad file descriptor +`,1);g=t.content}else!g&&e.state.groupStdin!==void 0&&(g=e.state.groupStdin);let y=a===``?`\0`:a,b=``,x=0,S=t=>{let n=V(t);if(n>e.limits.maxStringLength-x)throw new H(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`);b+=t,x+=n},C=t=>{if(V(t)>e.limits.maxStringLength)throw new H(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,`string_length`)},w=0,T=!0,E=t=>{v?U5(e,l,t):r>=0?U5(e,r,t):e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=g.substring(t),e.state.groupStdinSourceFd!==void 0&&U5(e,e.state.groupStdinSourceFd,t))};if(s>=0){let t=Math.min(s,g.length);b=g.substring(0,t),C(b),w=t,T=t>=s,E(w);let n=d[0]||`REPLY`;e.state.env.set(n,b);for(let t=1;t=0){let e=0,t=0,n=!1;for(;t=o||n,E(w)}else{w=0;let t=0;for(;t=g.length&&(T=!1,w=t,b.length===0&&g.length===0)){for(let t of d)e.state.env.set(t,``);return c&&c4(e,c),$(``,``,1)}E(w)}y===` +`&&b.endsWith(` +`)&&(b=b.slice(0,-1));let D=e=>i?e:e.replace(/\\(.)/g,`$1`);if(d.length===1&&d[0]===`REPLY`)return e.state.env.set(`REPLY`,D(b)),$(``,``,+!T);let O=e6(e.state.env),k=e.limits.maxArrayElements;if(c){let{words:t}=a6(b,O,k,void 0,i);c4(e,c);for(let n=0;n0){let e=t[0],r=Number.parseInt(e,10);if(e===``||Number.isNaN(r)||!/^-?\d+$/.test(e))return Q(`bash: return: ${e}: numeric argument required +`,2);n=(r%256+256)%256}throw new PB(n)}sH(),U();var R7=`set: usage: set [-eux] [+eux] [-o option] [+o option] +Options: + -e Exit immediately if a command exits with non-zero status + +e Disable -e + -u Treat unset variables as an error when substituting + +u Disable -u + -x Print commands and their arguments as they are executed + +x Disable -x + -o errexit Same as -e + +o errexit Disable errexit + -o nounset Same as -u + +o nounset Disable nounset + -o pipefail Return status of last failing command in pipeline + +o pipefail Disable pipefail + -o xtrace Same as -x + +o xtrace Disable xtrace +`,z7=new Map([[`e`,`errexit`],[`u`,`nounset`],[`x`,`xtrace`],[`v`,`verbose`],[`f`,`noglob`],[`C`,`noclobber`],[`a`,`allexport`],[`n`,`noexec`],[`h`,null],[`b`,null],[`m`,null],[`B`,null],[`H`,null],[`P`,null],[`T`,null],[`E`,null],[`p`,null]]),B7=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`allexport`,`allexport`],[`noexec`,`noexec`],[`posix`,`posix`],[`vi`,`vi`],[`emacs`,`emacs`],[`notify`,null],[`monitor`,null],[`braceexpand`,null],[`histexpand`,null],[`physical`,null],[`functrace`,null],[`errtrace`,null],[`privileged`,null],[`hashall`,null],[`ignoreeof`,null],[`interactive-comments`,null],[`keyword`,null],[`onecmd`,null]]),V7=[`errexit`,`nounset`,`pipefail`,`verbose`,`xtrace`,`posix`,`allexport`,`noclobber`,`noglob`,`noexec`,`vi`,`emacs`],H7=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`];function U7(e,t,n){t!==null&&(n&&(t===`vi`?e.state.options.emacs=!1:t===`emacs`&&(e.state.options.vi=!1)),e.state.options[t]=n,m4(e))}function cNe(e,t){return t+10&&t.append(` `),t.append(`[${a}]=`),t.reserve(_7(o)),t.append(v7(o))}t.append(`)`)}function uNe(e,t){if(/^[a-zA-Z0-9_]+$/.test(t)){e.append(t);return}e.reserve(_7(t)),e.append(v7(t))}function dNe(e,t,n){let r=l4(e,n);if(r.length===0){t.append(n).append(`=()`);return}t.append(n).append(`=(`);for(let i=0;i0&&t.append(` `),t.append(`[`),uNe(t,a),t.append(`]=`),t.reserve(_7(o)),t.append(v7(o))}t.append(` )`)}function fNe(e){let t=new Set,n=e.state.associativeArrays??new Set;for(let[r,i]of e.state.arrays??[])i.kind===`indexed`&&!n.has(r)&&t.add(r);return t}function pNe(e){return e.state.associativeArrays??new Set}function W7(e){let t=V7.map(t=>`${t.padEnd(16)}${e.state.options[t]?`on`:`off`}`),n=H7.map(e=>`${e.padEnd(16)}off`);return`${[...t,...n].sort().join(` +`)} +`}function G7(e){let t=V7.map(t=>`set ${e.state.options[t]?`-o`:`+o`} ${t}`),n=H7.map(e=>`set +o ${e}`);return`${[...t,...n].sort().join(` +`)} +`}function mNe(e,t){if(t.includes(`--help`))return I8(R7);if(t.length===0){let t=fNe(e),n=pNe(e),r=[];for(let[i,a]of e.state.env)/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&(t.has(i)||n.has(i)||r.push([i,a]));let i=[...r.map(([e,t])=>({kind:`scalar`,name:e,value:t})),...Array.from(t,e=>({kind:`indexed`,name:e})),...Array.from(n,e=>({kind:`associative`,name:e}))];i.sort((e,t)=>e.namet.name));let a=new oH(e.limits.maxOutputSize,`set`);for(let t of i)e.executionScope.consumeWork(1,`set variable listing`),t.kind===`scalar`?(a.append(t.name).append(`=`),a.reserve(jMe(t.value)),a.append(g7(t.value))):t.kind===`indexed`?lNe(e,a,t.name):dNe(e,a,t.name),a.append(` +`);return I8(a.build())}let n=[],r=()=>n.length>0?I8(n.join(``)):F8,i=0;for(;i1&&(a[0]===`-`||a[0]===`+`)&&a[1]!==`-`){let r=a[0]===`-`,o=0;for(let s=1;s0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<0){let n=`bash: shift: ${t[0]}: numeric argument required +`;if(e.state.options.posix)throw new WB(1,``,n);return Q(n)}n=r}let r=Number.parseInt(e.state.env.get(`#`)||`0`,10);if(n>r){let t=`bash: shift: shift count out of range +`;if(e.state.options.posix)throw new WB(1,``,t);return Q(t)}if(n===0)return F8;let i=[];for(let t=1;t<=r;t++)i.push(e.state.env.get(String(t))||``);let a=i.slice(n);for(let t=1;t<=r;t++)e.state.env.delete(String(t));for(let t=0;t0&&n[0]===`--`&&(n=n.slice(1)),n.length===0)return $(``,`bash: source: filename argument required +`,2);let r=n[0],i=null;if(r.includes(`/`)){let t=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(t)}catch{}}else{let t=(e.state.env.get(`PATH`)||``).split(`:`).filter(e=>e);for(let n of t){let t=e.fs.resolvePath(e.state.cwd,`${n}/${r}`);try{if((await e.fs.stat(t)).isDirectory)continue;i=await e.fs.readFile(t);break}catch{}}if(i===null){let t=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(t)}catch{}}}if(i===null)return Q(`bash: ${r}: No such file or directory +`);let a=new Map;if(n.length>1){for(let t=1;t<=9;t++)a.set(String(t),e.state.env.get(String(t)));a.set(`#`,e.state.env.get(`#`)),a.set(`@`,e.state.env.get(`@`));let t=n.slice(1);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `));for(let n=0;n{if(e.state.sourceDepth--,e.state.currentSource=o,n.length>1)for(let[t,n]of a)n===void 0?e.state.env.delete(t):e.state.env.set(t,n)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new H(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,`recursion`);e.state.currentSource=r;try{let t=T3(i),n=await e.executeScript(t);return s(),n}catch(e){if(s(),e instanceof LB)throw e;if(e instanceof PB)return $(e.stdout,e.stderr,e.exitCode);if(e.name===`ParseException`)return Q(`bash: ${r}: ${e.message} +`);throw e}}function q7(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function _Ne(e){return e.startsWith(`'`)&&e.endsWith(`'`)||e.startsWith(`"`)&&e.endsWith(`"`)}async function J7(e,t){if(_Ne(t))return null;try{return await M8(e,N4(new w3,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}function Y7(e,t){if(e.state.localVarStack?.has(t)){let n=_5(e,t);if(n){n.value===void 0?e.state.env.delete(t):e.state.env.set(t,n.value);let r=e.state.localVarStack?.get(t);if(!r||r.length===0)g5(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,n.scopeIndex),X7(e,t);else{let n=r[r.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,n.scopeIndex+1)}return!0}return e.state.env.delete(t),g5(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let n=e.state.localScopes.length-1;n>=0;n--){let r=e.state.localScopes[n];if(r.has(t)){let i=r.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),r.delete(t);let a=!1;for(let r=n-1;r>=0;r--)if(e.state.localScopes[r].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,r+1),a=!0;break}return a||g5(e,t),!0}}return!1}function X7(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function Z7(e,t){if(t.startsWith(`'`)&&t.endsWith(`'`))return t.slice(1,-1);if(t.startsWith(`"`)&&t.endsWith(`"`)){let n=t.slice(1,-1);return g8(e,new w3().parseWordFromString(n,!0,!1))}return t.includes(`$`)?g8(e,new w3().parseWordFromString(t,!1,!1)):t}async function vNe(e,t){let n=`both`,r=``,i=0;for(let a of t){if(a===`-v`){n=`variable`;continue}if(a===`-f`){n=`function`;continue}if(n===`function`){e.state.functions.delete(a);continue}if(n===`variable`){let t=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let n=t[1],a=t[2];if(z6(e,n)){r+=`bash: unset: ${n}: cannot unset: readonly variable +`,i=1;continue}if(a===`@`||a===`*`){o4(e,n),e.state.env.delete(n);continue}let o=e.state.associativeArrays?.has(n);if(o){a4(e,n,await Z7(e,a));continue}let s=v6(e,n),c=e.state.declaredVars?.has(n);if((e.state.env.has(n)||c)&&!s&&!o){r+=`bash: unset: ${n}: not an array variable +`,i=1;continue}let l=await J7(e,a);if(l===null&&s){r+=`bash: unset: ${a}: not a valid identifier +`,i=1;continue}if(l===null)continue;if(l<0){let t=_6(e,n),a=t.length,o=e.state.currentLine;if(a===0){r+=`bash: line ${o}: unset: [${l}]: bad array subscript +`,i=1;continue}let s=a+l;if(s<0){r+=`bash: line ${o}: unset: [${l}]: bad array subscript +`,i=1;continue}let c=t[s][0];a4(e,n,c);continue}a4(e,n,l);continue}if(!q7(a)){r+=`bash: unset: \`${a}': not a valid identifier +`,i=1;continue}let n=a;if(c6(e,a)){let t=p6(e,a);t&&t!==a&&(n=t)}if(z6(e,n)){r+=`bash: unset: ${n}: cannot unset: readonly variable +`,i=1;continue}o4(e,n);let o=h5(e,n);if(o!==void 0&&o!==e.state.callDepth)Y7(e,n);else if(e.state.fullyUnsetLocals?.has(n))e.state.env.delete(n);else if(o!==void 0){let t=e.state.accessedTempEnvVars?.has(n),r=e.state.mutatedTempEnvVars?.has(n);if((t||r)&&e.state.localVarStack?.has(n)){let t=_5(e,n);t?t.value===void 0?e.state.env.delete(n):e.state.env.set(n,t.value):e.state.env.delete(n)}else e.state.env.delete(n)}else X7(e,n)||e.state.env.delete(n);e.state.exportedVars?.delete(n);continue}let t=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let n=t[1],a=t[2];if(z6(e,n)){r+=`bash: unset: ${n}: cannot unset: readonly variable +`,i=1;continue}if(a===`@`||a===`*`){o4(e,n),e.state.env.delete(n);continue}let o=e.state.associativeArrays?.has(n);if(o){a4(e,n,await Z7(e,a));continue}let s=v6(e,n);if(e.state.env.has(n)&&!s&&!o){r+=`bash: unset: ${n}: not an array variable +`,i=1;continue}let c=await J7(e,a);if(c===null&&s){r+=`bash: unset: ${a}: not a valid identifier +`,i=1;continue}if(c===null)continue;if(c<0){let t=_6(e,n),a=t.length,o=e.state.currentLine;if(a===0){r+=`bash: line ${o}: unset: [${c}]: bad array subscript +`,i=1;continue}let s=a+c;if(s<0){r+=`bash: line ${o}: unset: [${c}]: bad array subscript +`,i=1;continue}let l=t[s][0];a4(e,n,l);continue}a4(e,n,c);continue}if(!q7(a)){r+=`bash: unset: \`${a}': not a valid identifier +`,i=1;continue}let o=a;if(c6(e,a)){let t=p6(e,a);t&&t!==a&&(o=t)}if(z6(e,o)){r+=`bash: unset: ${o}: cannot unset: readonly variable +`,i=1;continue}o4(e,o);let s=h5(e,o);if(s!==void 0&&s!==e.state.callDepth)Y7(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(s!==void 0){let t=e.state.accessedTempEnvVars?.has(o),n=e.state.mutatedTempEnvVars?.has(o);if((t||n)&&e.state.localVarStack?.has(o)){let t=_5(e,o);t?t.value===void 0?e.state.env.delete(o):e.state.env.set(o,t.value):e.state.env.delete(o)}else e.state.env.delete(o)}else X7(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(a)}return $(``,r,i)}XB(),U();function Q7(e,t,n,r){let i=n+V(t)+1;if(i>r)throw new H(`shopt: output size limit exceeded (${r} bytes)`,`output_size`);return e.push(t),i}var $7=[`extglob`,`dotglob`,`nullglob`,`failglob`,`globstar`,`globskipdots`,`nocaseglob`,`nocasematch`,`expand_aliases`,`lastpipe`,`xpg_echo`],yNe=`autocd.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.execfail.extdebug.extquote.force_fignore.globasciiranges.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath`.split(`.`);function e9(e){return $7.includes(e)}function bNe(e){return yNe.includes(e)}function xNe(e,t){let n=e.limits.maxArrayElements;if(t.length>n)throw new H(`shopt: argument limit exceeded (${n})`,`array_elements`);let r=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),i=!1,a=!1,o=!1,s=!1,c=!1,l=[],u=0;for(;u1){for(let t=1;t0?`${t.join(` +`)} +`:``,stderr:``}}let t=[];for(let n of $7){let r=e.state.shoptOptions[n];t.push(o?`shopt ${r?`-s`:`-u`} ${n}`:`${n} ${r?`on`:`off`}`)}return{exitCode:0,stdout:`${t.join(` +`)} +`,stderr:``}}let d=!1,f=[],p=0,m=[],h=0;for(let t of l){if(!e9(t)&&!bNe(t)){p=Q7(f,`shopt: ${t}: invalid shell option name`,p,r),d=!0;continue}if(i)e9(t)&&(e.state.shoptOptions[t]=!0,g4(e));else if(a)e9(t)&&(e.state.shoptOptions[t]=!1,g4(e));else if(e9(t)){let n=e.state.shoptOptions[t];s?n||(d=!0):o?(h=Q7(m,`shopt ${n?`-s`:`-u`} ${t}`,h,r),n||(d=!0)):(h=Q7(m,`${t} ${n?`on`:`off`}`,h,r),n||(d=!0))}else s?d=!0:o?(h=Q7(m,`shopt -u ${t}`,h,r),d=!0):(h=Q7(m,`${t} off`,h,r),d=!0)}return{exitCode:+!!d,stdout:m.length>0?`${m.join(` +`)} +`:``,stderr:f.length>0?`${f.join(` +`)} +`:``}}function SNe(e,t,n,r,i,a){let o=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),s=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`posix`,`posix`],[`allexport`,`allexport`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`noexec`,`noexec`],[`vi`,`vi`],[`emacs`,`emacs`]]),c=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`],l=[...s.keys(),...c].sort();if(t.length===0){let t=[];for(let a of l){let o=c.includes(a),l=s.get(a),u=o||!l?!1:e.state.options[l];n&&!u||r&&u||t.push(i?`set ${u?`-o`:`+o`} ${a}`:`${a} ${u?`on`:`off`}`)}return{exitCode:0,stdout:t.length>0?`${t.join(` +`)} +`:``,stderr:``}}let u=!1,d=[],f=0,p=[],m=0;for(let l of t){let t=s.has(l),h=c.includes(l);if(!t&&!h){f=Q7(d,`shopt: ${l}: invalid option name`,f,o),u=!0;continue}if(h){n||r||(a?u=!0:i?(m=Q7(p,`set +o ${l}`,m,o),u=!0):(m=Q7(p,`${l} off`,m,o),u=!0));continue}let g=s.get(l);if(g){if(n)g===`vi`?e.state.options.emacs=!1:g===`emacs`&&(e.state.options.vi=!1),e.state.options[g]=!0,m4(e);else if(r)e.state.options[g]=!1,m4(e);else{let t=e.state.options[g];a?t||(u=!0):i?(m=Q7(p,`set ${t?`-o`:`+o`} ${l}`,m,o),t||(u=!0)):(m=Q7(p,`${l} ${t?`on`:`off`}`,m,o),t||(u=!0))}}}return{exitCode:+!!u,stdout:p.length>0?`${p.join(` +`)} +`:``,stderr:d.length>0?`${d.join(` +`)} +`:``}}function t9(e,t){return e===`/bin/${t}`||e===`/usr/bin/${t}`}async function CNe(e,t,n){if(t.includes(`/`)){let n=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(n))return{error:`not_found`,path:n};try{let r=await e.fs.stat(n);if(r.isDirectory)return{error:`permission_denied`,path:n};let i=n.split(`/`).pop()||t,a=e.commands.get(i);return a&&t9(n,i)?{cmd:a,path:n}:r.mode&73?{script:!0,path:n}:{error:`permission_denied`,path:n}}catch{return{error:`not_found`,path:n}}}if(!n&&e.state.hashTable){let n=e.state.hashTable.get(t);if(n){try{let r=await e.fs.stat(n);if(!r.isDirectory){let i=e.commands.get(t);if(i&&t9(n,t))return{cmd:i,path:n};if(r.mode&73)return{script:!0,path:n}}}catch{}e.state.hashTable.delete(t)}}let r=(n??e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let n of r){if(!n)continue;let r=`${n.startsWith(`/`)?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(r))try{let n=await e.fs.stat(r);if(n.isDirectory)continue;let i=!!(n.mode&73),a=e.commands.get(t),o=t9(r,t);if(a&&o)return{cmd:a,path:r};if(i&&(a&&!o||!a))return{script:!0,path:r}}catch{}}if(!await e.fs.exists(`/usr/bin`)){let n=e.commands.get(t);if(n)return{cmd:n,path:`/usr/bin/${t}`}}return null}async function n9(e,t){let n=[];if(t.includes(`/`)){let r=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(r))try{let i=await e.fs.stat(r);i.isDirectory||i.mode&73&&n.push(t)}catch{}return n}let r=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let i of r){if(!i)continue;let r=`${i.startsWith(`/`)?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(t9(r,t)&&e.commands.has(t)){n.push(r);continue}if(await e.fs.exists(r)){try{let t=await e.fs.stat(r);if(t.isDirectory||!(t.mode&73))continue}catch{continue}n.push(i.startsWith(`/`)?r:`${i}/${t}`)}}return n}AK();function wNe(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function r9(e,t,n,r){return((...i)=>{OK(t,n,`${r} call`);let a=e(...i);return wNe(a)?a.then(e=>(OK(t,n,`${r} post-await`),e),e=>{throw OK(t,n,`${r} post-await`),e}):(OK(t,n,`${r} return`),a)})}function TNe(e,t,n){let r={readFile:r9(e.readFile.bind(e),t,n,`fs.readFile`),...typeof e.readFileBytes==`function`?{readFileBytes:r9(e.readFileBytes.bind(e),t,n,`fs.readFileBytes`)}:Object.create(null),readFileBuffer:r9(e.readFileBuffer.bind(e),t,n,`fs.readFileBuffer`),writeFile:r9(e.writeFile.bind(e),t,n,`fs.writeFile`),appendFile:r9(e.appendFile.bind(e),t,n,`fs.appendFile`),exists:r9(e.exists.bind(e),t,n,`fs.exists`),stat:r9(e.stat.bind(e),t,n,`fs.stat`),mkdir:r9(e.mkdir.bind(e),t,n,`fs.mkdir`),readdir:r9(e.readdir.bind(e),t,n,`fs.readdir`),rm:r9(e.rm.bind(e),t,n,`fs.rm`),cp:r9(e.cp.bind(e),t,n,`fs.cp`),mv:r9(e.mv.bind(e),t,n,`fs.mv`),resolvePath:r9(e.resolvePath.bind(e),t,n,`fs.resolvePath`),getAllPaths:r9(e.getAllPaths.bind(e),t,n,`fs.getAllPaths`),chmod:r9(e.chmod.bind(e),t,n,`fs.chmod`),symlink:r9(e.symlink.bind(e),t,n,`fs.symlink`),link:r9(e.link.bind(e),t,n,`fs.link`),readlink:r9(e.readlink.bind(e),t,n,`fs.readlink`),lstat:r9(e.lstat.bind(e),t,n,`fs.lstat`),realpath:r9(e.realpath.bind(e),t,n,`fs.realpath`),utimes:r9(e.utimes.bind(e),t,n,`fs.utimes`)};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=r9(e.readdirWithFileTypes.bind(e),t,n,`fs.readdirWithFileTypes`)),r}function i9(e,t){if(!e.requireDefenseContext)return e;let n=`command:${t}`,r=Object.getOwnPropertyDescriptors(e);r.fs={value:TNe(e.fs,e.requireDefenseContext,n),enumerable:!0,configurable:!0,writable:!0};let i=Object.defineProperties(Object.create(Object.getPrototypeOf(e)),r);return e.exec&&(i.exec=r9(e.exec,e.requireDefenseContext,n,`exec`)),e.origCommand&&(i.origCommand=r9(e.origCommand,e.requireDefenseContext,n,`origCommand`)),e.fetch&&(i.fetch=r9(e.fetch,e.requireDefenseContext,n,`fetch`)),e.sleep&&(i.sleep=r9(e.sleep,e.requireDefenseContext,n,`sleep`)),e.getRegisteredCommands&&(i.getRegisteredCommands=r9(e.getRegisteredCommands,e.requireDefenseContext,n,`getRegisteredCommands`)),i}U(),TV(),sH(),U(),U();var a9=`+ `;async function o9(e){let t=e.state.env.get(`PS4`);if(t===void 0)return a9;if(t===``)return``;let n=e.state.options.xtrace;e.state.options.xtrace=!1;try{return await g8(e,new w3().parseWordFromString(t,!1,!1))}catch(n){if(n instanceof RB&&!n.fatal)return t;if(n instanceof jB||n instanceof Error&&n.name===`AbortError`)throw n;return e.state.expansionStderr=`${e.state.expansionStderr||``}bash: ${t}: bad substitution +`,t||a9}finally{e.state.options.xtrace=n}}function ENe(e){return e.map(e=>DNe(e)).join(` `)}function DNe(e){if(e===``)return`''`;if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let t=/[\x00-\x1f\x7f]/.test(e),n=e.includes(` +`),r=e.includes(` `),i=e.includes(`\\`),a=e.includes(`'`);if(t||n||r||i){let t=``;for(let n of e){let e=n.charCodeAt(0);t+=n===` +`?`\\n`:n===` `?`\\t`:n===`\\`?`\\\\`:n===`'`?`'`:n===`"`?`"`:e<32||e===127?e<256?`\\x${e.toString(16).padStart(2,`0`)}`:`\\u${e.toString(16).padStart(4,`0`)}`:n}return`$'${t}'`}return a?`"${e.replace(/([\\$`"])/g,`\\$1`)}"`:`'${e}'`}async function ONe(e,t,n){return e.state.options.xtrace?`${await o9(e)}${ENe([t,...n])} +`:``}async function kNe(e,t,n){return e.state.options.xtrace?`${await o9(e)}${t}=${n} +`:``}function s9(e,t,n){return aH([t,n],``,e.limits.maxStringLength,`array assignment`)}async function ANe(e,t){let n=new Map,r=``;for(let i of t.assignments){let a=i.name;if(i.array){let o=await jNe(e,t,a,i.array,i.append,n);if(o.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:o.error};if(r+=o.xtraceOutput,o.continueToNext)continue}let o=i.value?await g8(e,i.value):``;if(a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:$(``,`bash: ${a}: bad array subscript +`,1)};let s=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let a=await INe(e,t,s[1],s[2],o,i.append,n);if(a.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:a.error};if(a.continueToNext)continue}let c=await LNe(e,t,a,o,i.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function jNe(e,t,n,r,i,a){let o=``;if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:``,error:$(``,`bash: ${n}: cannot assign list to array member +`,1)};if(c6(e,n)){let t=m6(e,n);if(t===void 0||t===``)throw new LB(1,``,``);let r=p6(e,n);if(r&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(r))return{continueToNext:!1,xtraceOutput:``,error:$(``,`bash: ${n}: cannot assign list to array member +`,1)}}if(z6(e,n)){if(t.name)return o+=`bash: ${n}: readonly variable +`,{continueToNext:!0,xtraceOutput:o};let r=B6(e,n);if(r)return{continueToNext:!1,xtraceOutput:``,error:r}}let s=e.state.associativeArrays?.has(n),c=Z2(e,n),l=c?Y2(c):void 0,u=e.state.env.get(n),d=()=>{e.state.arrays??=new Map,l?e.state.arrays.set(n,l):e.state.arrays.delete(n),u===void 0?e.state.env.delete(n):e.state.env.set(n,u)},f=MNe(r),p=()=>{c4(e,n),e.state.env.delete(n)};try{s&&f?await NNe(e,t,n,r,i,p,e=>{o+=e}):f?await PNe(e,n,r,i,p):await FNe(e,n,r,i,p)}catch(e){throw d(),e}if(t.name){a.set(n,e.state.env.get(n));let t=`(${r.map(e=>f4(e)).join(` `)})`;e.state.env.set(n,t)}return{continueToNext:!0,xtraceOutput:o}}function MNe(e){return e.some(e=>{if(e.parts.length>=2){let t=e.parts[0],n=e.parts[1];if(t.type!==`Glob`||!t.pattern.startsWith(`[`))return!1;if(t.pattern===`[`&&(n.type===`DoubleQuoted`||n.type===`SingleQuoted`)){if(e.parts.length<3)return!1;let t=e.parts[2];return t.type===`Literal`?t.value.startsWith(`]=`)||t.value.startsWith(`]+=`):!1}return n.type===`Literal`?n.value.startsWith(`]`)?n.value.startsWith(`]=`)||n.value.startsWith(`]+=`):t.pattern.endsWith(`]`)?n.value.startsWith(`=`)||n.value.startsWith(`+=`):!1:!1}return!1})}async function NNe(e,t,n,r,i,a,o){let s=[];for(let t of r){if(s.length>=e.limits.maxArrayElements)throw new H(`array element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);let n=d4(t);if(n){let{key:t,valueParts:r,append:i}=n,a;r.length>0?(a=await g8(e,{type:`Word`,parts:r}),r.every(e=>e.type===`Literal`||e.type===`TildeExpansion`)&&(a=J6(e,a))):a=``,s.push({type:`keyed`,key:t,value:a,append:i})}else{let n=await g8(e,t);s.push({type:`invalid`,expandedValue:n})}}e.executionScope.consumeWork(s.length,`associative array assignment`),i||a();for(let r of s)if(r.type===`keyed`){if(r.append){let t=t4(e,n,r.key)??``;r4(e,n,r.key,s9(e,t,r.value),`associative`)}else r4(e,n,r.key,r.value,`associative`)}else o(`bash: line ${t.line??e.state.currentLine??1}: ${n}: ${r.expandedValue}: must use subscript when assigning associative array +`)}async function PNe(e,t,n,r,i){let a=[],o=0;for(let t of n){let n=d4(t);if(n){if(o>=e.limits.maxArrayElements)throw new H(`array element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);let{key:t,valueParts:r,append:i}=n,s;r.length>0?(s=await g8(e,{type:`Word`,parts:r}),r.every(e=>e.type===`Literal`||e.type===`TildeExpansion`)&&(s=J6(e,s))):s=``,a.push({type:`keyed`,indexExpr:t,value:s,append:i}),o++}else{let n=await S8(e,t);if(n.values.length>e.limits.maxArrayElements-o)throw new H(`array element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);a.push({type:`non-keyed`,values:n.values}),o+=n.values.length}}e.executionScope.consumeWork(o,`indexed array assignment`),r||i();let s=0;for(let n of a)if(n.type===`keyed`){let r;try{r=await M8(e,N4(new w3,n.indexExpr).expression,!1)}catch{if(/^-?\d+$/.test(n.indexExpr))r=Number.parseInt(n.indexExpr,10);else{let t=e.state.env.get(n.indexExpr);r=t?Number.parseInt(t,10):0,Number.isNaN(r)&&(r=0)}}if(n.append){let i=t4(e,t,r)??``;r4(e,t,r,s9(e,i,n.value))}else r4(e,t,r,n.value);s=r+1}else for(let r of n.values)r4(e,t,s++,r)}async function FNe(e,t,n,r,i){let a=[];for(let t of n){let n=await S8(e,t);for(let t of n.values){if(a.length>=e.limits.maxArrayElements)throw new H(`array element limit exceeded (${e.limits.maxArrayElements})`,`array_elements`);a.push(t)}}let o=0;if(e.executionScope.consumeWork(a.length,`indexed array assignment`),r){let n=_6(e,t);if(n.length>0)o=Math.max(...n.map(([e])=>typeof e==`number`?e:0))+1;else{let n=e.state.env.get(t);n!==void 0&&(r4(e,t,0,n),e.state.env.delete(t),o=1)}}else i();for(let n=0;n=2&&(r=n.slice(1,-1));let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await M8(e,N4(new w3,r).expression,!1)}catch(r){if(r instanceof LB)throw r;if(r instanceof RB){let t=`bash: line ${e.state.currentLine}: ${n}: ${r.message} +`;if(r.fatal)throw new LB(1,``,t);return{index:0,error:$(``,t,1)}}let i=e.state.currentLine;return{index:0,error:$(``,`bash: line ${i}: ${t}[${n}]: bad array subscript +`,1)}}Number.isNaN(i)&&(i=0)}if(i<0){let r=_6(e,t);if(r.length===0){let r=e.state.currentLine;return{index:0,error:$(``,`bash: line ${r}: ${t}[${n}]: bad array subscript +`,1)}}if(i=Math.max(...r.map(([e])=>typeof e==`number`?e:0))+1+i,i<0){let r=e.state.currentLine;return{index:0,error:$(``,`bash: line ${r}: ${t}[${n}]: bad array subscript +`,1)}}}return{index:i}}async function LNe(e,t,n,r,i,a){let o=``,s=n,c=null;if(c6(e,n)){let t=h6(e,n,r);if(t===void 0)return{continueToNext:!1,xtraceOutput:``,error:$(``,`bash: ${n}: circular name reference +`,1)};if(t===null)return{continueToNext:!0,xtraceOutput:``};s=t;let i=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);i&&(c={arrayName:i[1],subscriptExpr:i[2]},s=i[1])}if(z6(e,s)){if(t.name)return o+=`bash: ${s}: readonly variable +`,{continueToNext:!0,xtraceOutput:o};let n=B6(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let l;if(D7(e,s))try{let t=new w3;if(i){let n=N4(t,`(${e.state.env.get(s)||`0`}) + (${r})`);l=String(await M8(e,n.expression))}else{let n=N4(t,r);l=String(await M8(e,n.expression))}}catch{l=`0`}else{let t=v6(e,s)?t4(e,s,0):e.state.env.get(s);l=i?s9(e,t||``,r):r}l=A7(e,s,l),o+=await kNe(e,s,l);let u;return c?u=await RNe(e,c):v6(e,s)&&(u=`0`),t.name?u===void 0&&(a.set(s,e.state.env.get(s)),e.state.env.set(s,l)):(u===void 0?e.state.env.set(s,l):r4(e,s,u,l),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s)),e.state.tempEnvBindings?.some(e=>e.has(s))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(s))),{continueToNext:!1,xtraceOutput:o}}async function RNe(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return c9(e,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await M8(e,N4(new w3,r).expression,!1)}catch{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let t=_6(e,n);t.length>0&&(i=Math.max(...t.map(e=>e[0]))+1+i)}return String(i)}async function zNe(e,t,n,r){let i=!1,a=!1,o=!1,s=!1,c=!1,l=[];for(let e of t)if(e.startsWith(`-`)&&e.length>1)for(let t of e.slice(1))t===`t`?i=!0:t===`p`?a=!0:t===`P`?o=!0:t===`a`?s=!0:t===`f`&&(c=!0);else l.push(e);let u=``,d=``,f=0,p=!1,m=!1;for(let t of l){let l=!1;if(o){if(s){let e=await r(t);if(e.length>0){for(let t of e)u+=`${t} +`;p=!0,l=!0}}else{let e=await n(t);e&&(u+=`${e} +`,p=!0,l=!0)}l||(m=!0);continue}let f=!c&&e.state.functions.has(t);if(s&&f){if(!a){if(i)u+=`function +`;else{let n=e.state.functions.get(t),r=n?u9(t,n):`${t} is a function +`;u+=r}}l=!0}let h=e.state.env.get(`BASH_ALIAS_${t}`);if(!(h!==void 0&&(s||!l)&&(a||(u+=i?`alias +`:`${t} is aliased to \`${h}' +`),l=!0,!s)||y5.has(t)&&(s||!l)&&(a||(u+=i?`keyword +`:`${t} is a shell keyword +`),l=!0,!s))){if(!s&&f&&!l){if(!a){if(i)u+=`function +`;else{let n=e.state.functions.get(t),r=n?u9(t,n):`${t} is a function +`;u+=r}}l=!0;continue}if(!(b5.has(t)&&(s||!l)&&(a||(u+=i?`builtin +`:`${t} is a shell builtin +`),l=!0,!s))){if(s){let e=await r(t);for(let n of e)u+=a?`${n} +`:i?`file +`:`${t} is ${n} +`,p=!0,l=!0}else if(!l){let e=await n(t);e&&(u+=a?`${e} +`:i?`file +`:`${t} is ${e} +`,p=!0,l=!0)}if(!l&&(m=!0,!i&&!a)){let n=!0;if(t.includes(`/`)){let r=e.fs.resolvePath(e.state.cwd,t);await e.fs.exists(r)&&(n=!1)}n&&(d+=`bash: type: ${t}: not found +`)}}}}return f=a?m&&!p?1:0:+!!m,$(u,d,f)}function u9(e,t){let n;return n=t.body.type===`Group`?t.body.body.map(e=>d9(e)).join(`; `):d9(t.body),`${e} is a function +${e} () +{ + ${n} +} +`}function d9(e){if(Array.isArray(e))return e.map(e=>d9(e)).join(`; `);if(e.type===`Statement`){let t=[];for(let n=0;nd9(e)).join(`; `)}; }`:`...`}function f9(e){return e.parts.map(p9).join(``)}function p9(e){switch(e.type){case`Literal`:return e.value;case`Escaped`:return`\\${e.value}`;case`SingleQuoted`:return`'${e.value}'`;case`DoubleQuoted`:return`"${e.parts.map(p9).join(``)}"`;default:return k3(X.word([e]))}}function BNe(e){let t=e.commands.map(e=>d9(e));return(e.negated?`! `:``)+t.join(` | `)}async function VNe(e,t,n,r){let i=``,a=``,o=0;for(let n of t){if(!n){o=1;continue}let t=e.state.env.get(`BASH_ALIAS_${n}`);if(t!==void 0)i+=r?`${n} is an alias for "${t}" +`:`alias ${n}='${t}' +`;else if(y5.has(n))i+=r?`${n} is a shell keyword +`:`${n} +`;else if(b5.has(n))i+=r?`${n} is a shell builtin +`:`${n} +`;else if(e.state.functions.has(n))i+=r?`${n} is a function +`:`${n} +`;else if(n.includes(`/`)){let t=e.fs.resolvePath(e.state.cwd,n),s=!1;if(await e.fs.exists(t))try{let a=await e.fs.stat(t);a.isDirectory||a.mode&73&&(i+=r?`${n} is ${n} +`:`${n} +`,s=!0)}catch{}s||(r&&(a+=`${n}: not found +`),o=1)}else if(e.commands.has(n)){let t=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`),a=null;for(let r of t){if(!r)continue;let t=`${r}/${n}`;try{let n=await e.fs.stat(t);if(!n.isDirectory&&n.mode&73){a=t;break}}catch{}}a||=`/usr/bin/${n}`,i+=r?`${n} is ${a} +`:`${a} +`}else r&&(a+=`${n}: not found +`),o=1}return $(i,a,o)}async function HNe(e,t){if(t.includes(`/`)){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let t=await e.fs.stat(n);if(t.isDirectory||!(t.mode&73))return null}catch{return null}return t}return null}let n=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let r of n){if(!r)continue;let n=`${r.startsWith(`/`)?r:e.fs.resolvePath(e.state.cwd,r)}/${t}`;if(await e.fs.exists(n)){try{let t=await e.fs.stat(n);if(t.isDirectory||!(t.mode&73))continue}catch{continue}return`${r}/${t}`}}if(e.commands.has(t)){for(let e of n)if(e===`/usr/bin`||e===`/bin`)return`${e}/${t}`;return`/usr/bin/${t}`}return null}function m9(e,t){let n=!0,r=e.signal?new AbortController:void 0,i=new WeakMap,a=()=>{if(!n)throw new HB(``,`bash: ${t} used its context after cancellation +`)},o=e=>{if(e===null||typeof e!=`object`&&typeof e!=`function`)return e;let n=i.get(e);if(n!==void 0)return n;if(typeof e==`object`&&KDe(e))return e;if(e instanceof Uint8Array){let t=new Uint8Array(e);return i.set(e,t),t}if(e instanceof ArrayBuffer){let t=e.slice(0);return i.set(e,t),t}if(e instanceof Promise){let t=e.then(e=>(a(),o(e)));return i.set(e,t),t}if(typeof e==`function`){let t=function(...t){return a(),o(Reflect.apply(e,this,t))};return i.set(e,t),t}let r=Object.getPrototypeOf(e);if(Array.isArray(e)||r===Object.prototype||r===null){let t=Array.isArray(e)?[]:Object.create(r);i.set(e,t);let n=Object.getOwnPropertyDescriptors(e);for(let t of Object.values(n)){if(`value`in t){let n=t.value;t.value=typeof n==`function`?(...t)=>(a(),o(Reflect.apply(n,e,t))):o(n)}if(t.get){let n=t.get;t.get=()=>(a(),o(Reflect.apply(n,e,[])))}if(t.set){let n=t.set;t.set=t=>{a(),Reflect.apply(n,e,[t])}}}return Object.defineProperties(t,n),t}let s=new Map,c=new p$(e,{get(e,n){if(a(),n===`constructor`||n===`prototype`||n===`__proto__`)throw Error(`${t}: unsafe context property access`);let r=Reflect.get(e,n,e);if(typeof r!=`function`)return o(r);if(s.has(n))return s.get(n);let i=(...t)=>(a(),o(Reflect.apply(r,e,t)));return s.set(n,i),i},set(e,n,r){if(a(),n===`constructor`||n===`prototype`||n===`__proto__`)throw Error(`${t}: unsafe context property access`);return Reflect.set(e,n,r,e)}});return i.set(e,c),c},s=e=>o(e),c=e=>e&&((...t)=>(a(),o(e(...t)))),l=e=>({value:e,enumerable:!0,configurable:!0,writable:!0}),u=Object.getOwnPropertyDescriptors(e);return Object.assign(u,{fs:l(s(e.fs)),env:l(s(e.env)),limits:l(Object.freeze({...e.limits})),exportedEnv:l(e.exportedEnv?Object.freeze({...e.exportedEnv}):void 0),executionScope:l(e.executionScope?s(e.executionScope):void 0),fileDescriptors:l(e.fileDescriptors?s(e.fileDescriptors):void 0),coverage:l(e.coverage?s(e.coverage):void 0),assignShellVariable:l(c(e.assignShellVariable)),exec:l(c(e.exec)),origCommand:l(c(e.origCommand)),execWithInheritedStdin:l(c(e.execWithInheritedStdin)),fetch:l(c(e.fetch)),getRegisteredCommands:l(c(e.getRegisteredCommands)),sleep:l(c(e.sleep)),trace:l(c(e.trace)),invokeTool:l(c(e.invokeTool)),signal:l(r?.signal)}),{context:Object.defineProperties(Object.create(Object.getPrototypeOf(e)),u),revoke(){n=!1,r?.signal.aborted||r?.abort(new HB(``,`bash: ${t} context revoked +`))}}}async function UNe(e,t,n,r,i,a){let o=i.remainingTimeMs()??t.limits.maxExecutionTimeMs,s=t.limits.maxExtensionCleanupTimeMs,c,l,u,d=Promise.resolve().then(e).then(e=>({kind:`result`,result:e}),e=>({kind:`error`,error:e})),f=new Promise(e=>{let t=()=>{n(),e({kind:`abort`})};l=t,a?.addEventListener(`abort`,t,{once:!0}),a?.aborted&&t(),c=sB(()=>{n(),e({kind:`deadline`})},o)});try{let e=await Promise.race([d,f]);if(e.kind===`result`)return e.result;if(e.kind===`error`)throw e.error;n();let t=await Promise.race([d.then(()=>!0),new Promise(e=>{u=sB(()=>e(!1),s)})]),a=e.kind===`deadline`?new HB(``,`bash: ${r} exceeded its execution deadline +`):new HB(``,`bash: execution aborted +`);throw t||i.poisonAfterAbort(a),a}finally{n(),cB(c),cB(u),l&&a?.removeEventListener(`abort`,l)}}async function WNe(e,t,n,r,i,a,o,s,c=!1){let{ctx:l,runCommand:u}=e;if(l.coverage&&b5.has(t)&&l.coverage.hit(`bash:builtin:${t}`),t===`export`)return ZMe(l,n);if(t===`unset`)return vNe(l,n);if(t===`exit`)return XMe(l,n);if(t===`local`)return iNe(l,n);if(t===`set`)return mNe(l,n);if(t===`break`)return Fje(l,n);if(t===`continue`)return FMe(l,n);if(t===`return`)return sNe(l,n);if(t===`eval`&&l.state.options.posix)return P7(l,n,i,c);if(t===`shift`)return hNe(l,n);if(t===`getopts`)return F7(l,n);if(t===`compgen`)return gMe(l,n);if(t===`complete`)return NMe(l,n);if(t===`compopt`)return PMe(l,n);if(t===`pushd`)return await qMe(l,n);if(t===`popd`)return JMe(l,n);if(t===`dirs`)return YMe(l,n);if(t===`source`||t===`.`)return gNe(l,n);if(t===`read`)return oNe(l,n,i,s);if(t===`mapfile`||t===`readarray`)return aNe(l,n,i);if(t===`declare`||t===`typeset`)return WMe(l,n);if(t===`readonly`)return GMe(l,n);if(!a){let e=l.state.functions.get(t);if(e)return a7(l,e,n,i,void 0,c)}if(t===`__just_bash_tee_restore`){if(n.length===0||n.length>l.limits.maxArrayElements)return Q(`bash: invalid internal pipeline status restore +`,2);let e=[];for(let t of n){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(t))return Q(`bash: invalid internal pipeline status restore +`,2);let n=Number(t);if(!Number.isSafeInteger(n)||n>255)return Q(`bash: invalid internal pipeline status restore +`,2);e.push(n)}let t=e[e.length-1]??0,r=[...e].reverse().find(e=>e!==0);return{stdout:``,stderr:``,exitCode:l.state.options.pipefail&&r!==void 0?r:t,internalPipeStatusOverride:e}}if(t===`eval`)return P7(l,n,i,c);if(t===`cd`)return await Ije(l,n);if(t===`:`||t===`true`)return F8;if(t===`false`)return L8(!1);if(t===`let`)return rNe(l,n);if(t===`command`)return GNe(e,n,i,c);if(t===`builtin`)return KNe(e,n,i,c);if(t===`shopt`)return xNe(l,n);if(t===`exec`){if(n.length===0)return F8;let[e,...t]=n;return{...await u(e,t,[],i,!1,!1,-1,c),internalProducerOmitsShellPrefix:!0}}if(t===`wait`)return F8;if(t===`type`)return await zNe(l,n,e=>HNe(l,e),e=>n9(l,e));if(t===`hash`)return QMe(l,n);if(t===`help`)return $Me(l,n);if(t===`[`||t===`test`){let e=n;if(t===`[`){if(n[n.length-1]!==`]`)return Q(`[: missing \`]' +`,2);e=n.slice(0,-1)}return Q8(l,e)}return null}async function GNe(e,t,n,r=!1){let{ctx:i,runCommand:a}=e;if(t.length===0)return F8;let o=!1,s=!1,c=!1,l=t;for(;l.length>0&&l[0].startsWith(`-`);){let e=l[0];if(e===`--`){l=l.slice(1);break}for(let t of e.slice(1))t===`p`?o=!0:t===`V`?s=!0:t===`v`&&(c=!0);l=l.slice(1)}if(l.length===0)return F8;if(c||s)return await VNe(i,l,c,s);let[u,...d]=l;return a(u,d,[],n,!0,o,-1,r)}async function KNe(e,t,n,r=!1){let{runCommand:i}=e;if(t.length===0)return F8;let a=t;if(a[0]===`--`&&(a=a.slice(1),a.length===0))return F8;let o=a[0];if(o!==`__just_bash_tee_restore`&&!b5.has(o))return Q(`bash: builtin: ${o}: not a shell builtin +`);let[,...s]=a;return i(o,s,[],n,!0,!1,-1,r)}async function qNe(e,t,n,r,i){let{ctx:a,buildExportedEnv:o,executeUserScript:s}=e,c=await CNe(a,t,i?`/usr/bin:/bin`:void 0);if(!c)return Nje(t)?Q(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle. +`,127):Q(`bash: ${t}: command not found +`,127);if(`error`in c)return c.error===`permission_denied`?Q(`bash: ${t}: Permission denied +`,126):Q(`bash: ${t}: No such file or directory +`,127);if(`script`in c)return t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,c.path)),await s(c.path,n,r);let{cmd:l,path:u}=c;t.includes(`/`)||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,u));let d=r||a.state.groupStdin||``,f=!1,p=o();a.state.fileDescriptors??=new Map;let m={fs:a.fs,fsIdentity:GDe(a.fs),cwd:a.state.cwd,env:a.state.env,assignShellVariable:async(e,t,n)=>{if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))throw Error(`${e}: not a valid identifier`);let r=n===void 0?e:`${e}[${n}]`,i=h6(a,e,t);if(i===void 0)throw Error(`${e}: circular name reference`);if(i===null)return;let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(?:\[(.*)\])?$/);if(!o)throw Error(`${r}: not a valid identifier`);let s=o[1],c=o[2]??n;if(z6(a,e)||z6(a,s))throw Error(`${s}: readonly variable`);if(c===void 0)a.state.env.set(s,t);else{let e=a.state.associativeArrays?.has(s)?`associative`:`indexed`;if(e===`associative`){r4(a,s,c,t,e);return}let n=await l9(a,s,c);if(n.error)throw new LB(n.error.exitCode,n.error.stdout,n.error.stderr);r4(a,s,n.index,t,e)}},exportedEnv:p,get stdin(){return f=!0,d},limits:a.limits,executionScope:l.internalIsExtension?QDe(a.executionScope):a.executionScope,exec:(e,t)=>a.execFn(e,t,!1),execWithInheritedStdin:(e,t)=>a.execFn(e,{...t,stdin:d,stdinKind:`bytes`},!0),fetch:a.fetch,getRegisteredCommands:()=>Array.from(a.commands.keys()),sleep:a.sleep,trace:a.trace,fileDescriptors:a.state.fileDescriptors,xpgEcho:a.state.shoptOptions.xpg_echo,coverage:a.coverage,signal:a.state.signal,requireDefenseContext:a.requireDefenseContext,jsBootstrapCode:a.jsBootstrapCode,invokeTool:a.invokeTool},h=l.internalOriginalCommand,g=()=>{};if(h){let e=Object.getOwnPropertyDescriptors(m);e.executionScope={value:a.executionScope,enumerable:!0,configurable:!0,writable:!0};let t=m9(Object.defineProperties(Object.create(Object.getPrototypeOf(m)),e),h.name),n=i9(t.context,h.name);g=t.revoke,m.origCommand=e=>{let t=()=>h.execute(e,n);return h.trusted?iB.runTrustedAsync(t):iB.runUntrustedAsync(t)}}let _=m9(m,t),v=i9(_.context,t),y=()=>{_.revoke(),g()};try{let e=()=>kK(a.requireDefenseContext,`command`,`${t} execution`,()=>l.execute(n,v)),i=()=>UNe(e,v,y,t,a.executionScope,a.state.signal),o=l.trusted?await iB.runTrustedAsync(i):await i();return{...o,internalStdinConsumed:o.internalStdinConsumed??(f?r.length:0)}}catch(e){if(e instanceof H||e instanceof HB||e instanceof eB)throw e;return Q(`${t}: ${_H(wV(e))} +`)}}kB(),U(),oX();async function h9(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r=new aX(e.executionScope,`condition`),i=0;try{for(let n of t){let t=await e.executeStatement(n);r.appendResult(t),i=t.exitCode}}catch(e){throw r.prependTo(e),e}finally{e.state.inCondition=n}return r.build(i)}TV(),U(),TV();function g9(e,t,n,r){if(e instanceof MB)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:`rethrow`,stdout:t,stderr:n,error:e}):{action:`break`,stdout:t,stderr:n};if(e instanceof NB)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:`rethrow`,stdout:t,stderr:n,error:e}):{action:`continue`,stdout:t,stderr:n};if(e instanceof PB||e instanceof FB||e instanceof LB||e instanceof H)return e.prependOutput(t,n),{action:`rethrow`,stdout:t,stderr:n,error:e};let i=wV(e);return{action:`error`,stdout:t,stderr:`${n}${i} +`,exitCode:1}}function _9(e,t){return e===void 0?t===``?{owns:!1}:{owns:!0,stdin:t}:{owns:!0,stdin:e}}var v9=class{ctx;stdoutChunks=[];stderrChunks=[];totalBytes=0;constructor(e){this.ctx=e}append(e,t){let n=V(e)+V(t);n>this.ctx.limits.maxOutputSize-this.totalBytes&&R8(`total output size exceeded (>${this.ctx.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,`output_size`),e&&this.stdoutChunks.push(e),t&&this.stderrChunks.push(t),this.totalBytes+=n}appendUnaccounted(e,t){this.ctx.executionScope.appendOutput(`stdout`,e,`control-flow`),this.ctx.executionScope.appendOutput(`stderr`,t,`control-flow`),this.append(e,t)}replace(e,t){this.stdoutChunks=[],this.stderrChunks=[],this.totalBytes=0,this.append(e,t)}get stdout(){return this.stdoutChunks.join(``)}get stderr(){return this.stderrChunks.join(``)}build(e){let t=this.stdout,n=this.stderr;return{stdout:t,stderr:n,exitCode:e,internalOutputAccounting:{stdout:V(t),stderr:V(n)}}}};async function y9(e,t,n){let r=0;try{for(let i of t){let t=await e.executeStatement(i);n.append(t.stdout,t.stderr),r=t.exitCode}}catch(e){if(AB(e)||e instanceof FB||e instanceof LB||e instanceof H||e instanceof UB)throw e.prependOutput(n.stdout,n.stderr),e;return n.appendUnaccounted(``,`${wV(e)} +`),n.build(1)}return n.build(r)}async function JNe(e,t){return r7(e,t.redirections,``,()=>YNe(e,t))}async function YNe(e,t){let n=new v9(e);for(let r of t.clauses){let t=await h9(e,r.condition);if(n.append(t.stdout,t.stderr),t.exitCode===0)return y9(e,r.body,n)}return t.elseBody?y9(e,t.elseBody,n):n.build(0)}async function XNe(e,t){return r7(e,t.redirections,``,()=>ZNe(e,t))}async function ZNe(e,t){let n=new v9(e),r=0,i=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return Q(`bash: \`${t.variable}': not a valid identifier +`);let a=[];if(t.words===null)a=(e.state.env.get(`@`)||``).split(` `).filter(Boolean);else if(t.words.length===0)a=[];else try{for(let n of t.words){let t=await S8(e,n);Y6(a,t.values,e.limits.maxArrayElements,`for-loop expansion`)}}catch(e){if(e instanceof BB)return{stdout:``,stderr:e.stderr,exitCode:1};throw e}e.state.loopDepth++;try{for(let o of a){i++,i>e.limits.maxLoopIterations&&R8(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,n.stdout,n.stderr),e.state.env.set(t.variable,o);try{for(let i of t.body){let t=await e.executeStatement(i);n.append(t.stdout,t.stderr),r=t.exitCode}}catch(t){let r=g9(t,n.stdout,n.stderr,e.state.loopDepth);if(n.replace(r.stdout,r.stderr),r.action===`break`)break;if(r.action===`continue`)continue;if(r.action===`error`)return n.build(r.exitCode??1);throw r.error}}}finally{e.state.loopDepth--}return n.build(r)}async function QNe(e,t){return r7(e,t.redirections,``,()=>$Ne(e,t))}async function $Ne(e,t){let n=t.line;n!==void 0&&(e.state.currentLine=n);let r=new v9(e),i=0,a=0;t.init&&await M8(e,t.init.expression),e.state.loopDepth++;try{for(;a++,a>e.limits.maxLoopIterations&&R8(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,r.stdout,r.stderr),!(t.condition&&(n!==void 0&&(e.state.currentLine=n),await M8(e,t.condition.expression)===0));){try{for(let n of t.body){let t=await e.executeStatement(n);r.append(t.stdout,t.stderr),i=t.exitCode}}catch(n){let i=g9(n,r.stdout,r.stderr,e.state.loopDepth);if(r.replace(i.stdout,i.stderr),i.action===`break`)break;if(i.action===`continue`){t.update&&await M8(e,t.update.expression);continue}if(i.action===`error`)return r.build(i.exitCode??1);throw i.error}t.update&&await M8(e,t.update.expression)}}finally{e.state.loopDepth--}return r.build(i)}async function ePe(e,t,n=``){return r7(e,t.redirections,n,r=>tPe(e,t,n,r))}async function tPe(e,t,n,r){let i=new v9(e),a=0,o=0,s=_9(r.stdin,n),c=e.state.groupStdin;s.owns&&(e.state.groupStdin=s.stdin),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&R8(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,i.stdout,i.stderr);let n=0,r=!1,s=!1,c=e.state.inCondition;e.state.inCondition=!0;try{for(let r of t.condition){let t=await e.executeStatement(r);i.append(t.stdout,t.stderr),n=t.exitCode}}catch(t){if(t instanceof MB){if(i.append(t.stdout,t.stderr),t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=i.stdout,t.stderr=i.stderr,e.state.inCondition=c,t;r=!0}else if(t instanceof NB){if(i.append(t.stdout,t.stderr),t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=i.stdout,t.stderr=i.stderr,e.state.inCondition=c,t;s=!0}else throw e.state.inCondition=c,t}finally{e.state.inCondition=c}if(r)break;if(!s){if(n!==0)break;try{for(let n of t.body){let t=await e.executeStatement(n);i.append(t.stdout,t.stderr),a=t.exitCode}}catch(t){let n=g9(t,i.stdout,i.stderr,e.state.loopDepth);if(i.replace(n.stdout,n.stderr),n.action===`break`)break;if(n.action===`continue`)continue;if(n.action===`error`)return i.build(n.exitCode??1);throw n.error}}}}finally{e.state.loopDepth--,s.owns&&(e.state.groupStdin=c)}return i.build(a)}async function nPe(e,t,n=``){return r7(e,t.redirections,n,r=>rPe(e,t,n,r))}async function rPe(e,t,n,r){let i=new v9(e),a=0,o=0,s=_9(r.stdin,n),c=e.state.groupStdin;s.owns&&(e.state.groupStdin=s.stdin),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&R8(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,i.stdout,i.stderr);let n=await h9(e,t.condition);if(i.append(n.stdout,n.stderr),n.exitCode===0)break;try{for(let n of t.body){let t=await e.executeStatement(n);i.append(t.stdout,t.stderr),a=t.exitCode}}catch(t){let n=g9(t,i.stdout,i.stderr,e.state.loopDepth);if(i.replace(n.stdout,n.stderr),n.action===`break`)break;if(n.action===`continue`)continue;if(n.action===`error`)return i.build(n.exitCode??1);throw n.error}}}finally{e.state.loopDepth--,s.owns&&(e.state.groupStdin=c)}return i.build(a)}async function iPe(e,t){return r7(e,t.redirections,``,()=>aPe(e,t))}async function aPe(e,t){let n=new v9(e),r=0,i=await g8(e,t.word),a=!1;for(let o=0;o1,d=e.state.lastArg,f=e.state.groupStdin,p=e.state.groupStdinSourceFd;for(let r=0;r1)y={stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode};else if(n instanceof FB&&t.commands.length>1)y={stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode};else throw _&&(e.state.env=_,e.state.arrays=v??new Map),n}finally{u&&(h&&(f=e.state.groupStdin,p=e.state.groupStdinSourceFd),e.state.groupStdin=f,e.state.groupStdinSourceFd=p)}if(_&&(e.state.env=_,e.state.arrays=v??new Map),y=e.executionScope.accountResult(y,`pipeline`,e.executionScope.outputBytesUsed-b),!m){let n=t.pipeStderr?.[r]??!1,i=y.internalOutputAccounting?.stdout??0,a=n?y.internalOutputAccounting?.stderr??0:0;$De(e.executionScope,i+a,`pipeline`),y={...y,internalOutputAccounting:{stdout:0,stderr:n?0:y.internalOutputAccounting?.stderr??0}}}s.push(y.exitCode),y.exitCode!==0&&(o=y.exitCode),m?a=y:(t.pipeStderr?.[r]??!1?i=yB(y.stderr)+CB(y):(i=CB(y),c+=y.stderr,l+=y.internalOutputAccounting?.stderr??0),a={stdout:``,stderr:``,exitCode:y.exitCode})}c&&(a={...a,stderr:c+a.stderr,internalOutputAccounting:{stdout:a.internalOutputAccounting?.stdout??0,stderr:l+(a.internalOutputAccounting?.stderr??0)}});let m=t.commands.length>1||t.commands.length===1&&t.commands[0].type===`SimpleCommand`,h=a.internalPipeStatusOverride??s;if(m){c4(e,`PIPESTATUS`);for(let t=0;t[e,x9(t)])):void 0}function cPe(e){if(!e)return;let t=new Map,n=new Map;for(let[r,i]of e){let e=t.get(i);e||(e=new Set(i),t.set(i,e)),n.set(r,e)}return n}function lPe(e){return e?.map(e=>new Map(Array.from(e,([e,t])=>[e,t?{kind:t.kind,elements:new Map(t.elements)}:void 0])))}function uPe(e){return e?new Map(Array.from(e,([e,t])=>[e,t.map(e=>({...e}))])):void 0}function S9(e){let t={env:e.env,arrays:e.arrays,cwd:e.cwd,previousDir:e.previousDir,lastExitCode:e.lastExitCode,lastArg:e.lastArg,currentLine:e.currentLine,options:e.options,shoptOptions:e.shoptOptions,fileDescriptors:e.fileDescriptors,inputFds:e.inputFds,fdAliases:e.fdAliases,closedStandardFds:e.closedStandardFds,nextFd:e.nextFd,readonlyVars:e.readonlyVars,associativeArrays:e.associativeArrays,namerefs:e.namerefs,boundNamerefs:e.boundNamerefs,invalidNamerefs:e.invalidNamerefs,integerVars:e.integerVars,lowercaseVars:e.lowercaseVars,uppercaseVars:e.uppercaseVars,exportedVars:e.exportedVars,tempExportedVars:e.tempExportedVars,localExportedVars:e.localExportedVars,declaredVars:e.declaredVars,localScopes:e.localScopes,localArrayScopes:e.localArrayScopes,localVarDepth:e.localVarDepth,localVarStack:e.localVarStack,fullyUnsetLocals:e.fullyUnsetLocals,tempEnvBindings:e.tempEnvBindings,mutatedTempEnvVars:e.mutatedTempEnvVars,accessedTempEnvVars:e.accessedTempEnvVars,functions:e.functions,callDepth:e.callDepth,sourceDepth:e.sourceDepth,callLineStack:e.callLineStack,funcNameStack:e.funcNameStack,sourceStack:e.sourceStack,currentSource:e.currentSource,inCondition:e.inCondition,loopDepth:e.loopDepth,parentHasLoopContext:e.parentHasLoopContext,errexitSafe:e.errexitSafe,directoryStack:e.directoryStack,hashTable:e.hashTable,completionSpecs:e.completionSpecs,defaultCompletionSpec:e.defaultCompletionSpec,emptyCompletionSpec:e.emptyCompletionSpec,groupStdin:e.groupStdin,groupStdinSourceFd:e.groupStdinSourceFd,bashPid:e.bashPid,expansionExitCode:e.expansionExitCode,expansionStderr:e.expansionStderr};e.env=new Map(e.env),e.arrays=X2(e.arrays),e.options={...e.options},e.shoptOptions={...e.shoptOptions},e.fileDescriptors=e.fileDescriptors?new Map(e.fileDescriptors):void 0,e.inputFds=e.inputFds?new Set(e.inputFds):void 0,e.fdAliases=cPe(e.fdAliases),e.closedStandardFds=e.closedStandardFds?new Set(e.closedStandardFds):void 0,e.readonlyVars=new Set(e.readonlyVars),e.associativeArrays=new Set(e.associativeArrays),e.namerefs=new Set(e.namerefs),e.boundNamerefs=new Set(e.boundNamerefs),e.invalidNamerefs=new Set(e.invalidNamerefs),e.integerVars=new Set(e.integerVars),e.lowercaseVars=new Set(e.lowercaseVars),e.uppercaseVars=new Set(e.uppercaseVars),e.exportedVars=new Set(e.exportedVars),e.tempExportedVars=new Set(e.tempExportedVars),e.localExportedVars=e.localExportedVars?.map(e=>new Set(e)),e.declaredVars=new Set(e.declaredVars),e.localScopes=e.localScopes.map(e=>new Map(e)),e.localArrayScopes=lPe(e.localArrayScopes),e.localVarDepth=e.localVarDepth?new Map(e.localVarDepth):void 0,e.localVarStack=uPe(e.localVarStack),e.fullyUnsetLocals=e.fullyUnsetLocals?new Map(e.fullyUnsetLocals):void 0,e.tempEnvBindings=e.tempEnvBindings?.map(e=>new Map(e)),e.mutatedTempEnvVars=e.mutatedTempEnvVars?new Set(e.mutatedTempEnvVars):void 0,e.accessedTempEnvVars=e.accessedTempEnvVars?new Set(e.accessedTempEnvVars):void 0,e.functions=new Map(e.functions),e.callLineStack=e.callLineStack?[...e.callLineStack]:void 0,e.funcNameStack=e.funcNameStack?[...e.funcNameStack]:void 0,e.sourceStack=e.sourceStack?[...e.sourceStack]:void 0,e.directoryStack=e.directoryStack?[...e.directoryStack]:void 0,e.hashTable=e.hashTable?new Map(e.hashTable):void 0,e.completionSpecs=sPe(e.completionSpecs),e.defaultCompletionSpec=x9(e.defaultCompletionSpec),e.emptyCompletionSpec=x9(e.emptyCompletionSpec);let n=!1;return()=>{n||(n=!0,Object.assign(e,t))}}async function dPe(e,t,n,r,i=!1){let a=e.state.loopDepth,o=new Map;for(let t of e.state.fileDescriptors?.keys()??[]){let n=P5(e,t);n&&o.set(t,n)}let s=S9(e.state);e.state.parentHasLoopContext=a>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++;try{return await r7(e,t.redirections,n,a=>fPe(e,t,a.stdin??n,r,i||a.stdin!==void 0))}finally{let t=new Map;for(let[n,r]of o){let i=P5(e,n),a=r.kind===`input`&&i?.kind===`input`?r.content.length-i.content.length:r.kind===`readwrite`&&i?.kind===`readwrite`&&r.path===i.path?i.position-r.position:0;if(a<=0)continue;let o=Math.min(...A5(e,n));t.set(o,Math.max(t.get(o)??0,a))}s();for(let[n,r]of t)U5(e,n,r)}}async function fPe(e,t,n,r,i){(i||n)&&(e.state.groupStdin=n);let a=new aX(e.executionScope,`subshell`),o=0;try{for(let e of t.body){let t=await r(e);a.appendResult(t),o=t.exitCode}}catch(e){if(e instanceof H)throw a.prependTo(e),e;return e instanceof UB||e instanceof MB||e instanceof NB?(a.append(`stdout`,e.stdout,e.internalOutputAccounting.stdout),a.append(`stderr`,e.stderr,e.internalOutputAccounting.stderr),a.build(0)):e instanceof LB||e instanceof PB||e instanceof FB?(a.append(`stdout`,e.stdout,e.internalOutputAccounting.stdout),a.append(`stderr`,e.stderr,e.internalOutputAccounting.stderr),a.build(e.exitCode)):(a.append(`stderr`,`${wV(e)} +`),a.build(1))}return a.build(o)}async function pPe(e,t,n,r,i=!1){return r7(e,t.redirections,n,a=>mPe(e,t,n,r,i,a))}async function mPe(e,t,n,r,i,a){let o=new aX(e.executionScope,`group`),s=0,c=a.stdin??n,l=i||n!==``||a.stdin!==void 0,u=e.state.groupStdin;l&&(e.state.groupStdin=c);let d=()=>{(l||u!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=u)};try{for(let e of t.body){let t=await r(e);o.appendResult(t),s=t.exitCode}}catch(e){if(d(),e instanceof H)throw o.prependTo(e),e;if(AB(e)||e instanceof FB||e instanceof LB)throw e.prependOutput(o.stdout,o.stderr),e;return o.append(`stderr`,`${wV(e)} +`),o.build(1)}return d(),o.build(s)}async function hPe(e,t,n,r,i){let a;try{a=await e.fs.readFile(t)}catch{return Q(`bash: ${t}: No such file or directory +`,127)}if(a.startsWith(`#!`)){let e=a.indexOf(` +`);e!==-1&&(a=a.slice(e+1))}let o=e.state.loopDepth,s=S9(e.state);e.state.parentHasLoopContext=o>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set(`0`,t),e.state.env.set(`#`,String(n.length)),e.state.env.set(`@`,n.join(` `)),e.state.env.set(`*`,n.join(` `));for(let t=0;t0)throw e.prependOutput(n.stdout,n.stderr),e;n.append(`stdout`,e.stdout),n.append(`stderr`,e.stderr);continue}throw e instanceof PB&&e.prependOutput(n.stdout,n.stderr),e}return{...n.build(t),env:QK(this.ctx.state.env)}}async executeUserScript(e,t,n=``){return hPe(this.ctx,e,t,n,e=>this.executeScript(e))}async executeStatement(e){if(this.assertDefenseContext(`statement`),this.ctx.state.signal?.aborted)throw new HB;if(e.deferredError)throw new k4(e.deferredError.message,e.line??1,1);if(this.ctx.state.options.noexec)return F8;this.ctx.state.errexitSafe=!1;let t=new aX(this.ctx.executionScope,`statement`);this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&e.sourceText&&t.append(`stderr`,`${e.sourceText} +`);let n=0,r=-1,i=!1;try{for(let a=0;a0?e.operators[a-1]:null;if(s===`&&`&&n!==0||s===`||`&&n===0)continue;let c=await this.executePipeline(o);t.appendResult(c,wB(c)),n=c.exitCode,r=a,i=o.negated,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(`?`,String(n))}}catch(e){throw t.prependTo(e),e}let a=rthis.executeCommand(e,t))}async executeCommand(e,t,n=!1){let r=gje(this.ctx),i;try{i=await this.executeCommandInner(e,t,n)}catch(e){throw await p8(this.ctx,r).catch(()=>{}),e}let a=await p8(this.ctx,r);return!a.stdout&&!a.stderr?i:{...i,stdout:a.stdout?CB(i)+a.stdout:i.stdout,stdoutKind:a.stdout?`bytes`:i.stdoutKind,stderr:i.stderr+a.stderr}}async executeCommandInner(e,t,n){switch(this.assertDefenseContext(`command`),this.ctx.coverage?.hit(`bash:cmd:${e.type}`),e.type){case`SimpleCommand`:return this.executeSimpleCommand(e,t);case`If`:return JNe(this.ctx,e);case`For`:return XNe(this.ctx,e);case`CStyleFor`:return QNe(this.ctx,e);case`While`:return ePe(this.ctx,e,t);case`Until`:return nPe(this.ctx,e,t);case`Case`:return iPe(this.ctx,e);case`Subshell`:return this.executeSubshell(e,t,n);case`Group`:return this.executeGroup(e,t,n);case`FunctionDef`:return pMe(this.ctx,e);case`ArithmeticCommand`:return this.executeArithmeticCommand(e);case`ConditionalCommand`:return this.executeConditionalCommand(e);default:return gPe(e)}}async executeSimpleCommand(e,t){let n;try{return await this.executeSimpleCommandInner(e,t,e=>{n=e})}catch(e){if(n?.finish(),e instanceof BB)return Q(e.stderr);throw e}}async executeSimpleCommandInner(e,t,n){if(e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.shoptOptions.expand_aliases&&e.name){let t=e,n=0;for(;;){let e=this.expandAlias(t);if(e===t)break;if(n>=this.ctx.limits.maxCallDepth)throw new H(`alias expansion depth limit exceeded (${this.ctx.limits.maxCallDepth})`,`recursion`);n++,t=e}this.aliasExpansionStack.clear(),t!==e&&(e=t)}this.ctx.state.expansionStderr=``;let r=await ANe(this.ctx,e);if(r.error)return r.error;let i=r.tempAssignments,a=r.xtraceOutput,o=()=>{for(let[e,t]of i)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t)};if(!e.name){if(e.redirections.length>0){let r=e7(this.ctx,e.redirections,oMe);n(r);let i=await r.prepare(t);if(i.error){if(o(),!i.errorCause)return r.finish(),i.error;try{return t7(i)}finally{r.finish()}}let s=$(``,a,0),c=await i7(this.ctx,s,e.redirections,i.targets,i.dupSources,i.standardRoutes);return r.finish(),c}this.ctx.state.lastArg=``;let r=(this.ctx.state.expansionStderr||``)+a;return this.ctx.state.expansionStderr=``,$(``,r,this.ctx.state.lastExitCode)}let s=e.name&&b9(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`]),c=Array.from(i.keys());if(c.length>0&&!s){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let e of c)this.ctx.state.tempExportedVars.add(e)}let l=await g8(this.ctx,e.name),u=[],d=[],f=(e,t)=>{if(u.length>=this.ctx.limits.maxArrayElements)throw new H(`expanded argument element limit exceeded (${this.ctx.limits.maxArrayElements})`,`array_elements`);u.push(e),d.push(t)};if(b9(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`])&&(l===`local`||l===`declare`||l===`typeset`||l===`export`||l===`readonly`))for(let t of e.args){let e=await Aje(this.ctx,t);if(e)f(e,!0);else{let e=await jje(this.ctx,t);if(e!==null)f(e,!0);else{let e=await S8(this.ctx,t);for(let t of e.values)f(t,e.quoted)}}}else for(let t of e.args){let e=await S8(this.ctx,t);for(let t of e.values)f(t,e.quoted)}let p=e.name.parts.every(e=>e.type===`CommandSubstitution`||e.type===`ParameterExpansion`||e.type===`ArithmeticExpansion`);!l&&p&&u.length>0&&(l=u.shift(),d.shift());let m=e7(this.ctx,e.redirections,l===`exec`?sMe:Y5);n(m);let h=await m.prepare(t);if(h.error)return o(),h.errorCause?t7(h):(m.finish(),h.error);let g=h.stdinSourceFd,_=h.stdin!==void 0;if(h.stdin!==void 0&&(t=h.stdin),!l)return p?(m.finish(),$(``,``,this.ctx.state.lastExitCode)):(m.finish(),Q(`bash: : command not found +`,127));if(l===`exec`&&(u.length===0||u[0]===`--`)){for(let[e,t]of i)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);if(this.ctx.state.tempExportedVars)for(let e of i.keys())this.ctx.state.tempExportedVars.delete(e);return m.finish(),F8}if(this.ctx.state.extraArgs){let e=this.ctx.state.extraArgs;this.ctx.state.extraArgs=void 0;for(let t of e)f(t,!0)}let v=await ONe(this.ctx,l,u);i.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(i)));let y,b=null;try{y=await this.runCommand(l,u,d,t,!1,!1,g,_)}catch(e){if(e instanceof MB||e instanceof NB)b=e,y=F8;else throw e}g>=0&&l!==`read`&&U5(this.ctx,g,y.internalStdinConsumed??0);let x=a+v;if(x&&(y={...y,stderr:x+y.stderr}),y=await i7(this.ctx,y,e.redirections,h.targets,h.dupSources,h.standardRoutes,y.internalProducerCommand??l,y.internalProducerOmitsShellPrefix),m.finish(),b)throw b;if(u.length>0){let e=u[u.length-1];if((l===`declare`||l===`local`||l===`typeset`)&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(e)){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);t&&(e=t[1])}this.ctx.state.lastArg=e}else this.ctx.state.lastArg=l;let S=$je(l)&&l!==`unset`&&l!==`eval`;if(!this.ctx.state.options.posix||!S)for(let[e,t]of i)this.ctx.state.fullyUnsetLocals?.has(e)||(t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t));if(this.ctx.state.tempExportedVars)for(let e of i.keys())this.ctx.state.tempExportedVars.delete(e);return i.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(y={...y,stderr:this.ctx.state.expansionStderr+y.stderr},this.ctx.state.expansionStderr=``),y}async runCommand(e,t,n,r,i=!1,a=!1,o=-1,s=!1){let c={ctx:this.ctx,runCommand:(e,t,n,r,i,a,o,s)=>this.runCommand(e,t,n,r,i,a,o,s),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(e,t,n)=>this.executeUserScript(e,t,n)},l=await WNe(c,e,t,n,r,i,a,o,s);return l===null?{...await qNe(c,e,t,r,a),internalProducerCommand:e}:l.internalProducerCommand===void 0?{...l,internalProducerCommand:e}:l}aliasExpansionStack=new Set;expandAlias(e){return Ake({env:this.ctx.state.env,limits:this.ctx.limits},e,this.aliasExpansionStack)}async findCommandInPath(e){return n9(this.ctx,e)}async executeSubshell(e,t=``,n=!1){return dPe(this.ctx,e,t,e=>this.executeStatement(e),n)}async executeGroup(e,t=``,n=!1){return pPe(this.ctx,e,t,e=>this.executeStatement(e),n)}async executeArithmeticCommand(e){return e.line!==void 0&&(this.ctx.state.currentLine=e.line),r7(this.ctx,e.redirections,``,async()=>{try{let t=L8(await M8(this.ctx,e.expression.expression)!==0);return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),t}catch(e){return Q(`bash: arithmetic expression: ${e.message} +`)}})}async executeConditionalCommand(e){return e.line!==void 0&&(this.ctx.state.currentLine=e.line),r7(this.ctx,e.redirections,``,async()=>{try{let t=L8(await Z8(this.ctx,e.expression));return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),t}catch(e){let t=e instanceof RB?1:2;return Q(`bash: conditional expression: ${e.message} +`,t)}})}};jz(),gB(),aB(),mB();function C9(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function vPe(e){let t=C9(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}var yPe=3;function w9(e){let t=e;for(let e=0;eT9(e,E9(t)))}function D9(e){let t=SPe(e);if(t===`localhost`||t.endsWith(`.localhost`))return!0;let n=O9(t);if(n)return k9(n);let r=wPe(t);return r?TPe(r):!1}function SPe(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function CPe(e){if(!e)return null;let t=10,n=e;if(n.startsWith(`0x`)||n.startsWith(`0X`)?(t=16,n=n.slice(2)):n.length>1&&n.startsWith(`0`)&&(t=8),!n||t===16&&!/^[0-9a-fA-F]+$/.test(n)||t===10&&!/^\d+$/.test(n)||t===8&&!/^[0-7]+$/.test(n))return null;let r=Number.parseInt(n,t);return!Number.isFinite(r)||r<0?null:r}function O9(e){let t=e.split(`.`);if(t.length===0||t.length>4)return null;let n=t.map(e=>CPe(e));if(n.some(e=>e===null))return null;let r=n;if(t.length===1){let e=r[0];return e>4294967295?null:[e>>>24&255,e>>>16&255,e>>>8&255,e&255]}if(t.length===2){let[e,t]=r;return e>255||t>16777215?null:[e,t>>>16&255,t>>>8&255,t&255]}if(t.length===3){let[e,t,n]=r;return e>255||t>255||n>65535?null:[e,t,n>>>8&255,n&255]}let[i,a,o,s]=r;return i>255||a>255||o>255||s>255?null:[i,a,o,s]}function wPe(e){let t=e,n=null;if(t.includes(`.`)){let e=t.lastIndexOf(`:`);if(e<0)return null;let r=O9(t.slice(e+1));if(!r)return null;n=r,t=t.slice(0,e)}let r=t.includes(`::`)?t.split(`::`).length-1:0;if(r>1)return null;let[i,a]=t.split(`::`),o=i?i.split(`:`).filter(Boolean):[],s=a?a.split(`:`).filter(Boolean):[],c=e=>/^[0-9a-f]{1,4}$/i.test(e)?Number.parseInt(e,16):null,l=o.map(c),u=s.map(c);if(l.some(e=>e===null)||u.some(e=>e===null))return null;let d=n?2:0,f=l.length+u.length+d,p=0;if(r===1){if(p=8-f,p<0)return null}else if(f!==8)return null;let m=[...l,...Array(p).fill(0),...u];return n&&(m.push(n[0]<<8|n[1]),m.push(n[2]<<8|n[3])),m.length===8?m:null}function k9(e){let[t,n]=e;return t===127||t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===169&&n===254||t===0||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===192&&n===0&&e[2]===0||t===192&&n===0&&e[2]===2||t===198&&n===51&&e[2]===100||t===203&&n===0&&e[2]===113||t>=240}function TPe(e){return e.every(e=>e===0)||e.slice(0,7).every(e=>e===0)&&e[7]===1||(e[0]&65472)==65152||(e[0]&65024)==64512?!0:e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535?k9([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===8193&&e[1]===3512?!0:e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0?k9([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===100&&e[1]===65435&&e[2]===1||e[0]===8194&&k9([e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255])}function EPe(e){let t=[];for(let n of e){if(typeof n!=`string`&&(typeof n!=`object`||!n||!(`url`in n)||typeof n.url!=`string`)){t.push(`Invalid allow-list entry: must be a string URL or an object with a "url" string property`);continue}let e=E9(n);if(!C9(e)){t.push(`Invalid URL in allow-list: "${e}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let r=new URL(e);if(r.protocol!==`http:`&&r.protocol!==`https:`){t.push(`Only http and https URLs are allowed in allow-list: "${e}"`);continue}if(!r.hostname){t.push(`Allow-list entry must include a hostname: "${e}"`);continue}if(r.pathname!==`/`&&r.pathname!==``&&w9(r.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${e}"`);continue}(r.search||r.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${e}"`)}return t}var A9=class extends Error{constructor(){super(`DNS pinning is unavailable in this runtime`),this.name=`DnsPinningUnavailableError`}},DPe=async e=>{throw new A9},j9=class extends Error{constructor(e,t){super(`Network access denied: ${t??`URL not in allow-list`}: ${e}`),this.name=`NetworkAccessDeniedError`}},OPe=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name=`TooManyRedirectsError`}},kPe=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name=`RedirectNotAllowedError`}},APe=class extends Error{constructor(e,t){super(`HTTP method '${e}' not allowed. Allowed methods: ${t.join(`, `)}`),this.name=`MethodNotAllowedError`}},M9=class extends Error{constructor(e){super(`Response body too large (max: ${e} bytes)`),this.name=`ResponseTooLargeError`}};function jPe(e){return new Promise((t,n)=>{Oz(e,{all:!0},(e,r)=>{e?n(e):t(r)})})}var MPe=20,NPe=3e4,PPe=10485760,FPe=[`GET`,`HEAD`],IPe=new Set([`GET`,`HEAD`,`OPTIONS`]),LPe=new Set([301,302,303,307,308]);function N9(e){return e.reason instanceof Error?e.reason:new DOMException(`The operation was aborted`,`AbortError`)}function P9(e){if(e?.aborted)throw N9(e)}async function F9(e,t){if(!t)return e;if(t.aborted)throw e.catch(()=>{}),N9(t);let n,r=new Promise((e,r)=>{n=()=>r(N9(t)),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e,r])}finally{n&&t.removeEventListener(`abort`,n)}}async function RPe(e,t){try{return await F9(e,t)}catch(n){throw t?.aborted&&e.then(e=>iB.runTrustedAsync(()=>e.close())).catch(()=>{}),n}}async function zPe(e){e.body&&!e.body.locked&&await e.body.cancel()}function BPe(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let e=EPe(t);if(e.length>0)throw Error(`Invalid network allow-list: +${e.join(` +`)}`)}let n=[];for(let e of t)typeof e==`object`&&e.transform&&e.transform.length>0&&n.push(e);function r(e){if(n.length===0)return null;let t=null;for(let r of n)if(T9(e,r.url)&&r.transform){t||=new Headers;for(let e of r.transform)for(let[n,r]of Object.entries(e.headers))t.set(n,r)}return t}if(e.maxRedirects!==void 0&&(!Number.isSafeInteger(e.maxRedirects)||e.maxRedirects<0))throw RangeError(`maxRedirects must be a non-negative safe integer`);let i=e.maxRedirects??MPe,a=e.timeoutMs??NPe,o=e.maxResponseSize??PPe,s=e.dangerouslyAllowFullInternetAccess?[`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`]:e.allowedMethods??FPe,c=e.denyPrivateRanges??(typeof process<`u`&&!0),l=e._dnsResolve??jPe,u=e._createConnectionOwner??DPe;function d(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;if(/^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/.test(t)&&t.split(`.`).every(e=>Number(e)<=255))return 4;if(t.includes(`:`)&&!t.includes(`%`))try{if(new URL(`http://[${t}]/`).hostname.length>2)return 6}catch{}return null}function f(e,t,n){let{address:r,family:i}=n;if(d(r)!==i)throw new j9(e,`DNS returned an invalid address for private IP check`);return{hostname:t,address:r,family:i}}async function p(n,r){if(P9(r),!e.dangerouslyAllowFullInternetAccess&&!xPe(n,t))throw new j9(n);if(!c)return null;let i;try{i=new URL(n)}catch{throw new j9(n,`invalid URL`)}if(D9(i.hostname))throw new j9(n,`private/loopback IP address blocked`);let a=i.hostname;if(d(a)!==null)return null;let o;try{o=await F9(l(a),r)}catch{throw r?.aborted?N9(r):new j9(n,`DNS resolution failed for private IP check`)}if(!Array.isArray(o)||o.length===0)throw new j9(n,`DNS resolution returned no addresses for private IP check`);let s=o.map(e=>f(n,a,e));for(let{address:e}of s)if(D9(e))throw new j9(n,`hostname resolves to private/loopback IP address`);return s[0]}function m(t){if(e.dangerouslyAllowFullInternetAccess)return;let n=t.toUpperCase();if(!s.includes(n))throw new APe(n,s)}async function h(e,t={}){let n=t.method?.toUpperCase()??`GET`,s=t.followRedirects??!0;if(t.maxRedirects!==void 0&&(!Number.isSafeInteger(t.maxRedirects)||t.maxRedirects<0))throw RangeError(`maxRedirects must be a non-negative safe integer`);let c=t.maxRedirects??i,l=Math.min(i,c),d=t.timeoutMs===void 0?a:Math.min(t.timeoutMs,a),f=new AbortController,h=dB(()=>f.abort(new DOMException(`The operation was aborted`,`AbortError`)),d),g=hB(t.signal,f.signal);try{let i=await p(e,g.signal);m(n);let a=e,c=0;for(;;){P9(g.signal);let e;try{let d=await iB.runTrustedAsync(async()=>{let o=r(a),s=VPe(t.headers,o),c={method:n,headers:s,signal:g.signal,redirect:`manual`};if(t.body&&!IPe.has(n)&&(c.body=t.body),!i)return await F9(fetch(a,c),g.signal);try{return e=await RPe(u(i),g.signal),await F9(e.fetch(a,c),g.signal)}catch(e){throw e instanceof A9?new j9(a,`DNS pinning unavailable for private IP enforcement`):e}});if(LPe.has(d.status)&&s){let e=d.headers.get(`location`);if(!e)return await I9(d,a,o,g.signal);let t=new URL(e,a).href;await F9(zPe(d),g.signal);try{i=await p(t,g.signal)}catch{throw g.signal?.aborted?N9(g.signal):new kPe(t)}if(c++,c>l)throw new OPe(l);a=t;continue}return await I9(d,a,o,g.signal)}finally{if(e){let t=e;await F9(iB.runTrustedAsync(()=>t.close()),g.signal)}}}}finally{fB(h),g.cleanup()}}return h}function VPe(e,t){if(!e&&!t)return;if(!t)return e;let n=(e instanceof Headers,new Headers(e));for(let[e,r]of t)n.set(e,r);return n}async function I9(e,t,n,r){let i=Object.create(null);if(e.headers.forEach((e,t)=>{i[t.toLowerCase()]=e}),n>0){let t=e.headers.get(`content-length`);if(t){let e=parseInt(t,10);if(!Number.isNaN(e)&&e>n)throw new M9(n)}}let a;if(n>0&&e.body){let t=e.body.getReader(),i=[],o=0;try{for(;;){let{done:e,value:a}=await F9(t.read(),r);if(e)break;if(a){if(o+=a.byteLength,o>n)throw await t.cancel(),new M9(n);i.push(a)}}}catch(e){throw r?.aborted&&await t.cancel(N9(r)).catch(()=>{}),e}a=new Uint8Array(o);let s=0;for(let e of i)a.set(e,s),s+=e.byteLength}else{let t=await F9(e.arrayBuffer(),r);if(n>0&&t.byteLength>n)throw new M9(n);a=new Uint8Array(t)}return{status:e.status,statusText:e.statusText,headers:i,body:a,url:t}}aB(),XB(),U();function L9(e,t){if(e.length>t||V(e)>t)throw new H(`script input size limit exceeded (${t} bytes)`,`string_length`)}var HPe=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;invokeToolFn;transformPlugins=[];state;constructor(e={}){this.limits=JDe({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}},e.executionLimitProfile);let t=e.fs??new q2(e.files,{maxTotalBytes:this.limits.maxFileSystemBytes});this.fs=t,this.useDefaultLayout=!e.cwd&&!e.files;let n=e.cwd||(this.useDefaultLayout?`/home/user`:`/`),r=new Map([[`HOME`,this.useDefaultLayout?`/home/user`:`/`],[`PATH`,`/usr/bin:/bin`],[`IFS`,` +`],[`OSTYPE`,`linux-gnu`],[`MACHTYPE`,`x86_64-pc-linux-gnu`],[`HOSTTYPE`,`x86_64`],[`HOSTNAME`,`localhost`],[`PWD`,n],[`OLDPWD`,n],[`OPTIND`,`1`],...Object.entries(e.env??{})]);if(e.fetch?this.secureFetch=e.fetch:e.network&&(this.secureFetch=BPe(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.defenseInDepthConfig=e.defenseInDepth??!0,this.coverageWriter=e.coverage,this.state={env:r,arrays:new Map,cwd:n,previousDir:`/home/user`,functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:``,startTime:Date.now(),lastBackgroundPid:0,virtualPid:e.processInfo?.pid??1,virtualPpid:e.processInfo?.ppid??0,virtualUid:e.processInfo?.uid??1e3,virtualGid:e.processInfo?.gid??1e3,bashPid:e.processInfo?.pid??1,nextVirtualPid:(e.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set([`HOME`,`PATH`,`PWD`,`OLDPWD`,...Object.keys(e.env||{})]),readonlyVars:new Set([`SHELLOPTS`,`BASHOPTS`]),hashTable:new Map},this.state.env.set(`SHELLOPTS`,p4(this.state.options)),this.state.env.set(`BASHOPTS`,h4(this.state.shoptOptions)),sOe(t,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),n!==`/`&&t instanceof q2)try{t.mkdirSync(n,{recursive:!0})}catch{}for(let t of VDe(e.commands))this.registerBundledCommand(t);if(e.fetch||e.network)for(let e of HDe())this.registerBundledCommand(e);if(e.python)for(let e of UDe())this.registerBundledCommand(e);let i=typeof e.javascript==`object`?e.javascript:Object.create(null);if(e.javascript||i.invokeTool){for(let e of WDe())this.registerBundledCommand(e);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(e.customCommands)for(let t of e.customCommands)if(YDe(t)){let e=XDe(t);this.registerCommandInternal(e,!0)}else this.registerCommandInternal(t,!0)}registerCommand(e){this.registerCommandInternal(e,!0)}registerBundledCommand(e){this.registerCommandInternal(e,!1)}registerCommandInternal(e,t,n=t?e.trusted??!0:e.trusted){let r=this.commands.get(e.name),i=t?r?.internalOriginalCommand??(r&&!r.internalIsExtension?r:void 0):void 0,a={name:e.name,trusted:n,internalIsExtension:t,internalOriginalCommand:i,execute:(t,n)=>e.execute(t,n)};this.commands.set(e.name,a);let o=this.fs;if(typeof o.writeFileSync==`function`){let t=`#!/bin/bash +# Built-in command: ${e.name} +`;try{o.writeFileSync(`/bin/${e.name}`,t)}catch{}try{o.writeFileSync(`/usr/bin/${e.name}`,t)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug(`stdout`,{output:e.stdout}),e.stderr&&this.logger.info(`stderr`,{output:e.stderr}),this.logger.info(`exit`,{exitCode:e.exitCode})),e.stdout=z9(e.stdout),e.stderr=z9(e.stderr),e}async exec(e,t){let n=new ZDe(this.limits,t?.signal),r;try{r=await this.execInScope(e,t,n,0,t?.signal,!1,!1)}catch(e){try{await n.close()}catch{}throw e}let i=r;try{await n.close()}catch{i={...r,stderr:`${r.stderr}bash: execution cleanup failed +`,exitCode:126}}return e.trim()?this.logResult(i):i}async execInScope(e,t,n,r,i,a=!1,o=!0){let s=e=>o?this.logResult(e):e,c=hB(i,t?.signal),l=t?{...t,signal:c.signal}:{signal:c.signal};try{if(n.assertExecDepth(r),L9(e,this.limits.maxSourceBytes),!e.trim())return{stdout:``,stderr:``,exitCode:0,env:$K(this.state.env,l.env)};this.logger?.info(`exec`,{command:e});let t=l.cwd??this.state.cwd,i,o=t;if(l.cwd){if(l.env&&`PWD`in l.env)i=l.env.PWD;else if(l.env&&!(`PWD`in l.env))try{i=await this.fs.realpath(t),o=i}catch{i=t}else i=t}let c=l.replaceEnv?new Map:new Map(this.state.env);if(l.env)for(let[e,t]of Object.entries(l.env))c.set(e,t);i!==void 0&&c.set(`PWD`,i);let u={...this.state,env:c,arrays:l.replaceEnv?new Map:X2(this.state.arrays),cwd:o,previousDir:l.env?.OLDPWD??this.state.previousDir,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:GPe(l.stdin,l.stdinKind,this.limits.maxInputBytes,this.limits.maxStringLength,n,a),signal:l.signal,extraArgs:l.args},d=e;l.rawScript||(d=R9(e));let f=this.defenseInDepthConfig?iB.getInstance(this.defenseInDepthConfig):null,p=f?.activate();try{let e=async()=>{let e=T3(d,{maxHeredocSize:this.limits.maxHeredocSize}),t;if(this.transformPlugins.length>0){let n=Object.create(null);for(let t of this.transformPlugins){let r=t.transform({ast:e,metadata:n});e=r.ast,r.metadata&&(n=eq(n,r.metadata))}t=n}let i=await new _Pe({fs:this.fs,commands:this.commands,limits:this.limits,executionScope:n,exec:(e,t,i=!1)=>this.execInScope(e,t,n,r+1,l.signal,i),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:f?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,invokeTool:this.invokeToolFn},u).executeScript(e);return t&&(i.metadata=t),s(i)};return p?await p.run(e):await e()}catch(e){if(e instanceof LB)return s({stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,internalOutputAccounting:e.internalOutputAccounting,env:$K(this.state.env,l.env)});if(e instanceof WB)return s({stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,env:$K(this.state.env,l.env)});if(e instanceof RB)return s({stdout:e.stdout,stderr:e.stderr,exitCode:1,env:$K(this.state.env,l.env)});if(e instanceof HB)return s({stdout:e.stdout,stderr:e.stderr,exitCode:124,env:$K(this.state.env,l.env)});if(e instanceof H)return s({stdout:e.stdout,stderr:_H(e.stderr),exitCode:H.EXIT_CODE,internalOutputAccounting:e.internalOutputAccounting,env:$K(this.state.env,l.env)});if(e instanceof eB)return s({stdout:``,stderr:`bash: security violation: ${_H(e.message)} +`,exitCode:1,env:$K(this.state.env,l.env)});if(e.name===`ParseException`)return s({stdout:``,stderr:`bash: syntax error: ${_H(e.message)} +`,exitCode:2,env:$K(this.state.env,l.env)});if(e instanceof y4)return s({stdout:``,stderr:`bash: ${_H(e.message)} +`,exitCode:2,env:$K(this.state.env,l.env)});if(e instanceof RangeError)return s({stdout:``,stderr:`bash: ${_H(e.message)} +`,exitCode:1,env:$K(this.state.env,l.env)});throw e}finally{p?.deactivate()}}catch(e){if(e instanceof HB)return s({stdout:e.stdout,stderr:e.stderr,exitCode:124,env:$K(this.state.env,l.env)});if(e instanceof H)return s({stdout:e.stdout,stderr:_H(e.stderr),exitCode:H.EXIT_CODE,internalOutputAccounting:e.internalOutputAccounting,env:$K(this.state.env,l.env)});throw e}finally{c.cleanup()}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,t){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),t)}getCwd(){return this.state.cwd}getEnv(){return QK(this.state.env)}registerTransformPlugin(e){this.transformPlugins.push(e)}transform(e){L9(e,this.limits.maxSourceBytes);let t=T3(R9(e),{maxHeredocSize:this.limits.maxHeredocSize}),n=Object.create(null);for(let e of this.transformPlugins){let r=e.transform({ast:t,metadata:n});t=r.ast,r.metadata&&(n=eq(n,r.metadata))}return{script:oke(t),ast:t,metadata:n}}};function UPe(e,t){let n=t;for(let t=0;t0){let e=r[r.length-1];if((e.stripTabs?a.replace(/^\t+/,``):a)===e.delimiter){n.push(a.trimStart()),r.pop();continue}n.push(a);continue}let o=i,s=o===`none`?a.trimStart():a;if(n.push(s),i=UPe(a,o),o===`none`)for(let e of s.matchAll(/<<(-?)\s*(['"]?)([\w-]+)\2/g)){let t=e[1]===`-`,n=e[3];r.push({delimiter:n,stripTabs:t})}}return n.join(` +`)}var WPe=new TextDecoder(`utf-8`,{fatal:!0});function z9(e){if(!e)return e;let t=!1;for(let n=0;n255)return e;r>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let t=0;tn||o>r)throw new H(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,`string_length`);return a||i.consumeInput(o,`stdin`),t===`bytes`?e:yB(e)} +/*! Bundled license information: + +re2js/build/index.esm.js: +(*! +* re2js +* RE2JS is the JavaScript port of RE2, a regular expression engine that provides linear time matching +* +* @version v1.3.3 +* @author Alexey Vasiliev +* @homepage https://github.com/le0pard/re2js#readme +* @repository github:le0pard/re2js +* @license MIT +*) + +ieee754/index.js: +(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) +*/ +const B9=Object.freeze([`https://api.github.com`,`https://raw.githubusercontent.com`,`https://huggingface.co`,`https://jsonplaceholder.typicode.com`,`https://httpbin.org`]),KPe=Object.freeze([`GET`,`HEAD`,`POST`]);function qPe({transport:e=globalThis.fetch,origins:t=B9,timeoutMs:n=8e3,maxBytes:r=1048576}={}){let i=new Set(t);return async(t,a={})=>{let o=new URL(t);if(o.protocol!==`https:`||!i.has(o.origin))throw Error(`HTTP destination is not enabled in this experiment. Allowed hosts: ${[...i].map(e=>new URL(e).host).join(`, `)}.`);if(o.username||o.password)throw Error(`Credentials in URLs are unsupported. Use an explicit Authorization header if needed.`);let s=(a.method??`GET`).toUpperCase();if(!KPe.includes(s))throw Error(`HTTP method ${s} is not enabled. Use GET, HEAD, or POST.`);let c=a.timeoutMs>0?a.timeoutMs:n,l=new AbortController,u=Math.min(c,n),d=setTimeout(()=>l.abort(new DOMException(`HTTP request timed out after ${u} ms.`,`TimeoutError`)),u),f=a.signal?AbortSignal.any([a.signal,l.signal]):l.signal,p;try{f.throwIfAborted();let t=await e(o.href,{method:s,headers:a.headers,body:[`GET`,`HEAD`].includes(s)?void 0:a.body,mode:`cors`,credentials:`omit`,redirect:`manual`,referrerPolicy:`no-referrer`,signal:f});if(t.type===`opaqueredirect`||t.status>=300&&t.status<400&&t.status!==304)throw Error(`HTTP redirect cannot be followed safely in this browser shell. Use the final HTTPS URL directly (including exact capitalization).`);if(t.status===0||t.type===`opaque`)throw Error(`HTTP response is unreadable. The destination must allow browser access with CORS.`);if(Number(t.headers.get(`content-length`))>r)throw await t.body?.cancel(),Error(`HTTP response exceeds the ${r}-byte limit.`);let n=[],i=0;if(t.body)for(p=t.body.getReader();;){let{done:e,value:t}=await p.read();if(f.throwIfAborted(),e)break;if(i+=t.byteLength,i>r)throw await p.cancel(),Error(`HTTP response exceeds the ${r}-byte limit.`);n.push(t)}let c=new Uint8Array(i),l=0;for(let e of n)c.set(e,l),l+=e.byteLength;return{status:t.status,statusText:t.statusText,headers:Object.fromEntries(t.headers.entries()),body:c,url:t.url||o.href}}catch(e){throw f.aborted?f.reason:e instanceof TypeError?Error(`HTTP request failed: the server may block browser requests (CORS), or the connection failed. No proxy is used.`):e}finally{clearTimeout(d),p?.releaseLock()}}}const V9=JSON.stringify([{product:`Notebook`,unit_cost:2.5,stock:24},{product:`Pencil`,unit_cost:.5,stock:120},{product:`Folder`,unit_cost:1.2,stock:18},{product:`Eraser`,unit_cost:.35,stock:40},{product:`Stapler`,unit_cost:2.75,stock:9},{product:`Ruler`,unit_cost:.8,stock:30}],null,2)+` +`,JPe=JSON.stringify(JSON.parse(V9).map(({product:e,unit_cost:t})=>({product:e,unit_cost:t})),null,2)+` +`,H9={"/workspace/README.md":`# Browser workspace + +Your files are saved in this browser. +`,"/workspace/sales.csv":`product,units +Notebook,12 +Pencil,30 +Folder,8 +`,"/workspace/products.json":JSON.stringify([{product:`Notebook`,price:5},{product:`Pencil`,price:2},{product:`Folder`,price:3},{product:`Eraser`,price:1.5},{product:`Stapler`,price:4.99},{product:`Ruler`,price:2.5}],null,2)+` +`},YPe=e=>e.length>6e3?e.slice(0,6e3)+` +[Output truncated at 6,000 characters; use head, grep, or a narrower query.]`:e,U9=(e,t={})=>({content:[{type:`text`,text:YPe(e)}],details:t});function XPe(e=H9,t){t&&(e=Object.fromEntries(t.filter(([,e])=>e.type===`file`).map(([e,t])=>[e,{mode:t.mode,content:Uint8Array.from(atob(t.base64),e=>e.charCodeAt(0))}])));let n=new HPe({files:e,cwd:`/workspace`,executionLimitProfile:`hardened`,fetch:qPe(),executionLimits:{maxExecutionTimeMs:1e4,maxCommandCount:3e3,maxFileSystemBytes:16*1024**2,maxOutputSize:262144,maxSourceBytes:131072}}),r=e=>n.fs.resolvePath(`/workspace`,e),i=(async()=>{for(let[e,r]of t??[])r.type===`directory`?(await n.fs.mkdir(e,{recursive:!0}),await n.fs.chmod(e,r.mode)):r.type===`symlink`&&await n.fs.symlink(r.target,e)})();async function a(e,t){let i=r(e);if(new TextEncoder().encode(t).length>1024**2)throw Error(`The editor accepts files up to 1 MiB.`);await n.fs.mkdir(i.slice(0,i.lastIndexOf(`/`))||`/`,{recursive:!0}),await n.fs.writeFile(i,t)}let o=[{name:`bash`,label:`Bash`,description:`Run a bash command in /workspace. Supports cat, ls, grep, sed, awk, jq, sort, pipes, redirects, shell scripts, and curl/wget. HTTP GET/HEAD/POST is enabled for ${B9.map(e=>new URL(e).host).join(`, `)}. Use curl -fsS URL; use set -o pipefail before piping HTTP output to jq. Browser CORS applies; redirects require the final URL. HTTP limits: 8 seconds, 1 MiB. No Node.js, Python, npm, or native binaries. Files persist across commands; cd and variables reset each call.`,parameters:Sn({command:Yr({description:`The shell command to execute.`})}),execute:async(e,{command:t},r)=>{let i=await n.exec(t,{signal:r});return U9(`${i.stdout}${i.stderr?` +STDERR: +`+i.stderr:``}\nExit code: ${i.exitCode}`,{exitCode:i.exitCode})}},{name:`read`,label:`Read file`,description:`Read a UTF-8 text file. Use bash head/grep for large files.`,parameters:Sn({path:Yr()}),execute:async(e,t)=>{let i=await n.fs.realpath(r(t.path));return U9(await n.fs.readFile(i),{path:i})}},{name:`write`,label:`Write file`,description:`Create or replace a UTF-8 text file. Parent directories are created.`,parameters:Sn({path:Yr(),content:Yr()}),execute:async(e,t)=>(await a(t.path,t.content),U9(`Wrote `+r(t.path)))},{name:`edit`,label:`Edit file`,description:`Replace one exact occurrence of oldText with newText in a UTF-8 file. oldText must match exactly once.`,parameters:Sn({path:Yr(),oldText:Yr(),newText:Yr()}),execute:async(e,t)=>{let i=await n.fs.readFile(r(t.path));if(!t.oldText||i.split(t.oldText).length!==2)throw Error(`oldText must match exactly once. Read the file first.`);return await a(t.path,i.replace(t.oldText,()=>t.newText)),U9(`Edited `+r(t.path))}}];async function s(){let e={};for(let t of n.fs.getAllPaths().sort())t.startsWith(`/bin/`)||t.startsWith(`/usr/bin/`)||t.startsWith(`/dev/`)||t.startsWith(`/proc/`)||(await n.fs.lstat(t)).isFile&&(e[t]=await n.fs.readFile(t));return e}async function c(){let e=[];for(let t of n.fs.getAllPaths().sort()){if([`/bin`,`/usr/bin`,`/dev`,`/proc`].some(e=>t===e||t.startsWith(e+`/`)))continue;let r=await n.fs.lstat(t);if(r.isSymbolicLink)e.push([t,{type:`symlink`,target:await n.fs.readlink(t)}]);else if(r.isDirectory)e.push([t,{type:`directory`,mode:r.mode}]);else if(r.isFile){let i=await n.fs.readFileBuffer(t),a=``;for(let e=0;en.fs.readFile(r(e))}}async function ZPe(){let e=await new Promise((e,t)=>{let n=indexedDB.open(`minicpm5-pi-workspace`,1);n.onupgradeneeded=()=>n.result.createObjectStore(`state`),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)});return{async load(){return new Promise((t,n)=>{let r=e.transaction(`state`).objectStore(`state`).get(`current`);r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})},async save(t){return new Promise((n,r)=>{let i=e.transaction(`state`,`readwrite`);i.objectStore(`state`).put(t,`current`),i.oncomplete=n,i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}}}const W9=e=>postMessage(e),G9=GI(W9);let K9,q9,J9,Y9=!1,X9,Z9=0;async function Q9(){return{version:1,demoVersion:4,files:await K9.snapshot(),entries:await K9.serialize(),messages:q9.state.messages}}async function $9(){let e=await Q9();try{await J9?.save(e)}catch(e){W9({type:`persistence_error`,error:`Changes are in memory, but browser storage failed: `+e.message})}return W9({type:`workspace`,files:e.files}),e}const QPe=(async()=>{let e;try{J9=await ZPe(),e=await J9.load()}catch(e){W9({type:`persistence_error`,error:`Workspace saving is unavailable: `+e.message})}K9=XPe(e?.files,e?.entries),await K9.ready;let t=e&&(e.demoVersion??0)<4;if(t){let t=K9.bash.fs.getAllPaths(),n=`/workspace/products.csv`,r=`/workspace/products.json`,i=`/workspace/sales.csv`,a=async(e,n)=>t.includes(e)&&(await K9.bash.fs.lstat(e)).isFile&&n.includes(await K9.read(e));if(await a(i,[`product,units,price +Notebook,12,5 +Pencil,30,2 +Folder,8,3 +`])){let o=await a(r,[V9,JPe]),s=!t.includes(r)&&await a(n,[`product,unit_cost,stock +Notebook,2.50,24 +Pencil,0.50,120 +Folder,1.20,18 +Eraser,0.35,40 +Stapler,2.75,9 +Ruler,0.80,30 +`]),c=(e.demoVersion??0)<1&&!t.includes(r)&&!t.includes(n);(o||s||c)&&(await K9.write(i,H9[i]),await K9.write(r,H9[r]),s&&await K9.bash.fs.rm(n))}let o=`/workspace/README.md`;await a(o,[`# Browser workspace + +Pi can read, write, edit, and run shell commands here. +Everything stays in this browser. Explore our sales, product costs, and stock levels. +`,`# Browser workspace + +Sales and product costs for a small shop. +Prices and unit costs are in USD. +Profit means revenue minus the cost of units sold, +before tax and other operating expenses. + +Pi can read, edit, and run shell commands here. +Everything stays in this browser. +`])&&await K9.write(o,H9[o])}q9=new zce({initialState:{model:WI,thinkingLevel:`medium`,systemPrompt:`You are Pi, a coding assistant powered by MiniCPM5-2B, a language model from OpenBMB. +The model, inference, tools, and workspace run entirely in the user's browser. Workspace files are stored in this browser, not on the user's operating-system filesystem. +Use your tools to inspect and change actual files. Never claim a command ran or a file changed without a successful tool result. +When the user explicitly asks you to use a tool, call that tool even if you already know the answer. +Working directory: /workspace. Use read, write, edit, and bash. Keep tool calls and answers concise. +The bash tool supports cat, ls, find, grep, sed, awk, jq, sort, wc, printf, pipes, redirects, and shell scripts. +Use jq for JSON and awk for CSV and calculations; python, python3, node, npm, and native binaries are unavailable. +Use curl -fsS for HTTP requests to the hosts listed by the bash tool. To save a response, use curl -fsS URL -o file.json, then inspect it with jq or read. For pipelines use set -o pipefail so failed downloads are not mistaken for success. CORS and redirect errors are browser limitations: report them accurately; do not invent fetched content or repeatedly retry blocked requests. +You can create and edit text files, including HTML, CSS, JavaScript, and shell scripts. External URLs may be referenced without fetching them. Only claim an asset was fetched or tested after a successful tool result. HTTP requests send the requested URL and any explicit request data to that external server; model inference stays local. +Interpret short follow-ups using the conversation and inspect the relevant files when needed. +Inspect files before editing them. After changing files, verify the result with a tool. Finish with a short factual answer.`,tools:K9.tools,messages:e?.messages??[]},streamFn:G9.streamFn,toolExecution:`sequential`,afterToolCall:({result:e,isError:t})=>({isError:t||e.details?.exitCode!==void 0&&e.details.exitCode!==0}),shouldStopAfterTurn:({toolResults:e})=>{let t=++Z9>=12&&e.length>0;return t&&W9({type:`notice`,text:`Paused after 12 agent turns. Send a follow-up to continue.`}),t}}),q9.subscribe(async e=>{W9({type:`agent_event`,event:e}),(e.type===`tool_execution_end`||e.type===`agent_end`)&&await $9()});let n=await Q9();if(t)try{await J9?.save(n)}catch(e){W9({type:`persistence_error`,error:`Changes are in memory, but browser storage failed: `+e.message})}W9({type:`initialized`,...n})})();onmessage=async({data:e})=>{let{id:t,action:n,args:r={}}=e,i=e=>W9({type:`reply`,id:t,value:e});try{if(await QPe,n===`stop`)return X9?.abort(),q9.abort(),G9.stop(),i(!0);if(n===`snapshot`)return i(await Q9());if(n===`cache_status`)return i(await SI());if(Y9)throw Error(`Wait for the current operation or stop it first.`);Y9=!0,X9=new AbortController,W9({type:`busy`,action:n,cachedOnly:r.cachedOnly===!0});try{let e;if(n===`load`)await G9.load(r,X9.signal),e=G9.device;else if(n===`prompt`)Z9=0,await q9.prompt(r.text),e=await Q9();else if(n===`shell`)e=await K9.bash.exec(r.command,{signal:X9.signal}),await $9();else if(n===`write`)await K9.write(r.path,r.content),e=await $9();else if(n===`new_chat`)q9.reset(),e=await $9();else if(n===`read`)e=await K9.read(r.path);else throw Error(`Unknown action: `+n);i(e)}finally{Y9=!1,X9=void 0,W9({type:`idle`})}}catch(e){W9({type:`reply`,id:t,error:e?.name===`AbortError`?`Stopped.`:String(e?.message??e),errorName:e?.name,errorCode:e?.code})}}; \ No newline at end of file diff --git a/assets/index-D2Hvfy3l.js b/assets/index-D2Hvfy3l.js new file mode 100644 index 0000000000000000000000000000000000000000..5709d78872dbba473c3eb3569826c4ac9d13acd4 --- /dev/null +++ b/assets/index-D2Hvfy3l.js @@ -0,0 +1,160 @@ +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=Object.defineProperty,u=Object.getOwnPropertyDescriptor,d=(e,t)=>{for(var n in t)l(e,n,{get:t[n],enumerable:!0})},f=(e,t,n,r)=>{for(var i=r>1?void 0:r?u(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&l(t,n,i),i},p=(e,t)=>(n,r)=>t(n,r,e),m=`Terminal input`,h={get:()=>m,set:e=>m=e},g=`Too much output to announce, navigate to rows manually to read`,_={get:()=>g,set:e=>g=e};function v(e){return e.replace(/\r?\n/g,`\r`)}function y(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function b(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function x(e,t,n,r){e.stopPropagation(),e.clipboardData&&S(e.clipboardData.getData(`text/plain`),t,n,r)}function S(e,t,n,r){e=v(e),e=y(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function C(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function w(e,t,n,r,i){C(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function T(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function E(e,t=0,n=e.length){let r=``;for(let i=t;i65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var D=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},O=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},k=``,ee=` `,te=class e{constructor(){this.fg=0,this.bg=0,this.extended=new ne}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},ne=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},A=class e extends te{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new ne,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?T(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},re=`di$target`,j=`di$dependencies`,M=new Map;function N(e){return e[j]||[]}function P(e){if(M.has(e))return M.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);ie(t,e,r)};return t._id=e,M.set(e,t),t}function ie(e,t,n){t[re]===t?t[j].push({id:e,index:n}):(t[j]=[{id:e,index:n}],t[re]=t)}var F=P(`BufferService`),I=P(`CoreMouseService`),L=P(`CoreService`),R=P(`CharsetService`),ae=P(`InstantiationService`),oe=P(`LogService`),z=P(`OptionsService`),se=P(`OscLinkService`),ce=P(`UnicodeService`),le=P(`DecorationService`),ue=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new A,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;ti?i.activate(e,t,a):de(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};ue=f([p(0,F),p(1,z),p(2,se)],ue);function de(e,t){if(confirm(`Do you want to navigate to ${t}? + +WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var fe=P(`CharSizeService`),B=P(`CoreBrowserService`),pe=P(`MouseService`),me=P(`RenderService`),he=P(`SelectionService`),ge=P(`CharacterJoinerService`),_e=P(`ThemeService`),ve=P(`LinkProviderService`),ye=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Te.isErrorNoTelemetry(e)?new Te(e.message+` + +`+e.stack):Error(e.message+` + +`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function be(e){Se(e)||ye.onUnexpectedError(e)}var xe=`Canceled`;function Se(e){return e instanceof Ce||e instanceof Error&&e.name===xe&&e.message===xe}var Ce=class extends Error{constructor(){super(xe),this.name=this.message}};function we(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var Te=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},Ee=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function De(e,t=0){return e[e.length-(1+t)]}var Oe;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Oe||={});var ke=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||Oe.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};ke.empty=new ke(e=>{});function Ae(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var je;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Re(...e){return ze(()=>Le(e))}function ze(e){let t=Ne({dispose:Ae(()=>{Pe(t),e()})});return t}var Be=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,Ne(this)}dispose(){this._isDisposed||(Pe(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Le(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return Fe(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Fe(e,null))}};Be.DISABLE_DISPOSED_WARNING=!1;var Ve=Be,V=class{constructor(){this._store=new Ve,Ne(this),Fe(this._store,this)}dispose(){Pe(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};V.None=Object.freeze({dispose(){}});var He=class{constructor(){this._isDisposed=!1,Ne(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&Fe(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Pe(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&Fe(e,null),e}},Ue=typeof window==`object`?window:globalThis,We=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};We.Undefined=new We(void 0);var Ge=We,Ke=class{constructor(){this._first=Ge.Undefined,this._last=Ge.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Ge.Undefined}clear(){let e=this._first;for(;e!==Ge.Undefined;){let t=e.next;e.prev=Ge.Undefined,e.next=Ge.Undefined,e=t}this._first=Ge.Undefined,this._last=Ge.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new Ge(e);if(this._first===Ge.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==Ge.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Ge.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Ge.Undefined&&e.next!==Ge.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Ge.Undefined&&e.next===Ge.Undefined?(this._first=Ge.Undefined,this._last=Ge.Undefined):e.next===Ge.Undefined?(this._last=this._last.prev,this._last.next=Ge.Undefined):e.prev===Ge.Undefined&&(this._first=this._first.next,this._first.prev=Ge.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==Ge.Undefined;)yield e.element,e=e.next}},qe=globalThis.performance&&typeof globalThis.performance.now==`function`,Je=class e{static create(t){return new e(t)}constructor(e){this._now=qe&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Ye;(e=>{e.None=()=>V.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(Re(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new H({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new H({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new H({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new H({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new H({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new H;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new H(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Ve?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(Ye||={});var Xe=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Je,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Xe.all=new Set,Xe._idPool=0;var Ze=Xe,Qe=-1,$e=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t0||this._options?.leakWarningThreshold?new et(e?.onListenerError??be,this._options?.leakWarningThreshold??Qe):void 0,this._perfMon=this._options?._profName?new Ze(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new rt(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||be)(n),V.None}if(this._disposed)return V.None;t&&(e=e.bind(t));let r=new at(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=tt.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof at?(this._deliveryQueue??=new st,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=ze(()=>{i?.(),this._removeListener(r)});return n instanceof Ve?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*ot<=t.length){let e=0;for(let n=0;n0}},st=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},ct=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new H,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new H,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};ct.INSTANCE=new ct;var lt=ct;function ut(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}lt.INSTANCE.onDidChangeZoomLevel;function dt(e){return lt.INSTANCE.getZoomFactor(e)}lt.INSTANCE.onDidChangeFullscreen;var ft=typeof navigator==`object`?navigator.userAgent:``,pt=ft.indexOf(`Firefox`)>=0,mt=ft.indexOf(`AppleWebKit`)>=0,ht=ft.indexOf(`Chrome`)>=0,gt=!ht&&ft.indexOf(`Safari`)>=0;ft.indexOf(`Electron/`),ft.indexOf(`Android`);var _t=!1;if(typeof Ue.matchMedia==`function`){let e=Ue.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=Ue.matchMedia(`(display-mode: fullscreen)`);_t=e.matches,ut(Ue,e,({matches:e})=>{_t&&t.matches||(_t=e)})}function vt(){return _t}var yt=`en`,bt=!1,xt=!1,St=!1,Ct=!1,wt=!1,Tt=yt,Et,Dt=globalThis,Ot;typeof Dt.vscode<`u`&&typeof Dt.vscode.process<`u`?Ot=Dt.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(Ot=process);var kt=typeof Ot?.versions?.electron==`string`&&Ot?.type===`renderer`;if(typeof Ot==`object`){bt=Ot.platform===`win32`,xt=Ot.platform===`darwin`,St=Ot.platform===`linux`,St&&Ot.env.SNAP&&Ot.env.SNAP_REVISION,Ot.env.CI||Ot.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Tt=yt;let e=Ot.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Tt=t.resolvedLanguage||yt,t.languagePack?.translationsConfigFile}catch{}Ct=!0}else typeof navigator==`object`&&!kt?(Et=navigator.userAgent,bt=Et.indexOf(`Windows`)>=0,xt=Et.indexOf(`Macintosh`)>=0,(Et.indexOf(`Macintosh`)>=0||Et.indexOf(`iPad`)>=0||Et.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,St=Et.indexOf(`Linux`)>=0,Et?.indexOf(`Mobi`),wt=!0,Tt=globalThis._VSCODE_NLS_LANGUAGE||yt,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var At=bt,jt=xt,Mt=St,Nt=Ct;wt&&typeof Dt.importScripts==`function`&&Dt.origin;var Pt=Et,Ft=Tt,It;(e=>{function t(){return Ft}e.value=t;function n(){return Ft.length===2?Ft===`en`:Ft.length>=3&&Ft[0]===`e`&&Ft[1]===`n`&&Ft[2]===`-`}e.isDefaultVariant=n;function r(){return Ft===`en`}e.isDefault=r})(It||={});var Lt=typeof Dt.postMessage==`function`&&!Dt.importScripts;(()=>{if(Lt){let e=[];Dt.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n{let r=++t;e.push({id:r,callback:n}),Dt.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var Rt=!!(Pt&&Pt.indexOf(`Chrome`)>=0);Pt&&Pt.indexOf(`Firefox`),!Rt&&Pt&&Pt.indexOf(`Safari`),Pt&&Pt.indexOf(`Edg/`),Pt&&Pt.indexOf(`Android`);var zt=typeof navigator==`object`?navigator:{};Nt||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||zt&&zt.clipboard&&zt.clipboard.writeText,Nt||zt&&zt.clipboard&&zt.clipboard.readText,Nt||vt()||zt.keyboard,`ontouchstart`in Ue||zt.maxTouchPoints,Ue.PointerEvent&&(`ontouchstart`in Ue||navigator.maxTouchPoints);var Bt=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Vt=new Bt,Ht=new Bt,Ut=new Bt,Wt=Array(230),Gt;(e=>{function t(e){return Vt.keyCodeToStr(e)}e.toString=t;function n(e){return Vt.strToKeyCode(e)}e.fromString=n;function r(e){return Ht.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Ut.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Ht.strToKeyCode(e)||Ut.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Vt.keyCodeToStr(e)}e.toElectronAccelerator=o})(Gt||={});var Kt=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new qt([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},qt=class{constructor(e){if(e.length===0)throw we(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t{function t(t){return t===e.None||t===e.Cancelled||t instanceof cn?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Ye.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:on})})(sn||={});var cn=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?on:(this._emitter||=new H,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},ln=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Ee(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ee(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},un=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new Ee(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=ze(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var dn;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(dn||={});var fn=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new H,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};fn.EMPTY=fn.fromArray([]);function pn(e){return mn(e,0)}function mn(e,t){switch(typeof e){case`object`:return e===null?hn(349,t):Array.isArray(e)?vn(e,t):yn(e,t);case`string`:return _n(e,t);case`boolean`:return gn(e,t);case`number`:return hn(e,t);case`undefined`:return hn(937,t);default:return hn(617,t)}}function hn(e,t){return(t<<5)-t+e|0}function gn(e,t){return hn(e?433:863,t)}function _n(e,t){t=hn(149417,t);for(let n=0,r=e.length;nmn(t,e),t)}function yn(e,t){return t=hn(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=_n(n,t),mn(e[n],t)),t)}var{registerWindow:bn,getWindow:xn,getDocument:Sn,getWindows:Cn,getWindowsCount:wn,getWindowId:Tn,getWindowById:En,hasWindow:Dn,onDidRegisterWindow:On,onWillUnregisterWindow:kn,onDidUnregisterWindow:An}=function(){let e=new Map,t={window:Ue,disposables:new Ve};e.set(Ue.vscodeWindowId,t);let n=new H,r=new H,i=new H;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return V.None;let a=new Ve,o={window:t,disposables:a.add(new Ve)};return e.set(t.vscodeWindowId,o),a.add(ze(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(U(t,Bn.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:Ue},getDocument(e){return xn(e).document}}}(),jn=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function U(e,t,n,r){return new jn(e,t,n,r)}function Mn(e,t){return function(n){return t(new rn(e,n))}}function Nn(e){return function(t){return e(new $t(t))}}var Pn=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=Mn(xn(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=Nn(n)),U(e,t,i,r)},Fn,In=class extends un{constructor(e){super(),this.defaultTarget=e&&xn(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},Ln=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){be(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(Ln.sort),a.shift().execute();r.set(i,!1)};Fn=(t,r,a=0)=>{let o=Tn(t),s=new Ln(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var Rn=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};Rn.None=new Rn(0,0);function zn(e){let t=e.getBoundingClientRect(),n=xn(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=pn(n),a=r.get(i);if(a)a.users+=1;else{let o=new H,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(ze(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var Bn={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:mt?`webkitAnimationStart`:`animationstart`,ANIMATION_END:mt?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:mt?`webkitAnimationIteration`:`animationiteration`},Vn=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=Hn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Hn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Hn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Hn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Hn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Hn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Hn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Hn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Hn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Hn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Hn(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Hn(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Hn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Hn(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Hn(e){return typeof e==`number`?`${e}px`:e}function Un(e){return new Vn(e)}var Wn=class{constructor(){this._hooks=new Ve,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(ze(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=xn(e)}this._hooks.add(U(a,Bn.POINTER_MOVE,e=>{if(e.buttons!==n){this.stopMonitoring(!0);return}e.preventDefault(),this._pointerMoveCallback(e)})),this._hooks.add(U(a,Bn.POINTER_UP,e=>this.stopMonitoring(!0)))}};function Gn(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Kn;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Kn||={});var qn=class e extends V{constructor(){super(),this.dispatched=!1,this.targets=new Ke,this.ignoreTargets=new Ke,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Ye.runAndSubscribe(On,({window:e,disposables:t})=>{t.add(U(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(U(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(U(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:Ue,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Ie(new e),ze(e.INSTANCE.targets.push(t))):V.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Ie(new e),ze(e.INSTANCE.ignoreTargets.push(t))):V.None}static isTouchDevice(){return`ontouchstart`in Ue||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n=e.HOLD_DELAY&&Math.abs(s.initialPageX-De(s.rollingPageX))<30&&Math.abs(s.initialPageY-De(s.rollingPageY))<30){let e=this.newGestureEvent(Kn.Contextmenu,s.initialTarget);e.pageX=De(s.rollingPageX),e.pageY=De(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=De(s.rollingPageX),n=De(s.rollingPageY),i=De(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Kn.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Kn.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===Kn.Change||t.type===Kn.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=Fn(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Kn.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};qn.SCROLL_FRICTION=-.005,qn.HOLD_DELAY=700,qn.CLEAR_TAP_COUNT_TIME=400,f([Gn],qn,`isTouchDevice`,1);var Jn=qn,Yn=class extends V{onclick(e,t){this._register(U(e,Bn.CLICK,n=>t(new rn(xn(e),n))))}onmousedown(e,t){this._register(U(e,Bn.MOUSE_DOWN,n=>t(new rn(xn(e),n))))}onmouseover(e,t){this._register(U(e,Bn.MOUSE_OVER,n=>t(new rn(xn(e),n))))}onmouseleave(e,t){this._register(U(e,Bn.MOUSE_LEAVE,n=>t(new rn(xn(e),n))))}onkeydown(e,t){this._register(U(e,Bn.KEY_DOWN,e=>t(new $t(e))))}onkeyup(e,t){this._register(U(e,Bn.KEY_UP,e=>t(new $t(e))))}oninput(e,t){this._register(U(e,Bn.INPUT,t))}onblur(e,t){this._register(U(e,Bn.BLUR,t))}onfocus(e,t){this._register(U(e,Bn.FOCUS,t))}onchange(e,t){this._register(U(e,Bn.CHANGE,t))}ignoreGesture(e){return Jn.ignoreTarget(e)}},Xn=11,Zn=class extends Yn{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Xn+`px`,this.domNode.style.height=Xn+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new Wn),this._register(Pn(this.bgDomNode,Bn.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(Pn(this.domNode,Bn.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new In),this._pointerdownScheduleRepeatTimer=this._register(new ln)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,xn(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Qn=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},$n=class extends V{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new H),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Qn(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new rr(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=rr.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},er=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function tr(e,t){let n=t-e;return function(t){return e+n*ar(t)}}function nr(e,t,n){return function(r){return r2.5*n){let r,i;return e{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},sr=140,cr=class extends Yn{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new or(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Wn),this._shouldRender=!0,this.domNode=Un(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(U(this.domNode.domNode,Bn.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Zn(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Un(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(U(this.slider.domNode,Bn.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=zn(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(At&&a>sr){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},lr=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};gr.INSTANCE=new gr;var _r=gr,vr=class extends Yn{constructor(e,t,n){super(),this._onScroll=this._register(new H),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new H),this.onWillScroll=this._onWillScroll.event,this._options=br(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new dr(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new ur(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Un(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Un(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Un(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new ln),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Le(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,jt&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new an(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Le(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(U(this._listenOnDomNode,Bn.MOUSE_WHEEL,e=>{this._onMouseWheel(new an(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=_r.INSTANCE;mr&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!jt&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=pr*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=pr*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(mr&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),fr)}},yr=class extends vr{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function br(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,jt&&(t.className+=` mac`),t}var xr=class extends V{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new H),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new $n({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>Fn(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new yr(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Ye.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ze(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(ze(()=>this._styleElement.remove())),this._register(Ye.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};xr=f([p(2,F),p(3,B),p(4,I),p(5,_e),p(6,z),p(7,me)],xr);var Sr=class extends V{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(ze(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};Sr=f([p(1,F),p(2,B),p(3,le),p(4,me)],Sr);var Cr=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},wr={full:0,left:0,center:0,right:0},Tr={full:0,left:0,center:0,right:0},Er={full:0,left:0,center:0,right:0},Dr=class extends V{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new Cr,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(ze(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Tr.full=this._canvas.width,Tr.left=e,Tr.center=t,Tr.right=e,this._refreshDrawHeightConstants(),Er.full=1,Er.left=1,Er.center=1+Tr.left,Er.right=1+Tr.left+Tr.center}_refreshDrawHeightConstants(){wr.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);wr.left=t,wr.center=t,wr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*wr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Er[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-wr[e.position||`full`]/2),Tr[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+wr[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Dr=f([p(2,F),p(3,le),p(4,me),p(5,z),p(6,_e),p(7,B)],Dr);var W;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=` +`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))(W||={});var Or;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(Or||={});var kr;(e=>e.ST=`${W.ESC}\\`)(kr||={});var Ar=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};Ar=f([p(2,F),p(3,z),p(4,L),p(5,me)],Ar);var jr=0,Mr=0,Nr=0,Pr=0,Fr={css:`#00000000`,rgba:0},Ir;(e=>{function t(e,t,n,r){return r===void 0?`#${Vr(e)}${Vr(t)}${Vr(n)}`:`#${Vr(e)}${Vr(t)}${Vr(n)}${Vr(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(Ir||={});var Lr;(e=>{function t(e,t){if(Pr=(t.rgba&255)/255,Pr===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return jr=a+Math.round((n-a)*Pr),Mr=o+Math.round((r-o)*Pr),Nr=s+Math.round((i-s)*Pr),{css:Ir.toCss(jr,Mr,Nr),rgba:Ir.toRgba(jr,Mr,Nr)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=Br.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return Ir.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[jr,Mr,Nr]=Br.toChannels(t),{css:Ir.toCss(jr,Mr,Nr),rgba:t}}e.opaque=i;function a(e,t){return Pr=Math.round(t*255),[jr,Mr,Nr]=Br.toChannels(e.rgba),{css:Ir.toCss(jr,Mr,Nr,Pr),rgba:Ir.toRgba(jr,Mr,Nr,Pr)}}e.opacity=a;function o(e,t){return Pr=e.rgba&255,a(e,Pr*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(Lr||={});var Rr;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return jr=parseInt(e.slice(1,2).repeat(2),16),Mr=parseInt(e.slice(2,3).repeat(2),16),Nr=parseInt(e.slice(3,4).repeat(2),16),Ir.toColor(jr,Mr,Nr);case 5:return jr=parseInt(e.slice(1,2).repeat(2),16),Mr=parseInt(e.slice(2,3).repeat(2),16),Nr=parseInt(e.slice(3,4).repeat(2),16),Pr=parseInt(e.slice(4,5).repeat(2),16),Ir.toColor(jr,Mr,Nr,Pr);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return jr=parseInt(r[1]),Mr=parseInt(r[2]),Nr=parseInt(r[3]),Pr=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Ir.toColor(jr,Mr,Nr,Pr);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[jr,Mr,Nr,Pr]=t.getImageData(0,0,1,1).data,Pr!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:Ir.toRgba(jr,Mr,Nr,Pr),css:e}}e.toColor=r})(Rr||={});var zr;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(zr||={});var Br;(e=>{function t(e,t){if(Pr=(t&255)/255,Pr===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return jr=a+Math.round((n-a)*Pr),Mr=o+Math.round((r-o)*Pr),Nr=s+Math.round((i-s)*Pr),Ir.toRgba(jr,Mr,Nr)}e.blend=t;function n(e,t,n){let a=zr.relativeLuminance(e>>8),o=zr.relativeLuminance(t>>8);if(Hr(a,o)>8));if(sHr(a,zr.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Hr(a,zr.relativeLuminance(s>>8));if(cHr(a,zr.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Hr(zr.relativeLuminance2(o,s,c),zr.relativeLuminance2(r,i,a));for(;l0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Hr(zr.relativeLuminance2(o,s,c),zr.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Hr(zr.relativeLuminance2(o,s,c),zr.relativeLuminance2(r,i,a));for(;l>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(Br||={});function Vr(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Hr(e,t){return e1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t=E,re=k,j=this._workCell;if(f.length>0&&k===f[0][0]&&A){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v=r[1],A?(ne=!0,j=new Ur(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),re=r[1]-1,m=j.getWidth()):E=r[1]}let M=this._isCellInSelection(k,t),N=n&&k===a,P=O&&k>=l&&k<=u,ie=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{ie=!0});let F=j.getChars()||ee;if(F===` `&&(j.isUnderline()||j.isOverline())&&(F=`\xA0`),T=m*s-c.get(F,j.isBold(),j.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(M&&w||!M&&!w&&j.bg===y)&&(M&&w&&p.selectionForeground||j.fg===b)&&j.extended.ext===x&&P===S&&T===C&&!N&&!ne&&!ie&&A){j.isInvisible()?_+=ee:_+=F,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=j.bg,b=j.fg,x=j.extended.ext,S=P,C=T,w=M,ne&&a>=k&&a<=re&&(a=k),!this._coreService.isCursorHidden&&N&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`)}}if(j.isBold()&&D.push(`xterm-bold`),j.isItalic()&&D.push(`xterm-italic`),j.isDim()&&D.push(`xterm-dim`),_=j.isInvisible()?ee:j.getChars()||ee,j.isUnderline()&&(D.push(`xterm-underline-${j.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!j.isUnderlineColorDefault())){if(j.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${te.toColorRGB(j.getUnderlineColor()).join(`,`)})`;else{let e=j.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&j.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}j.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),j.isStrikethrough()&&D.push(`xterm-strikethrough`),P&&(h.style.textDecoration=`underline`);let I=j.getFgColor(),L=j.getFgColorMode(),R=j.getBgColor(),ae=j.getBgColorMode(),oe=!!j.isInverse();if(oe){let e=I;I=R,R=e;let t=L;L=ae,ae=t}let z,se,ce=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&ce||(e.backgroundColorRGB&&(ae=50331648,R=e.backgroundColorRGB.rgba>>8&16777215,z=e.backgroundColorRGB),e.foregroundColorRGB&&(L=50331648,I=e.foregroundColorRGB.rgba>>8&16777215,se=e.foregroundColorRGB),ce=e.options.layer===`top`)}),!ce&&M&&(z=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,R=z.rgba>>8&16777215,ae=50331648,ce=!0,p.selectionForeground&&(L=50331648,I=p.selectionForeground.rgba>>8&16777215,se=p.selectionForeground)),ce&&D.push(`xterm-decoration-top`);let le;switch(ae){case 16777216:case 33554432:le=p.ansi[R],D.push(`xterm-bg-${R}`);break;case 50331648:le=Ir.toColor(R>>16,R>>8&255,R&255),this._addStyle(h,`background-color:#${Zr((R>>>0).toString(16),`0`,6)}`);break;default:oe?(le=p.foreground,D.push(`xterm-bg-257`)):le=p.background}switch(z||j.isDim()&&(z=Lr.multiplyOpacity(le,.5)),L){case 16777216:case 33554432:j.isBold()&&I<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(I+=8),this._applyMinimumContrast(h,le,p.ansi[I],j,z,void 0)||D.push(`xterm-fg-${I}`);break;case 50331648:let e=Ir.toColor(I>>16&255,I>>8&255,I&255);this._applyMinimumContrast(h,le,e,j,z,se)||this._addStyle(h,`color:#${Zr(I.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,le,p.foreground,j,z,se)||oe&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!N&&!ne&&!ie&&A?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=re}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||qr(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=Lr.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};Xr=f([p(1,ge),p(2,z),p(3,B),p(4,L),p(5,le),p(6,_e)],Xr);function Zr(e,t,n){for(;e.length0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},$r=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function ei(){return new $r}var ti=`xterm-dom-renderer-owner-`,ni=`xterm-rows`,ri=`xterm-fg-`,ii=`xterm-bg-`,ai=`xterm-focus`,oi=`xterm-selection`,si=1,ci=class extends V{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=si++,this._rowElements=[],this._selectionRenderModel=ei(),this.onRequestRedraw=this._register(new H).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(ni),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(oi),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=Jr(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Xr,document),this._element.classList.add(ti+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(ze(()=>{this._element.classList.remove(ti+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Qr(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${ni} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${ni} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${ni} .xterm-dim { color: ${Lr.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${ni}.${ai} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${ni}.${ai} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${ni}.${ai} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${ni} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${oi} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${oi} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${oi} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${ri}${n} { color: ${r.css}; }${this._terminalSelector} .${ri}${n}.xterm-dim { color: ${Lr.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${ii}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${ri}257 { color: ${Lr.opaque(e.background).css}; }${this._terminalSelector} .${ri}257.xterm-dim { color: ${Lr.multiplyOpacity(Lr.opaque(e.background),.5).css}; }${this._terminalSelector} .${ii}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ai),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ai),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${ti}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};ci=f([p(7,ae),p(8,fe),p(9,z),p(10,F),p(11,L),p(12,B),p(13,_e)],ci);var li=class extends V{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new H),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new fi(this._optionsService))}catch{this._measureStrategy=this._register(new di(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};li=f([p(2,z)],li);var ui=class extends V{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},di=class extends ui{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},fi=class extends ui{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},pi=class extends V{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new mi(this._window)),this._onDprChange=this._register(new H),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new H),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(Ye.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(U(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(U(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},mi=class extends V{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new He),this._onDprChange=this._register(new H),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ze(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=U(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},hi=class extends V{constructor(){super(),this.linkProviders=[],this._register(ze(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function gi(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function _i(e,t,n,r,i,a,o,s,c){if(!a)return;let l=gi(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var vi=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return _i(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=gi(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};vi=f([p(0,me),p(1,fe)],vi);var yi=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},bi={};d(bi,{getSafariVersion:()=>Di,isChromeOS:()=>Ni,isFirefox:()=>wi,isIpad:()=>ki,isIphone:()=>Ai,isLegacyEdge:()=>Ti,isLinux:()=>Mi,isMac:()=>Oi,isNode:()=>xi,isSafari:()=>Ei,isWindows:()=>ji});var xi=typeof process<`u`&&`title`in process,Si=xi?`node`:navigator.userAgent,Ci=xi?`node`:navigator.platform,wi=Si.includes(`Firefox`),Ti=Si.includes(`Edge`),Ei=/^((?!chrome|android).)*safari/i.test(Si);function Di(){if(!Ei)return 0;let e=Si.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Oi=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(Ci),ki=Ci===`iPad`,Ai=Ci===`iPhone`,ji=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(Ci),Mi=Ci.indexOf(`Linux`)>=0,Ni=/\bCrOS\b/.test(Si),Pi=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ii){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},Fi=class extends Pi{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Ii=class extends Pi{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Li=!xi&&`requestIdleCallback`in window?Ii:Fi,Ri=class{constructor(){this._queue=new Li}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},zi=class extends V{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new He),this._pausedResizeTask=new Ri,this._observerDisposable=this._register(new He),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new H),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new H),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new H),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new H),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new yi((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Bi(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ze(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=ze(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};zi=f([p(2,z),p(3,fe),p(4,L),p(5,le),p(6,F),p(7,B),p(8,_e)],zi);var Bi=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Vi(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return Wi(i,a,e,t,n,r)+Gi(a,t,n,r)+Ki(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,$i(Math.abs(i-e),Qi(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return $i(Ui(a>t?e:i,n)+(s-1)*n.cols+1+Hi(a>t?i:e,n),Qi(o,r))}function Hi(e,t){return e-1}function Ui(e,t){return t.cols-e}function Wi(e,t,n,r,i,a){return Gi(t,r,i,a).length===0?``:$i(Zi(e,t,e,t-Ji(t,i),!1,i).length,Qi(`D`,a))}function Gi(e,t,n,r){let i=e-Ji(e,n),a=t-Ji(t,n);return $i(Math.abs(i-a)-qi(e,t,n),Qi(Xi(e,t),r))}function Ki(e,t,n,r,i,a){let o;o=Gi(t,r,i,a).length>0?r-Ji(r,i):t;let s=r,c=Yi(e,t,n,r,i,a);return $i(Zi(e,o,n,s,c===`C`,i).length,Qi(c,a))}function qi(e,t,n){let r=0,i=e-Ji(e,n),a=t-Ji(t,n);for(let o=0;o=0&&e0?r-Ji(r,i):t,e=n&&ot?`A`:`B`}function Zi(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&sa.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Qi(e,t){let n=t?`O`:`[`;return W.ESC+n+e}function $i(e,t){e=Math.floor(e);let n=``;for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function ta(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var na=50,ra=15,ia=50,aa=500,oa=RegExp(`\xA0`,`g`),sa=class extends V{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new A,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new H),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new H),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new H),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new H),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new ea(this._bufferService),this._activeSelectionMode=0,this._register(ze(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]e.replace(oa,` `)).join(ji?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),Mi&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=ta(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=gi(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-na),na),t/=na,t/Math.abs(t)+Math.round(t*(ra-1)))}shouldForceSelection(e){return Oi?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),ia)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Oi&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=ta(n,this._bufferService.cols)}};sa=f([p(3,F),p(4,L),p(5,pe),p(6,z),p(7,me),p(8,B)],sa);var ca=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},la=class{constructor(){this._color=new ca,this._css=new ca}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},ua=Object.freeze((()=>{let e=[Rr.toColor(`#2e3436`),Rr.toColor(`#cc0000`),Rr.toColor(`#4e9a06`),Rr.toColor(`#c4a000`),Rr.toColor(`#3465a4`),Rr.toColor(`#75507b`),Rr.toColor(`#06989a`),Rr.toColor(`#d3d7cf`),Rr.toColor(`#555753`),Rr.toColor(`#ef2929`),Rr.toColor(`#8ae234`),Rr.toColor(`#fce94f`),Rr.toColor(`#729fcf`),Rr.toColor(`#ad7fa8`),Rr.toColor(`#34e2e2`),Rr.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:Ir.toCss(r,i,a),rgba:Ir.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:Ir.toCss(n,n,n),rgba:Ir.toRgba(n,n,n)})}return e})()),da=Rr.toColor(`#ffffff`),fa=Rr.toColor(`#000000`),pa=Rr.toColor(`#ffffff`),ma=fa,ha={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},ga=da,_a=class extends V{constructor(e){super(),this._optionsService=e,this._contrastCache=new la,this._halfContrastCache=new la,this._onChangeColors=this._register(new H),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:da,background:fa,cursor:pa,cursorAccent:ma,selectionForeground:void 0,selectionBackgroundTransparent:ha,selectionBackgroundOpaque:Lr.blend(fa,ha),selectionInactiveBackgroundTransparent:ha,selectionInactiveBackgroundOpaque:Lr.blend(fa,ha),scrollbarSliderBackground:Lr.opacity(da,.2),scrollbarSliderHoverBackground:Lr.opacity(da,.4),scrollbarSliderActiveBackground:Lr.opacity(da,.5),overviewRulerBorder:da,ansi:ua.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=G(e.foreground,da),t.background=G(e.background,fa),t.cursor=Lr.blend(t.background,G(e.cursor,pa)),t.cursorAccent=Lr.blend(t.background,G(e.cursorAccent,ma)),t.selectionBackgroundTransparent=G(e.selectionBackground,ha),t.selectionBackgroundOpaque=Lr.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=G(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Lr.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?G(e.selectionForeground,Fr):void 0,t.selectionForeground===Fr&&(t.selectionForeground=void 0),Lr.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Lr.opacity(t.selectionBackgroundTransparent,.3)),Lr.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Lr.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=G(e.scrollbarSliderBackground,Lr.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=G(e.scrollbarSliderHoverBackground,Lr.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=G(e.scrollbarSliderActiveBackground,Lr.opacity(t.foreground,.5)),t.overviewRulerBorder=G(e.overviewRulerBorder,ga),t.ansi=ua.slice(),t.ansi[0]=G(e.black,ua[0]),t.ansi[1]=G(e.red,ua[1]),t.ansi[2]=G(e.green,ua[2]),t.ansi[3]=G(e.yellow,ua[3]),t.ansi[4]=G(e.blue,ua[4]),t.ansi[5]=G(e.magenta,ua[5]),t.ansi[6]=G(e.cyan,ua[6]),t.ansi[7]=G(e.white,ua[7]),t.ansi[8]=G(e.brightBlack,ua[8]),t.ansi[9]=G(e.brightRed,ua[9]),t.ansi[10]=G(e.brightGreen,ua[10]),t.ansi[11]=G(e.brightYellow,ua[11]),t.ansi[12]=G(e.brightBlue,ua[12]),t.ansi[13]=G(e.brightMagenta,ua[13]),t.ansi[14]=G(e.brightCyan,ua[14]),t.ansi[15]=G(e.brightWhite,ua[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;re.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},ba={trace:0,debug:1,info:2,warn:3,error:4,off:5},xa=`xterm.js: `,Sa=class extends V{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),Ca=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=ba[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;tthis._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*K+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*K+0]=e|2097152|t[2]<<22):this._data[e*K+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*K+0]>>22}hasWidth(e){return this._data[e*K+0]&12582912}getFg(e){return this._data[e*K+1]}getBg(e){return this._data[e*K+2]}hasContent(e){return this._data[e*K+0]&4194303}getCodePoint(e){let t=this._data[e*K+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*K+0]&2097152}getString(e){let t=this._data[e*K+0];return t&2097152?this._combined[e]:t&2097151?T(t&2097151):``}isProtected(e){return this._data[e*K+2]&536870912}loadCell(e,t){return Ea=e*K,t.content=this._data[Ea+0],t.fg=this._data[Ea+1],t.bg=this._data[Ea+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*K+0]=t.content,this._data[e*K+1]=t.fg,this._data[e*K+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*K+0]=t|n<<22,this._data[e*K+1]=r.fg,this._data[e*K+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*K+0];r&2097152?this._combined[e]+=T(t):r&2097151?(this._combined[e]=T(r&2097151)+T(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*K+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;rthis.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*Da=0;--e)if(this._data[e*K+0]&4194303)return e+(this._data[e*K+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*K+0]&4194303||this._data[e*K+2]&50331648)return e+(this._data[e*K+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t>22||1}return r&&r.push(t),i}};function ka(e,t,n,r,i,a){let o=[];for(let s=0;s=s&&r0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function Aa(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;oNa(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;sc&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function Na(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var Pa=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new H),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Le(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};Pa._nextId=1;var Fa=Pa,Ia={},La=Ia.B;Ia[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},Ia.A={"#":`£`},Ia.B=void 0,Ia[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},Ia.C=Ia[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Ia.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},Ia.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},Ia.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},Ia.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},Ia.E=Ia[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},Ia.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},Ia.H=Ia[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Ia[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var Ra=4294967295,za=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Ta.clone(),this.savedCharset=La,this.markers=[],this._nullCell=A.fromCharData([0,k,1,0]),this._whitespaceCell=A.fromCharData([0,ee,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Li,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new wa(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new ne),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new ne),this._whitespaceCell}getBlankLine(e,t){return new Oa(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eRa?Ra:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Ta);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new wa(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(Ta),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new Oa(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=ka(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ta),n);if(r.length>0){let n=Aa(this.lines,r);ja(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(Ta),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=Na(c,Math.max(g,0),this._cols))}for(let t=0;t0;)this.ybase===0?this.y0){let e=[],t=[];for(let e=0;e=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.linee.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Ba=class extends V{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new H),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new za(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new za(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Va=2,Ha=1,Ua=class extends V{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new H),this.onResize=this._onResize.event,this._onScroll=this._register(new H),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Va),this.rows=Math.max(e.rawOptions.rows||0,Ha),this.buffers=this._register(new Ba(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Ua=f([p(0,z)],Ua);var Wa={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Oi,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Ga=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Ka=class extends V{constructor(e){super(),this._onOptionChange=this._register(new H),this.onOptionChange=this._onOptionChange.event;let t={...Wa};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ze(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Wa))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Wa))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Wa[e],!qa(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Wa[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Ga.includes(t)?t:Wa[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function qa(e){return e===`block`||e===`underline`||e===`bar`}function Ja(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Ja(e[r],t-1);return n}var Ya=Object.freeze({insertMode:!1}),Xa=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Za=class extends V{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new H),this.onData=this._onData.event,this._onUserInput=this._register(new H),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new H),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new H),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Ja(Ya),this.decPrivateModes=Ja(Xa)}reset(){this.modes=Ja(Ya),this.decPrivateModes=Ja(Xa)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Za=f([p(0,F),p(1,oe),p(2,z)],Za);var Qa={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function $a(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var eo=String.fromCharCode,to={DEFAULT:e=>{let t=[$a(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${eo(t[0])}${eo(t[1])}${eo(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${$a(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${$a(e,!0)};${e.x};${e.y}${t}`}},no=class extends V{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new H),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Qa))this.addProtocol(e,Qa[e]);for(let e of Object.keys(to))this.addEncoding(e,to[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};no=f([p(0,F),p(1,L),p(2,z)],no);var ro=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],io=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],ao;function oo(e,t){let n=0,r=t.length-1,i;if(et[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=co.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return co.createPropertyValue(0,n,r)}},co=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new H,this.onChange=this._onChange.event;let e=new so;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},lo=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function uo(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var fo=2147483647,po=256,mo=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>po)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>fo?fo:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>fo?fo:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,fo):e}},ho=[],go=class{constructor(){this._state=0,this._active=ho,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=ho}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=ho,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||ho,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,E(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=ho,this._id=-1,this._state=0}}},_o=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=E(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},vo=[],yo=class{constructor(){this._handlers=Object.create(null),this._active=vo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=vo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=vo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||vo,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,E(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=vo,this._ident=0}},bo=new mo;bo.addParam(0);var xo=class{constructor(e){this._handler=e,this._data=``,this._params=bo,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():bo,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=E(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=bo,this._data=``,this._hitLimit=!1,e));return this._params=bo,this._data=``,this._hitLimit=!1,t}},So=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;it),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Co,0,2,0),e.add(Co,8,5,8),e.add(Co,6,0,6),e.add(Co,11,0,11),e.add(Co,13,13,13),e}(),To=class extends V{constructor(e=wo){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new mo,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ze(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new go),this._dcsParser=this._register(new yo),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;tr||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n>4){case 2:for(let i=n+1;;++i){if(i>=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r=t||(r=e[i])<32||r>127&&r>4:i>>8}return n}}function ko(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function Ao(e,t=16){let[n,r,i]=e;return`rgb:${ko(n,t)}/${ko(r,t)}/${ko(i,t)}`}var jo={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Mo=131072,No=10;function Po(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Fo=5e3,Io=0,Lo=class extends V{constructor(e,t,n,r,i,a,o,s,c=new To){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new D,this._utf8Decoder=new O,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ta.clone(),this._eraseAttrDataInternal=Ta.clone(),this._onRequestBell=this._register(new H),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new H),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new H),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new H),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new H),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new H),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new H),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new H),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new H),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new H),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new H),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new H),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new H),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Ro(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(W.BEL,()=>this.bell()),this._parser.setExecuteHandler(W.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(W.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(W.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(W.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(W.BS,()=>this.backspace()),this._parser.setExecuteHandler(W.HT,()=>this.tab()),this._parser.setExecuteHandler(W.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(W.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Or.IND,()=>this.index()),this._parser.setExecuteHandler(Or.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Or.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new _o(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new _o(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new _o(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new _o(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new _o(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new _o(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new _o(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new _o(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new _o(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new _o(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new _o(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new _o(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in Ia)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new xo((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),Fo))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${Fo} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Mo&&(a=this._parseStack.position+Mo)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.lengthMo)for(let t=a;t0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;ps){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof Oa&&d.copyCellsFrom(e,t,0,m,!1);t=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!Po(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new xo(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _o(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=s;for(let e=1;e0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(W.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(W.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(W.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(W.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(W.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${W.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=te.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Ta.fg,e.bg=Ta.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=Ta.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=Ta.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=Ta.fg&16777215,r.bg&=-67108864,r.bg|=Ta.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${W.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${W.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${W.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Ta.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Po(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${W.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>No&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>No&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(zo(n)){if(r===`?`)t.push({type:0,index:n});else{let e=Oo(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=Oo(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Ta.clone(),this._eraseAttrDataInternal=Ta.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new A;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${W.ESC}${e}${W.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Ro=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Io=e,e=t,t=Io),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Ro=f([p(0,F)],Ro);function zo(e){return 0<=e&&e<256}var Bo=5e7,Vo=12,Ho=50,Uo=class extends V{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new H),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Bo)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=Vo?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=Vo)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Ho&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Wo=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Wo=f([p(0,F)],Wo);var Go=!1,Ko=class extends V{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new He),this._onBinary=this._register(new H),this.onBinary=this._onBinary.event,this._onData=this._register(new H),this.onData=this._onData.event,this._onLineFeed=this._register(new H),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new H),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new H),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new H),this._instantiationService=new ya,this.optionsService=this._register(new Ka(e)),this._instantiationService.setService(z,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Ua)),this._instantiationService.setService(F,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Sa)),this._instantiationService.setService(oe,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Za)),this._instantiationService.setService(L,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(no)),this._instantiationService.setService(I,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(co)),this._instantiationService.setService(ce,this.unicodeService),this._charsetService=this._instantiationService.createInstance(lo),this._instantiationService.setService(R,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Wo),this._instantiationService.setService(se,this._oscLinkService),this._inputHandler=this._register(new Lo(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Ye.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Ye.forward(this._bufferService.onResize,this._onResize)),this._register(Ye.forward(this.coreService.onData,this._onData)),this._register(Ye.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new Uo((e,t)=>this._inputHandler.parse(e,t))),this._register(Ye.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new H),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Go&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),Go=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Va),t=Math.max(t,Ha),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(uo.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(uo(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ze(()=>{for(let t of e)t.dispose()})}}},qo={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function Jo(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?W.ESC+`OA`:W.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?W.ESC+`OD`:W.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?W.ESC+`OC`:W.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?W.ESC+`OB`:W.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:W.DEL,e.altKey&&(i.key=W.ESC+i.key);break;case 9:if(e.shiftKey){i.key=W.ESC+`[Z`;break}i.key=W.HT,i.cancel=!0;break;case 13:i.key=e.altKey?W.ESC+W.CR:W.CR,i.cancel=!0;break;case 27:i.key=W.ESC,e.altKey&&(i.key=W.ESC+W.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?W.ESC+`[1;`+(a+1)+`D`:t?W.ESC+`OD`:W.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?W.ESC+`[1;`+(a+1)+`C`:t?W.ESC+`OC`:W.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?W.ESC+`[1;`+(a+1)+`A`:t?W.ESC+`OA`:W.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?W.ESC+`[1;`+(a+1)+`B`:t?W.ESC+`OB`:W.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=W.ESC+`[2~`);break;case 46:i.key=a?W.ESC+`[3;`+(a+1)+`~`:W.ESC+`[3~`;break;case 36:i.key=a?W.ESC+`[1;`+(a+1)+`H`:t?W.ESC+`OH`:W.ESC+`[H`;break;case 35:i.key=a?W.ESC+`[1;`+(a+1)+`F`:t?W.ESC+`OF`:W.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?W.ESC+`[5;`+(a+1)+`~`:W.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?W.ESC+`[6;`+(a+1)+`~`:W.ESC+`[6~`;break;case 112:i.key=a?W.ESC+`[1;`+(a+1)+`P`:W.ESC+`OP`;break;case 113:i.key=a?W.ESC+`[1;`+(a+1)+`Q`:W.ESC+`OQ`;break;case 114:i.key=a?W.ESC+`[1;`+(a+1)+`R`:W.ESC+`OR`;break;case 115:i.key=a?W.ESC+`[1;`+(a+1)+`S`:W.ESC+`OS`;break;case 116:i.key=a?W.ESC+`[15;`+(a+1)+`~`:W.ESC+`[15~`;break;case 117:i.key=a?W.ESC+`[17;`+(a+1)+`~`:W.ESC+`[17~`;break;case 118:i.key=a?W.ESC+`[18;`+(a+1)+`~`:W.ESC+`[18~`;break;case 119:i.key=a?W.ESC+`[19;`+(a+1)+`~`:W.ESC+`[19~`;break;case 120:i.key=a?W.ESC+`[20;`+(a+1)+`~`:W.ESC+`[20~`;break;case 121:i.key=a?W.ESC+`[21;`+(a+1)+`~`:W.ESC+`[21~`;break;case 122:i.key=a?W.ESC+`[23;`+(a+1)+`~`:W.ESC+`[23~`;break;case 123:i.key=a?W.ESC+`[24;`+(a+1)+`~`:W.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=W.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=W.DEL:e.keyCode===219?i.key=W.ESC:e.keyCode===220?i.key=W.FS:e.keyCode===221&&(i.key=W.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=qo[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=W.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=W.ESC+n}else if(e.keyCode===32)i.key=W.ESC+(e.ctrlKey?W.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=W.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=W.US),e.key===`@`&&(i.key=W.NUL))}return i}var Yo=0,Xo=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Li,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Li,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Yo=this._search(t),Yo===-1)||this._getKey(this._array[Yo])!==t)return!1;do if(this._array[Yo]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Yo),!0;while(++Yoe-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Yo=this._search(e),!(Yo<0||Yo>=this._array.length)&&this._getKey(this._array[Yo])===e))do yield this._array[Yo];while(++Yo=this._array.length)&&this._getKey(this._array[Yo])===e))do t(this._array[Yo]);while(++Yo=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},Zo=0,Qo=0,$o=class extends V{constructor(){super(),this._decorations=new Xo(e=>e?.marker.line),this._onDecorationRegistered=this._register(new H),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new H),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ze(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new es(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e{Zo=t.options.x??0,Qo=Zo+(t.options.width??1),e>=Zo&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},rs=20,is=class extends V{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;ethis._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new ns(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(U(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ze(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===rs+1&&(this._liveRegion.textContent+=_.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;ee;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{Le(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(U(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(U(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(U(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(U(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;tthis._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;ethis._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&os(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Le(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};as=f([p(1,pe),p(2,me),p(3,F),p(4,ve)],as);function os(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var ss=class extends Ko{constructor(e={}){super(e),this._linkifier=this._register(new He),this.browser=bi,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new He),this._onCursorMove=this._register(new H),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new H),this.onKey=this._onKey.event,this._onRender=this._register(new H),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new H),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new H),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new H),this.onBell=this._onBell.event,this._onFocus=this._register(new H),this._onBlur=this._register(new H),this._onA11yCharEmitter=this._register(new H),this._onA11yTabEmitter=this._register(new H),this._onWillOpen=this._register(new H),this._setup(),this._decorationService=this._instantiationService.createInstance($o),this._instantiationService.setService(le,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(hi),this._instantiationService.setService(ve,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(ue)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Ye.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ye.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ye.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ye.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(ze(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=Lr.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${W.ESC}]${n};${Ao(r)}${kr.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Ir.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Ir.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(is,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(W.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(W.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(U(this.element,`copy`,e=>{this.hasSelection()&&b(e,this._selectionService)}));let e=e=>x(e,this.textarea,this.coreService,this.optionsService);this._register(U(this.textarea,`paste`,e)),this._register(U(this.element,`paste`,e)),wi?this._register(U(this.element,`mousedown`,e=>{e.button===2&&w(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(U(this.element,`contextmenu`,e=>{w(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Mi&&this._register(U(this.element,`auxclick`,e=>{e.button===1&&C(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(U(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(U(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(U(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(U(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(U(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(U(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(U(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(U(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,h.get()),Ni||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(pi,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(B,this._coreBrowserService),this._register(U(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(U(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(li,this._document,this._helperContainer),this._instantiationService.setService(fe,this._charSizeService),this._themeService=this._instantiationService.createInstance(_a),this._instantiationService.setService(_e,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Wr),this._instantiationService.setService(ge,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(zi,this.rows,this.screenElement)),this._instantiationService.setService(me,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(Ar,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(vi),this._instantiationService.setService(pe,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(as,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(xr,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(sa,this.element,this.screenElement,r)),this._instantiationService.setService(he,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Ye.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(Sr,this.screenElement)),this._register(U(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(is,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Dr,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Dr,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ci,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(U(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(U(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=W.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){S(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=Jo(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===W.ETX||n.key===W.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(cs(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new A)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},ds=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new us(t)}getNullCell(){return new A}},fs=class extends V{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new H),this.onBufferChange=this._onBufferChange.event,this._normal=new ds(this._core.buffers.normal,`normal`),this._alternate=new ds(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},ps=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},ms=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},hs=[`cols`,`rows`],gs=0,_s=class extends V{constructor(e){super(),this._core=this._register(new ss(e)),this._addonManager=this._register(new ls),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(hs.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new ps(this._core),this._parser}get unicode(){return this._checkProposedApi(),new ms(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new fs(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return h.get()},set promptLabel(e){h.set(e)},get tooMuchOutput(){return _.get()},set tooMuchOutput(e){_.set(e)}}}_verifyIntegers(...e){for(gs of e)if(gs===1/0||isNaN(gs)||gs%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(gs of e)if(gs&&(gs===1/0||isNaN(gs)||gs%1!=0||gs<0))throw Error(`This API only accepts positive integers`)}},vs=2,ys=1,bs=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(vs,Math.floor(u/e.css.cell.width)),rows:Math.max(ys,Math.floor(l/e.css.cell.height))}}},xs=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Ss=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Cs;function ws(e,t){let n=0,r=t.length-1,i;if(et[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=lc.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return lc.createPropertyValue(0,n,r)}},Es=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?js.isErrorNoTelemetry(e)?new js(e.message+` + +`+e.stack):Error(e.message+` + +`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function Ds(e){ks(e)||Es.onUnexpectedError(e)}var Os=`Canceled`;function ks(e){return e instanceof As||e instanceof Error&&e.name===Os&&e.message===Os}var As=class extends Error{constructor(){super(Os),this.name=this.message}},js=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}};function Ms(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var Ns;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Ns||={});var Ps=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||Ns.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};Ps.empty=new Ps(e=>{});var Fs;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Vs(...e){return Hs(()=>Bs(e))}function Hs(e){let t=Ls({dispose:Ms(()=>{Rs(t),e()})});return t}var Us=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,Ls(this)}dispose(){this._isDisposed||(Rs(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Bs(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return zs(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),zs(e,null))}};Us.DISABLE_DISPOSED_WARNING=!1;var Ws=Us,Gs=class{constructor(){this._store=new Ws,Ls(this),zs(this._store,this)}dispose(){Rs(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};Gs.None=Object.freeze({dispose(){}});var Ks=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Ks.Undefined=new Ks(void 0);var qs=globalThis.performance&&typeof globalThis.performance.now==`function`,Js=class e{static create(t){return new e(t)}constructor(e){this._now=qs&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Ys;(e=>{e.None=()=>Gs.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(Vs(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new sc({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new sc({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new sc({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new sc({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new sc({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new sc;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new sc(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Ws?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(Ys||={});var Xs=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Js,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Xs.all=new Set,Xs._idPool=0;var Zs=Xs,Qs=-1,$s=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t0||this._options?.leakWarningThreshold?new ec(e?.onListenerError??Ds,this._options?.leakWarningThreshold??Qs):void 0,this._perfMon=this._options?._profName?new Zs(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new rc(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||Ds)(n),Gs.None}if(this._disposed)return Gs.None;t&&(e=e.bind(t));let r=new ac(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=tc.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof ac?(this._deliveryQueue??=new cc,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=Hs(()=>{i?.(),this._removeListener(r)});return n instanceof Ws?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*oc<=t.length){let e=0;for(let n=0;n0}},cc=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},lc=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new sc,this.onChange=this._onChange.event;let e=new Ts;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},uc=0,dc=-3,fc=class{constructor(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}},pc=class{constructor(e,t){this.tag=0,this.bitcount=0,this.destLen=0,this.sourceIndex=0,this.source=e,this.dest=t,this.ltree=new fc,this.dtree=new fc}},mc=new fc,hc=new fc,gc=new Uint8Array(30),_c=new Uint16Array(30),vc=new Uint8Array(30),yc=new Uint16Array(30),bc=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),xc=new fc,Sc=new Uint8Array(320);function Cc(e,t,n,r){for(var i=0,a;i>>=1,t}function Oc(e,t,n){if(!t)return n;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,r+n}function kc(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++i,n+=t.table[i],r-=t.table[i];while(r>=0);return e.tag=a,e.bitcount-=i,t.trans[n+r]}function Ac(e,t,n){for(var r=Oc(e,5,257),i=Oc(e,5,1),a=Oc(e,4,4),o=0,s,c;o<19;++o)Sc[o]=0;for(o=0;o8;)e.sourceIndex--,e.bitcount-=8;if(t=e.source[e.sourceIndex+1],t=256*t+e.source[e.sourceIndex],n=e.source[e.sourceIndex+3],n=256*n+e.source[e.sourceIndex+2],t!==(~n&65535))return dc;for(e.sourceIndex+=4,r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,uc}function Nc(e,t){var n=new pc(e,t),r,i,a;do{switch(r=Dc(n),i=Oc(n,2,0),i){case 0:a=Mc(n);break;case 1:a=jc(n,mc,hc);break;case 2:Ac(n,n.ltree,n.dtree),a=jc(n,n.ltree,n.dtree);break;default:a=dc}if(a!==uc)throw Error(`Data error`)}while(!r);return n.destLen>Fc,zc=(1<>Ic,Uc=Hc+(1024>>Ic)+32,Wc=1<1114111?this.errorValue:e<55296||e>56319&&e<=65535?(t=(this.data[e>>Ic]<>Ic)]<>Fc)],t=this.data[t+(e>>Ic&zc)],t=(t<>$c}function ml(e,t){let n=(e&Xc)>>Zc,r=(t&Xc)>>Zc;return hl(n,r)?r===rl?fl:r+16:r-16}function hl(e,t){return e>=al&&e<=ll&&(e==al&&(t==al||t==ol||t==cl||t==ll)||(e==cl||e==ol)&&(t==ol||t==sl)||(e==ll||e==sl)&&t==sl)||t==nl||t==ul||e==tl||t==il||e==ul&&t==dl||t==rl&&e==rl}function gl(e){return Yc.get(e)}var _l=class e{constructor(e=!0){this.ambiguousCharsAreWide=!1,this.version=e?`15-graphemes`:`15`,this.handleGraphemes=e}charProperties(t,n){if(t>=32&&t<127&&!(n>>3))return e._plainNarrowProperties;let r=gl(t),i=pl(r),a=!1;if(i=i>=2&&(i===3||this.ambiguousCharsAreWide||t===65039)?2:1,n!==0){let e=lc.extractWidth(n);r=this.handleGraphemes?ml(lc.extractCharKind(n),r):+(i===0),a=r>0,a&&(e>i?i=e:r===32&&(i=2))}return lc.createPropertyValue(r,i,a)}wcwidth(e){let t=gl(e),n=pl(t),r=(t&Xc)>>Zc;return r===nl||r===tl?0:n>=2&&(n===3||this.ambiguousCharsAreWide)?2:1}};_l._plainNarrowProperties=lc.createPropertyValue(el,1,!1);var vl=_l,yl=class{constructor(){this._oldVersion=``}activate(e){this._provider15||=new vl(!1),this._provider15Graphemes||=new vl(!0);let t=e.unicode;this._unicode=t,t.register(this._provider15),t.register(this._provider15Graphemes),this._oldVersion=t.activeVersion,t.activeVersion=`15-graphemes`}dispose(){this._unicode&&(this._unicode.activeVersion=this._oldVersion)}},bl=o((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){for(var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f=0;f>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;ac?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),xl=o((e=>{e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),Sl=o((e=>{var t=bl(),n=xl(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;var i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(_e(e,ArrayBuffer)||e&&_e(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(_e(e,SharedArrayBuffer)||e&&_e(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);let i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){let t=e.length<0?0:_(e.length)|0,n=o(t);for(let r=0;r=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(_e(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),_e(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);ir.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else if(s.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||_e(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return B(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return he(e).length;default:if(i)return r?-1:B(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return j(this,t,n);case`utf8`:case`utf-8`:return ee(this,t,n);case`ascii`:return A(this,t,n);case`latin1`:case`binary`:return re(this,t,n);case`base64`:return k(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return M(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;tn&&(t+=` ... `),``},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(_e(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,ve(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(i)n=0;else return-1}if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:C(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function C(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;lo&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;ri&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o=0;for(;o>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return w(this,e,t,n);case`utf8`:case`utf-8`:return T(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return E(this,e,t,n);case`base64`:return D(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return O(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function k(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function ee(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return ne(r)}var te=4096;function ne(e){let t=e.length;if(t<=te)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;rr)&&(n=r);let i=``;for(let r=t;rn&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),tn)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);let r=this[e],i=1,a=0;for(;++a>>=0,t>>>=0,n||N(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=t+this[++e]*256+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*256+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*256+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*256+n;return(BigInt(r)<>>=0,t>>>=0,n||N(e,t,this.length);let r=this[e],i=1,a=0;for(;++a=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=this[e+4]+this[e+5]*256+this[e+6]*2**16+(n<<24);return(BigInt(r)<>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*256+this[++e];return(BigInt(r)<>>=0,t||N(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!1,52,8)};function P(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||te.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;P(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a>>=0,n>>>=0,!r){let r=2**(8*n)-1;P(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function ie(e,t,n,r,i){ce(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function F(e,t,n,r,i){ce(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}s.prototype.writeBigUInt64LE=be(function(e,t=0){return ie(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=be(function(e,t=0){return F(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);P(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i>0)-o&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);P(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeBigInt64LE=be(function(e,t=0){return ie(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=be(function(e,t=0){return F(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function I(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function L(e,t,r,i,a){return t=+t,r>>>=0,a||I(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)};function R(e,t,r,i,a){return t=+t,r>>>=0,a||I(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i2**32?i=z(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=z(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function z(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function se(e,t,n){le(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&ue(t,e.length-(n+1))}function ce(e,t,n,r,i,a){if(e>n||e3?t===0||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${(a+1)*8}${r}`:`>= -(2${r} ** ${(a+1)*8-1}${r}) and < 2 ** ${(a+1)*8-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new ae.ERR_OUT_OF_RANGE(`value`,i,e)}se(r,i,a)}function le(e,t){if(typeof e!=`number`)throw new ae.ERR_INVALID_ARG_TYPE(t,`number`,e)}function ue(e,t,n){throw Math.floor(e)===e?t<0?new ae.ERR_BUFFER_OUT_OF_BOUNDS:new ae.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(le(e,n),new ae.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}var de=/[^+/0-9A-Za-z-_]/g;function fe(e){if(e=e.split(`=`)[0],e=e.trim().replace(de,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function B(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function pe(e){let t=[];for(let n=0;n>8,i=n%256,a.push(i),a.push(r);return a}function he(e){return t.toByteArray(fe(e))}function ge(e,t,n,r){let i=0;for(;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function _e(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function ve(e){return e!==e}var ye=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function be(e){return typeof BigInt>`u`?xe:e}function xe(){throw Error(`BigInt not supported`)}}))(),Cl=globalThis.performance,wl={env:{TERM:`xterm-256color`,TERM_PROGRAM:`xtermjs`},platform:`browser`,nextTick:e=>queueMicrotask(e)},Tl=new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?".split(``)),q={shift:1,alt:2,ctrl:4,super:8},El=192,J={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},Dl={up:-1,down:-2,right:-3,left:-4},Ol={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},kl=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,Dl.left],[57418,Dl.right],[57419,Dl.up],[57420,Dl.down],[57421,Ol.pageUp],[57422,Ol.pageDown],[57423,Ol.home],[57424,Ol.end],[57425,Ol.insert],[57426,Ol.delete]]);function Al(e){return kl.get(e)??e}function jl(e,t){return t&-193&q.shift&&e>=65&&e<=90?e+32:e}var Ml={up:[`\x1B[A`,`\x1BOA`],down:[`\x1B[B`,`\x1BOB`],right:[`\x1B[C`,`\x1BOC`],left:[`\x1B[D`,`\x1BOD`],home:[`\x1B[H`,`\x1BOH`,`\x1B[1~`,`\x1B[7~`],end:[`\x1B[F`,`\x1BOF`,`\x1B[4~`,`\x1B[8~`],insert:[`\x1B[2~`],delete:[`\x1B[3~`],pageUp:[`\x1B[5~`,`\x1B[[5~`],pageDown:[`\x1B[6~`,`\x1B[[6~`],clear:[`\x1B[E`,`\x1BOE`],f1:[`\x1BOP`,`\x1B[11~`,`\x1B[[A`],f2:[`\x1BOQ`,`\x1B[12~`,`\x1B[[B`],f3:[`\x1BOR`,`\x1B[13~`,`\x1B[[C`],f4:[`\x1BOS`,`\x1B[14~`,`\x1B[[D`],f5:[`\x1B[15~`,`\x1B[[E`],f6:[`\x1B[17~`],f7:[`\x1B[18~`],f8:[`\x1B[19~`],f9:[`\x1B[20~`],f10:[`\x1B[21~`],f11:[`\x1B[23~`],f12:[`\x1B[24~`]},Nl={up:[`\x1B[a`],down:[`\x1B[b`],right:[`\x1B[c`],left:[`\x1B[d`],clear:[`\x1B[e`],insert:[`\x1B[2$`],delete:[`\x1B[3$`],pageUp:[`\x1B[5$`],pageDown:[`\x1B[6$`],home:[`\x1B[7$`],end:[`\x1B[8$`]},Pl={up:[`\x1BOa`],down:[`\x1BOb`],right:[`\x1BOc`],left:[`\x1BOd`],clear:[`\x1BOe`],insert:[`\x1B[2^`],delete:[`\x1B[3^`],pageUp:[`\x1B[5^`],pageDown:[`\x1B[6^`],home:[`\x1B[7^`],end:[`\x1B[8^`]},Fl=(e,t)=>t.includes(e),Il=(e,t,n)=>n===q.shift?Fl(e,Nl[t]):n===q.ctrl&&Fl(e,Pl[t]);function Ll(e){return!e.includes(`\x1B[200~`)&&!!(e.includes(`:3u`)||e.includes(`:3~`)||e.includes(`:3A`)||e.includes(`:3B`)||e.includes(`:3C`)||e.includes(`:3D`)||e.includes(`:3H`)||e.includes(`:3F`))}function Rl(e){if(!e)return`press`;let t=parseInt(e,10);return t===2?`repeat`:t===3?`release`:`press`}function zl(e){let t=e.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(t){let e=parseInt(t[1],10),n=t[2]&&t[2].length>0?parseInt(t[2],10):void 0,r=t[3]?parseInt(t[3],10):void 0,i=t[4]?parseInt(t[4],10):1,a=Rl(t[5]);return{codepoint:e,shiftedKey:n,baseLayoutKey:r,modifier:i-1,eventType:a}}let n=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(n){let e=parseInt(n[1],10),t=Rl(n[2]);return{codepoint:{A:-1,B:-2,C:-3,D:-4}[n[3]],modifier:e-1,eventType:t}}let r=e.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(r){let e=parseInt(r[1],10),t=r[2]?parseInt(r[2],10):1,n=Rl(r[3]),i={2:Ol.insert,3:Ol.delete,5:Ol.pageUp,6:Ol.pageDown,7:Ol.home,8:Ol.end}[e];if(i!==void 0)return{codepoint:i,modifier:t-1,eventType:n}}let i=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(i){let e=parseInt(i[1],10),t=Rl(i[2]);return{codepoint:i[3]===`H`?Ol.home:Ol.end,modifier:e-1,eventType:t}}return null}function Y(e,t,n){let r=zl(e);if(!r||(r.modifier&-193)!=(n&-193))return!1;let i=jl(Al(r.codepoint),r.modifier);if(i===jl(Al(t),n))return!0;if(r.baseLayoutKey!==void 0&&r.baseLayoutKey===t){let e=i,t=e>=97&&e<=122,n=Tl.has(String.fromCharCode(e));if(!t&&!n)return!0}return!1}function Bl(e){let t=e.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!t)return null;let n=parseInt(t[1],10);return{codepoint:parseInt(t[2],10),modifier:n-1}}function Vl(e,t,n){let r=Bl(e);return r?r.codepoint===t&&r.modifier===n:!1}function Hl(){return!!wl.env.WT_SESSION&&!wl.env.SSH_CONNECTION&&!wl.env.SSH_CLIENT&&!wl.env.SSH_TTY}function Ul(e,t){return e===``?t===0:e===`\b`?Hl()?t===q.ctrl:t===0:!1}function Wl(e){let t=e.toLowerCase(),n=t.charCodeAt(0);return n>=97&&n<=122||t===`[`||t===`\\`||t===`]`||t===`_`?String.fromCharCode(n&31):t===`-`?``:null}function Gl(e){return e>=`0`&&e<=`9`}function Kl(e,t,n){if(n===0)return!1;let r=Bl(e);return!r||r.modifier!==n?!1:jl(r.codepoint,r.modifier)===jl(t,n)}function ql(e){let t=e.toLowerCase().split(`+`),n=t[t.length-1];return n?{key:n,ctrl:t.includes(`ctrl`),shift:t.includes(`shift`),alt:t.includes(`alt`),super:t.includes(`super`)}:null}function Jl(e,t){let n=ql(t);if(!n)return!1;let{key:r,ctrl:i,shift:a,alt:o,super:s}=n,c=0;switch(a&&(c|=q.shift),o&&(c|=q.alt),i&&(c|=q.ctrl),s&&(c|=q.super),r){case`escape`:case`esc`:return c===0?e===`\x1B`||Y(e,J.escape,0)||Vl(e,J.escape,0):!1;case`space`:return c===q.ctrl&&e===`\0`||c===q.alt&&e===`\x1B `?!0:c===0?e===` `||Y(e,J.space,0)||Vl(e,J.space,0):Y(e,J.space,c)||Vl(e,J.space,c);case`tab`:return c===q.shift?e===`\x1B[Z`||Y(e,J.tab,q.shift)||Vl(e,J.tab,q.shift):c===0?e===` `||Y(e,J.tab,0):Y(e,J.tab,c)||Vl(e,J.tab,c);case`enter`:case`return`:return c===q.shift?!!(Y(e,J.enter,q.shift)||Y(e,J.kpEnter,q.shift)||Vl(e,J.enter,q.shift)):c===q.alt?Y(e,J.enter,q.alt)||Y(e,J.kpEnter,q.alt)||Vl(e,J.enter,q.alt)?!0:e===`\x1B\r`:c===0?e===`\r`||e===` +`||e===`\x1BOM`||Y(e,J.enter,0)||Y(e,J.kpEnter,0):Y(e,J.enter,c)||Y(e,J.kpEnter,c)||Vl(e,J.enter,c);case`backspace`:return c===q.alt?e===`\x1B`||e===`\x1B\b`||Y(e,J.backspace,q.alt)||Vl(e,J.backspace,q.alt):c===q.ctrl?Ul(e,q.ctrl)?!0:Y(e,J.backspace,q.ctrl)||Vl(e,J.backspace,q.ctrl):c===0?Ul(e,0)||Y(e,J.backspace,0)||Vl(e,J.backspace,0):Y(e,J.backspace,c)||Vl(e,J.backspace,c);case`insert`:return c===0?Fl(e,Ml.insert)||Y(e,Ol.insert,0):Il(e,`insert`,c)?!0:Y(e,Ol.insert,c);case`delete`:return c===0?Fl(e,Ml.delete)||Y(e,Ol.delete,0):Il(e,`delete`,c)?!0:Y(e,Ol.delete,c);case`clear`:return c===0?Fl(e,Ml.clear):Il(e,`clear`,c);case`home`:return c===0?Fl(e,Ml.home)||Y(e,Ol.home,0):Il(e,`home`,c)?!0:Y(e,Ol.home,c);case`end`:return c===0?Fl(e,Ml.end)||Y(e,Ol.end,0):Il(e,`end`,c)?!0:Y(e,Ol.end,c);case`pageup`:return c===0?Fl(e,Ml.pageUp)||Y(e,Ol.pageUp,0):Il(e,`pageUp`,c)?!0:Y(e,Ol.pageUp,c);case`pagedown`:return c===0?Fl(e,Ml.pageDown)||Y(e,Ol.pageDown,0):Il(e,`pageDown`,c)?!0:Y(e,Ol.pageDown,c);case`up`:return c===q.alt?e===`\x1Bp`||Y(e,Dl.up,q.alt):c===0?Fl(e,Ml.up)||Y(e,Dl.up,0):Il(e,`up`,c)?!0:Y(e,Dl.up,c);case`down`:return c===q.alt?e===`\x1Bn`||Y(e,Dl.down,q.alt):c===0?Fl(e,Ml.down)||Y(e,Dl.down,0):Il(e,`down`,c)?!0:Y(e,Dl.down,c);case`left`:return c===q.alt?e===`\x1B[1;3D`||e===`\x1BB`||e===`\x1Bb`||Y(e,Dl.left,q.alt):c===q.ctrl?e===`\x1B[1;5D`||Il(e,`left`,q.ctrl)||Y(e,Dl.left,q.ctrl):c===0?Fl(e,Ml.left)||Y(e,Dl.left,0):Il(e,`left`,c)?!0:Y(e,Dl.left,c);case`right`:return c===q.alt?e===`\x1B[1;3C`||e===`\x1BF`||e===`\x1Bf`||Y(e,Dl.right,q.alt):c===q.ctrl?e===`\x1B[1;5C`||Il(e,`right`,q.ctrl)||Y(e,Dl.right,q.ctrl):c===0?Fl(e,Ml.right)||Y(e,Dl.right,0):Il(e,`right`,c)?!0:Y(e,Dl.right,c);case`f1`:case`f2`:case`f3`:case`f4`:case`f5`:case`f6`:case`f7`:case`f8`:case`f9`:case`f10`:case`f11`:case`f12`:return c===0&&Fl(e,Ml[r])}if(r.length===1&&(r>=`a`&&r<=`z`||Gl(r)||Tl.has(r))){let t=r.charCodeAt(0),n=Wl(r),i=r>=`a`&&r<=`z`,a=Gl(r);return c===q.ctrl+q.alt&&n&&e===`\x1b${n}`||c===q.alt&&(i||a||Tl.has(r))&&e===`\x1b${r}`?!0:c===q.ctrl?n&&e===n?!0:Y(e,t,q.ctrl)||Kl(e,t,q.ctrl):c===q.shift+q.ctrl?Y(e,t,q.shift+q.ctrl)||Kl(e,t,q.shift+q.ctrl):c===q.shift?i&&e===r.toUpperCase()?!0:Y(e,t,q.shift)||Kl(e,t,q.shift):c===0?e===r||Y(e,t,0):Y(e,t,c)||Kl(e,t,c)}return!1}var Yl=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,Xl=q.shift|El;function Zl(e){let t=e.match(Yl);if(!t)return;let n=Number.parseInt(t[1]??``,10);if(!Number.isFinite(n))return;let r=t[2]&&t[2].length>0?Number.parseInt(t[2],10):void 0,i=t[4]?Number.parseInt(t[4],10):1,a=Number.isFinite(i)?i-1:0;if((a&~Xl)!==0||a&(q.alt|q.ctrl))return;let o=n;if(a&q.shift&&typeof r==`number`&&(o=r),o=Al(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}function Ql(e){let t=Bl(e);if(t&&!(t.modifier&-193&~q.shift)&&!(!Number.isFinite(t.codepoint)||t.codepoint<32))try{return String.fromCodePoint(t.codepoint)}catch{return}}function $l(e){return Zl(e)??Ql(e)}var eu={"tui.editor.cursorUp":{defaultKeys:`up`,description:`Move cursor up`},"tui.editor.cursorDown":{defaultKeys:`down`,description:`Move cursor down`},"tui.editor.historyPrevious":{defaultKeys:[],description:`Select previous prompt history entry`},"tui.editor.historyNext":{defaultKeys:[],description:`Select next prompt history entry`},"tui.editor.cursorLeft":{defaultKeys:[`left`,`ctrl+b`],description:`Move cursor left`},"tui.editor.cursorRight":{defaultKeys:[`right`,`ctrl+f`],description:`Move cursor right`},"tui.editor.cursorWordLeft":{defaultKeys:[`alt+left`,`ctrl+left`,`alt+b`],description:`Move cursor word left`},"tui.editor.cursorWordRight":{defaultKeys:[`alt+right`,`ctrl+right`,`alt+f`],description:`Move cursor word right`},"tui.editor.cursorLineStart":{defaultKeys:[`home`,`ctrl+home`,`ctrl+a`],description:`Move to line start`},"tui.editor.cursorLineEnd":{defaultKeys:[`end`,`ctrl+end`,`ctrl+e`],description:`Move to line end`},"tui.editor.jumpForward":{defaultKeys:`ctrl+]`,description:`Jump forward to character`},"tui.editor.jumpBackward":{defaultKeys:`ctrl+alt+]`,description:`Jump backward to character`},"tui.editor.pageUp":{defaultKeys:[`pageUp`,`ctrl+pageUp`],description:`Page up`},"tui.editor.pageDown":{defaultKeys:[`pageDown`,`ctrl+pageDown`],description:`Page down`},"tui.editor.deleteCharBackward":{defaultKeys:`backspace`,description:`Delete character backward`},"tui.editor.deleteCharForward":{defaultKeys:[`delete`,`ctrl+d`],description:`Delete character forward`},"tui.editor.deleteWordBackward":{defaultKeys:[`ctrl+w`,`alt+backspace`],description:`Delete word backward`},"tui.editor.deleteWordForward":{defaultKeys:[`alt+d`,`alt+delete`],description:`Delete word forward`},"tui.editor.deleteToLineStart":{defaultKeys:`ctrl+u`,description:`Delete to line start`},"tui.editor.deleteToLineEnd":{defaultKeys:`ctrl+k`,description:`Delete to line end`},"tui.editor.yank":{defaultKeys:`ctrl+y`,description:`Yank`},"tui.editor.yankPop":{defaultKeys:`alt+y`,description:`Yank pop`},"tui.editor.undo":{defaultKeys:`ctrl+-`,description:`Undo`},"tui.input.newLine":{defaultKeys:[`shift+enter`,`ctrl+j`],description:`Insert newline`},"tui.input.submit":{defaultKeys:`enter`,description:`Submit input`},"tui.input.tab":{defaultKeys:`tab`,description:`Tab / autocomplete`},"tui.input.copy":{defaultKeys:`ctrl+c`,description:`Copy selection`},"tui.select.up":{defaultKeys:`up`,description:`Move selection up`},"tui.select.down":{defaultKeys:`down`,description:`Move selection down`},"tui.select.pageUp":{defaultKeys:`pageUp`,description:`Selection page up`},"tui.select.pageDown":{defaultKeys:`pageDown`,description:`Selection page down`},"tui.select.confirm":{defaultKeys:`enter`,description:`Confirm selection`},"tui.select.cancel":{defaultKeys:[`escape`,`ctrl+c`],description:`Cancel selection`},"tui.altScreen.pageUp":{defaultKeys:`pageUp`,description:`Scroll viewport up one page`},"tui.altScreen.pageDown":{defaultKeys:`pageDown`,description:`Scroll viewport down one page`},"tui.altScreen.halfPageUp":{defaultKeys:[],description:`Scroll viewport up half a page`},"tui.altScreen.halfPageDown":{defaultKeys:[],description:`Scroll viewport down half a page`},"tui.altScreen.lineUp":{defaultKeys:[],description:`Scroll viewport up one line`},"tui.altScreen.lineDown":{defaultKeys:[],description:`Scroll viewport down one line`},"tui.altScreen.previousPrompt":{defaultKeys:[`ctrl+shift+up`,`ctrl+up`],description:`Jump to previous semantic prompt`},"tui.altScreen.nextPrompt":{defaultKeys:[`ctrl+shift+down`,`ctrl+down`],description:`Jump to next semantic prompt`},"tui.altScreen.search":{defaultKeys:`ctrl+shift+f`,description:`Search the primary scroll view`},"tui.altScreen.searchNext":{defaultKeys:[`enter`,`ctrl+g`],description:`Select the next search match`},"tui.altScreen.searchPrevious":{defaultKeys:[`shift+enter`,`ctrl+shift+g`],description:`Select the previous search match`},"tui.altScreen.searchClose":{defaultKeys:`escape`,description:`Close transcript search`},"tui.altScreen.top":{defaultKeys:`home`,description:`Scroll viewport to top`},"tui.altScreen.bottom":{defaultKeys:`end`,description:`Scroll viewport to bottom`}};function tu(e){if(e===void 0)return[];let t=Array.isArray(e)?e:[e],n=new Set,r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}var nu=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(e,t={}){this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,n]of Object.entries(this.userBindings))if(t in this.definitions)for(let r of tu(n)){let n=e.get(r)??new Set;n.add(t),e.set(r,n)}for(let[t,n]of e)n.size>1&&this.conflicts.push({key:t,keybindings:[...n]});for(let[e,t]of Object.entries(this.definitions)){let n=this.userBindings[e],r=tu(n===void 0?t.defaultKeys:n);this.keysById.set(e,r)}}matches(e,t){let n=this.keysById.get(t)??[];for(let t of n)if(Jl(e,t))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let n=this.keysById.get(t)??[];e[t]=n.length===1?n[0]:[...n]}return e}},ru=null;function iu(e){ru=e}function au(){return ru||=new nu(eu),ru}var ou=class{ring=[];push(e,t){if(e){if(t.accumulate&&this.ring.length>0){let n=this.ring.pop();this.ring.push(t.prepend?e+n:n+e)}else this.ring.push(e)}}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};function su(e){let t=e.startsWith(`#`)?e.slice(1):e;return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}}function cu(e){if(!/^[0-9a-f]+$/i.test(e))return;let t=16**e.length-1;if(!(t<=0))return Math.round(parseInt(e,16)/t*255)}var lu=/^\x1b\]11;([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,uu=/^(?:\x1b\[\?997;(1|2)n)+$/;function du(e){return lu.test(e)}function fu(e){let t=e.match(lu);if(!t)return;let n=t[1].trim();if(n.startsWith(`#`)){let e=n.slice(1);if(/^[0-9a-f]{6}$/i.test(e))return su(n);if(/^[0-9a-f]{12}$/i.test(e)){let t=cu(e.slice(0,4)),n=cu(e.slice(4,8)),r=cu(e.slice(8,12));return t!==void 0&&n!==void 0&&r!==void 0?{r:t,g:n,b:r}:void 0}return}let[r,i,a]=n.replace(/^rgba?:/i,``).split(`/`);if(r===void 0||i===void 0||a===void 0)return;let o=cu(r),s=cu(i),c=cu(a);return o!==void 0&&s!==void 0&&c!==void 0?{r:o,g:s,b:c}:void 0}function pu(e){let t=e.match(uu);if(t)return t[1]===`2`?`light`:`dark`}var mu={images:null,trueColor:!0,hyperlinks:!0},hu=()=>mu,gu=e=>{mu={...e,images:null}},_u=()=>!1,vu=()=>void 0,yu=()=>void 0,bu=e=>e,xu=()=>``,Su=()=>``,Cu=()=>``;function wu(e,t){try{let n=new URL(t);return![`https:`,`http:`].includes(n.protocol)||/[\x00-\x20\x7f-\x9f]/.test(t)?e:`\x1b]8;;${n.href}\x07${e}\x1b]8;;\x07`}catch{return e}}var Tu=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Eu=[12288,12288,65281,65376,65504,65510],Du=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],Ou=(e,t)=>{let n=0,r=Math.floor(e.length/2)-1;for(;n<=r;){let i=Math.floor((n+r)/2),a=i*2;if(te[a+1])n=i+1;else return!0}return!1},ku=19968,[Au,ju]=Mu(Du);function Mu(e){let t=e[0],n=e[1];for(let r=0;r=i&&ku<=a)return[i,a];a-i>n-t&&(t=i,n=a)}return[t,n]}var Nu=e=>e<161||e>1114109?!1:Ou(Tu,e),Pu=e=>e<12288||e>65510?!1:Ou(Eu,e),Fu=e=>e>=Au&&e<=ju?!0:e<4352||e>262141?!1:Ou(Du,e);function Iu(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Lu(e,{ambiguousAsWide:t=!1}={}){return Iu(e),Pu(e)||Fu(e)||t&&Nu(e)?2:1}var Ru=new Intl.Segmenter(void 0,{granularity:`grapheme`}),zu=new Intl.Segmenter(void 0,{granularity:`word`});function Bu(){return Ru}function Vu(){return zu}function Hu(e){let t=e.codePointAt(0);return t>=126976&&t<=130047||t>=8960&&t<=9215||t>=9728&&t<=10175||t>=11088&&t<=11093||e.includes(`️`)||e.length>2}var Uu=RegExp(`^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$`,`v`),Wu=RegExp(`^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+`,`v`),Gu=RegExp(`^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$`,`v`),Ku=RegExp(`^\\p{Mark}$`,`v`),qu=RegExp(`^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$`,`v`),Ju=RegExp(`^\\p{RGI_Emoji}$`,`v`),Yu=512,Xu=new Map,Zu=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u;function Qu(e){for(let t=0;t126)return!1}return!0}function $u(e,t){if(t<=0||e.length===0)return{text:``,width:0};if(Qu(e)){let n=e.slice(0,t);return{text:n,width:n.length}}let n=e.includes(`\x1B`),r=e.includes(` `);if(!n&&!r){let n=``,r=0;for(let{segment:i}of Ru.segment(e)){let e=td(i);if(r+e>t)break;n+=i,r+=e}return{text:n,width:r}}let i=``,a=0,o=0,s=``;for(;ot)break;s&&=(i+=s,``),i+=` `,a+=3,o++;continue}let r=o;for(;rt)return{text:i,width:a};s&&=(i+=s,``),i+=n,a+=e}o=r}return{text:i,width:a}}function ed(e,t,n,r,i,a){let o=`\x1B[0m`,s=fd(e),c=t+r,l;return l=n.length>0?`${e}${s}${o}${n}${o}`:`${e}${s}${o}`,a?l+` `.repeat(Math.max(0,i-c)):l}function td(e){if(e===` `)return 3;if(qu.test(e))return[...e].length;if(Uu.test(e))return 0;if(Hu(e)&&Ju.test(e))return 2;let t=e.replace(Wu,``),n=t.codePointAt(0);if(n===void 0)return 0;if(n>=127462&&n<=127487)return 2;let r=Lu(n),i=!1,a=[...t];for(let e of a.slice(1))if(qu.test(e))r+=1,i=!1;else if(Ku.test(e))i=!0;else if(!Gu.test(e)){let t=e.codePointAt(0);i||t>=65280&&t<=65519?r+=Lu(t):(t===3635||t===3763)&&(r+=1),i=!1}return r}function X(e){if(e.length===0)return 0;if(Qu(e))return e.length;let t=Xu.get(e);if(t!==void 0)return t;let n=e;if(e.includes(` `)&&(n=n.replace(/\t/g,` `)),n.includes(`\x1B`)){let e=``,t=0;for(;t=Yu){let e=Xu.keys().next().value;e!==void 0&&Xu.delete(e)}return Xu.set(e,r),r}function nd(e){if(!e.includes(`\x1B`))return e;let t=``,n=0;for(;n0&&t>=n&&t=r&&te===`ำ`?`ํา`:`ໍາ`)),!t.includes(` `))return t;let n=``,r=0;for(;r=e.length||e[t]!==`\x1B`)return null;let n=e[t+1];if(n===`[`){let n=t+2;for(;n=30&&e<=37||e>=90&&e<=97?this.fgColor=String(e):(e>=40&&e<=47||e>=100&&e<=107)&&(this.bgColor=String(e))}a++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push(`1`),this.dim&&e.push(`2`),this.italic&&e.push(`3`),this.underline&&e.push(`4`),this.blink&&e.push(`5`),this.inverse&&e.push(`7`),this.hidden&&e.push(`8`),this.strikethrough&&e.push(`9`),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1b[${e.join(`;`)}m`:``;return this.activeHyperlink&&(t+=ud(this.activeHyperlink)),t}getActiveBackgroundCode(){return this.bgColor?`\x1b[${this.bgColor}m`:``}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let e=``;return this.underline&&(e+=`\x1B[24m`),this.activeHyperlink&&(e+=dd(this.activeHyperlink.terminator)),e}};function md(e,t){let n=0;for(;n{n&&(t.push(n),n=``,i=null)};for(;a0?t[t.length-1]+=r:n=r),n&&t.push(n),t}function _d(e,t){if(!e)return[``];let n=e.split(/\r\n|\r|\n/),r=[],i=new pd;for(let e of n){let n=vd((r.length>0?i.getActiveCodes():``)+e,t);for(let e of n)r.push(e);md(e,i)}return r.length>0?r:[``]}function vd(e,t){if(!e)return[``];if(X(e)<=t)return[e];let n=[],r=new pd,i=gd(e),a=``,o=0;for(let e of i){let i=X(e),s=e.trim()===``;if(i>t&&!s){if(a){let e=r.getLineEndReset();e&&(a+=e),n.push(a),a=``,o=0}let i=xd(e,t,r);for(let e=0;et&&o>0){let t=a.trimEnd(),c=r.getLineEndReset();c&&(t+=c),n.push(t),s?(a=r.getActiveCodes(),o=0):(a=r.getActiveCodes()+e,o=i)}else a+=e,o+=i;md(e,r)}return a&&n.push(a),n.length>0?n.map(e=>e.trimEnd()):[``]}var yd=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function bd(e){return/\s/.test(e)}function xd(e,t,n){let r=[],i=n.getActiveCodes(),a=0,o=0,s=[];for(;ot){let e=n.getLineEndReset();e&&(i+=e),r.push(i),i=n.getActiveCodes(),a=0}i+=o,a+=s}return i&&r.push(i),r.length>0?r:[``]}function Sd(e,t,n){let r=X(e),i=Math.max(0,t-r);return n(e+` `.repeat(i))}function Cd(e,t,n=`...`,r=!1){if(t<=0)return``;if(e.length===0)return r?` `.repeat(t):``;let i=X(n);if(i>=t){let i=X(e);if(i<=t)return r?e+` `.repeat(t-i):e;let a=$u(n,t);return a.width===0?r?` `.repeat(t):``:ed(``,0,a.text,a.width,t,r)}if(Qu(e)){if(e.length<=t)return r?e+` `.repeat(t-e.length):e;let a=t-i;return ed(e.slice(0,a),a,n,i,t,r)}let a=t-i,o=``,s=``,c=0,l=0,u=!0,d=!1,f=!1,p=e.includes(`\x1B`),m=e.includes(` `);if(!p&&!m){for(let{segment:n}of Ru.segment(e)){let e=td(n);if(u&&l+e<=a?(o+=n,l+=e):u=!1,c+=e,c>t){d=!0;break}}f=!d}else{let n=0;for(;nt){d=!0;break}n++;continue}let i=n;for(;it){d=!0;break}}if(d)break;n=i}f=n>=e.length}return!d&&f?r?e+` `.repeat(Math.max(0,t-c)):e:ed(o,l,n,i,t,r)}function wd(e,t,n,r=!1){return Td(e,t,n,r).text}function Td(e,t,n,r=!1){if(n<=0)return{text:``,width:0};let i=t+n,a=``,o=0,s=0,c=0,l=``;for(;c=t&&s=t&&s=i)break}if(c=u,s>=i)break}return{text:a,width:o}}var Ed=new pd;function Dd(e,t,n,r,i=!1){let a=``,o=0,s=``,c=0,l=0,u=0,d=``,f=!1,p=n+r;for(Ed.clear();u=n&&l=n&&l=t:l>=p)break}if(u=h,r<=0?l>=t:l>=p)break}return{before:a,beforeWidth:o,after:s,afterWidth:c}}function Od(e,t){let n=e.handleMouse?.(t);if(n){if(`target`in n)return n;if(n.handled||n.capture||n.focus)return{...n,handled:!0,...n.focus?{focusTarget:e}:{},target:{component:e,originX:t.screenX-t.x,originY:t.screenY-t.y,width:t.width,height:t.height}}}}function kd(e,t){return{...e,x:e.screenX-t.originX,y:e.screenY-t.originY,width:t.width,height:t.height}}function Ad(e){return e!==null&&`focused`in e}var jd=`\x1B_pi:c\x07`;function Md(e,t){if(e===void 0)return;if(typeof e==`number`)return e;let n=e.match(/^(\d+(?:\.\d+)?)%$/);if(n)return Math.floor(t*parseFloat(n[1])/100)}var Nd=class{children=[];mouseLayout;addChild(e){this.children.push(e)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&this.children.splice(t,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}handleMouse(e){if(e.y<0||e.y>=e.height)return;let t=this.mouseLayout?.width===e.width?this.mouseLayout.children:this.children.map(t=>({component:t,height:t.render(e.width).length})),n=0;for(let{component:r,height:i}of t){if(e.y>=n&&e.y0}overlayFocusRestore={status:`inactive`};constructor(e,t,n){super(),this.terminal=e,this.logDirectory=n,t!==void 0&&(this.showHardwareCursor=t)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(e){}afterTerminalStop(e){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(e){this.showHardwareCursor!==e&&(this.showHardwareCursor=e,e||this.terminal.hideCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(e){this.clearOnShrink=e}getFocusedComponent(){return this.focusedComponent}setFocus(e){this.setFocusInternal({component:e,overlayFocusRestore:`clear`})}setFocusInternal({component:e,overlayFocusRestore:t}){let n=this.focusedComponent,r=e,i=n?this.overlayStack.find(e=>e.component===n&&this.isOverlayVisible(e)):void 0,a=r?this.overlayStack.some(e=>e.component===r):!1,o=this.getVisibleOverlayFocusRestore();r&&!a?o.status===`blocked`&&o.blockedBy===n?o.resume.status===`focus-target`||!this.isComponentMounted(o.blockedBy)?r=this.resolveBlockedOverlayFocusResume(o):this.overlayFocusRestore={status:`blocked`,overlay:o.overlay,blockedBy:r,resume:o.resume}:i&&o.status!==`inactive`&&o.overlay===i&&!this.isOverlayFocusAncestor(i,r)&&(this.overlayFocusRestore={status:`blocked`,overlay:i,blockedBy:r,resume:{status:`restore-overlay`}}):r===null&&(o.status===`blocked`&&o.blockedBy===n?r=this.resolveBlockedOverlayFocusResume(o):t===`clear`&&this.clearOverlayFocusRestore()),Ad(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=r,Ad(r)&&(r.focused=!0);let s=r?this.overlayStack.find(e=>e.component===r&&this.isOverlayVisible(e)):void 0;s&&(this.overlayFocusRestore={status:`eligible`,overlay:s})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:`inactive`}}clearOverlayFocusRestoreFor(e){this.overlayFocusRestore.status!==`inactive`&&this.overlayFocusRestore.overlay===e&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(e){return e.resume.status===`restore-overlay`?e.overlay.component:(this.clearOverlayFocusRestore(),e.resume.target)}getVisibleOverlayFocusRestore(){let e=this.overlayFocusRestore;return e.status===`inactive`?e:!this.overlayStack.includes(e.overlay)||!this.isOverlayVisible(e.overlay)?{status:`inactive`}:e}isOverlayFocusAncestor(e,t){let n=new Set,r=e.preFocus;for(;r&&!n.has(r);){if(n.add(r),r===t)return!0;r=this.overlayStack.find(e=>e.component===r)?.preFocus??null}return!1}retargetOverlayPreFocus(e){for(let t of this.overlayStack)t!==e&&t.preFocus===e.component&&(t.preFocus=e.preFocus)}getMountedRoots(){return this.children}isComponentMounted(e){return this.getMountedRoots().some(t=>this.containsComponent(t,e))}containsComponent(e,t){return e===t||e instanceof Nd&&e.children.some(e=>this.containsComponent(e,t))}showOverlay(e,t){let n={component:e,...t===void 0?{}:{options:t},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(n),!t?.nonCapturing&&this.isOverlayVisible(n)&&this.setFocus(e),this.terminal.hideCursor(),this.requestRender(),{hide:()=>{let t=this.overlayStack.indexOf(n);if(t!==-1){if(this.clearOverlayFocusRestoreFor(n),this.retargetOverlayPreFocus(n),this.overlayStack.splice(t,1),this.focusedComponent===e){let e=this.getTopmostVisibleOverlay();this.setFocus(e?.component??n.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}},setHidden:r=>{if(n.hidden!==r){if(n.hidden=r,r){if(this.clearOverlayFocusRestoreFor(n),this.focusedComponent===e){let e=this.getTopmostVisibleOverlay();this.setFocus(e?.component??n.preFocus)}}else!t?.nonCapturing&&this.isOverlayVisible(n)&&(n.focusOrder=++this.focusOrderCounter,this.setFocus(e));this.requestRender()}},isHidden:()=>n.hidden,focus:()=>{this.overlayStack.includes(n)&&this.isOverlayVisible(n)&&(n.focusOrder=++this.focusOrderCounter,this.setFocus(e),this.requestRender())},unfocus:t=>{let r=this.focusedComponent===e,i=this.overlayFocusRestore,a=i.status!==`inactive`&&i.overlay===n;if(r||a){if(i.status===`blocked`&&i.overlay===n&&this.focusedComponent===i.blockedBy){t?this.overlayFocusRestore={status:`blocked`,overlay:n,blockedBy:i.blockedBy,resume:{status:`focus-target`,target:t.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(n),r||t){let e=this.getTopmostVisibleOverlay(),r=e&&e!==n?e.component:n.preFocus;this.setFocus(t?t.target:r)}this.requestRender()}},isFocused:()=>this.focusedComponent===e,getBounds:()=>{if(this.overlayStack.includes(n)&&this.isOverlayVisible(n)&&n.bounds)return{...n.bounds}}}}hideOverlay(){let e=this.overlayStack[this.overlayStack.length-1];if(e){if(this.clearOverlayFocusRestoreFor(e),this.retargetOverlayPreFocus(e),this.overlayStack.pop(),this.focusedComponent===e.component){let t=this.getTopmostVisibleOverlay();this.setFocus(t?.component??e.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}}hasOverlay(){return this.overlayStack.some(e=>this.isOverlayVisible(e))}isOverlayFocused(){return this.overlayStack.some(e=>e.component===this.focusedComponent&&this.isOverlayVisible(e))}resolveMouseFocusTarget(e){for(let t=this.overlayStack.length-1;t>=0;t--){let n=this.overlayStack[t];if(this.isOverlayVisible(n)&&this.containsComponent(n.component,e))return n.component}return e}dispatchMouseToOverlay(e){for(let t=this.renderedOverlayLayouts.length-1;t>=0;t--){let n=this.renderedOverlayLayouts[t];if(e.screenX=n.col+n.width||e.screenY=n.row+n.height)continue;let r=Od(n.entry.component,{...e,x:e.screenX-n.col,y:e.screenY-n.row,width:n.width,height:n.height});return r?{hit:!0,result:r.focus?{...r,focusTarget:n.entry.component}:r}:{hit:!0}}return{hit:!1}}isOverlayVisible(e){return e.hidden?!1:!e.options?.visible||e.options.visible(this.terminal.columns,this.terminal.rows)}getTopmostVisibleOverlay(){let e;for(let t of this.overlayStack)!t.options?.nonCapturing&&this.isOverlayVisible(t)&&(!e||t.focusOrder>e.focusOrder)&&(e=t);return e}invalidate(){for(let e of this.getMountedRoots())e.invalidate();for(let e of this.overlayStack)e.component.invalidate()}start(){this.stopped=!1,this.beforeTerminalStart(),this.terminal.start(e=>this.handleTerminalInput(e),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write(`\x1B[?2031h`),this.queryCellSize(),this.requestRender()}addInputListener(e){return this.inputListeners.add(e),()=>{this.inputListeners.delete(e)}}removeInputListener(e){this.inputListeners.delete(e)}onTerminalColorSchemeChange(e){return this.terminalColorSchemeListeners.add(e),()=>{this.terminalColorSchemeListeners.delete(e)}}setTerminalColorSchemeNotifications(e){this.terminalColorSchemeNotificationsEnabled!==e&&(this.terminalColorSchemeNotificationsEnabled=e,this.stopped||this.terminal.write(e?`\x1B[?2031h`:`\x1B[?2031l`))}queryCellSize(){hu().images&&this.terminal.write(`\x1B[16t`)}stop(e={}){this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write(`\x1B[?2031l`),this.beforeTerminalStop(e),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(e)}renderNow(e=!1){e&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=Cl.now(),this.doRender()}requestRender(e=!1){if(e){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,wl.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,wl.nextTick(()=>{this.immediateRenderScheduled=!1,!this.stopped&&this.renderRequested&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=Cl.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&=(clearTimeout(this.renderTimer),void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let t=Cl.now()-this.lastRenderAt,n=Math.max(0,e.MIN_RENDER_INTERVAL_MS-t);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!this.stopped&&this.renderRequested&&(this.renderRequested=!1,this.lastRenderAt=Cl.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},n)}handleTerminalInput(e){if(this.consumeOsc11BackgroundResponse(e)||this.consumeTerminalColorSchemeReport(e))return;if(this.inputListeners.size>0){let t=e;for(let e of this.inputListeners){let n=e(t);if(n?.consume)return;n?.data!==void 0&&(t=n.data)}if(t.length===0)return;e=t}if(this.consumeCellSizeResponse(e))return;if(Jl(e,`shift+ctrl+d`)&&this.onDebug){this.onDebug();return}let t=this.overlayStack.find(e=>e.component===this.focusedComponent);if(t&&!this.isOverlayVisible(t)){let e=this.getTopmostVisibleOverlay();e?this.setFocus(e.component):this.setFocusInternal({component:t.preFocus,overlayFocusRestore:`preserve`})}if(!this.overlayStack.some(e=>e.component===this.focusedComponent)){let e=this.getVisibleOverlayFocusRestore();e.status===`eligible`?this.setFocus(e.overlay.component):e.status===`blocked`&&e.blockedBy!==this.focusedComponent&&(e.resume.status===`restore-overlay`?this.setFocus(e.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(e.resume.target)))}if(this.focusedComponent?.handleInput){if(Ll(e)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(e),this.requestImmediateRender()}}consumeOsc11BackgroundResponse(e){if(this.pendingOsc11BackgroundReplies<=0||!du(e))return!1;let t=fu(e);--this.pendingOsc11BackgroundReplies;let n=this.pendingOsc11BackgroundQueries.shift();return n&&!n.settled&&(n.settled=!0,n.timer&&=(clearTimeout(n.timer),void 0),n.resolve?.(t),n.resolve=void 0),!0}consumeTerminalColorSchemeReport(e){let t=pu(e);if(!t)return!1;for(let e of this.terminalColorSchemeListeners)e(t);return!0}consumeCellSizeResponse(e){let t=e.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!t)return!1;let n=parseInt(t[1],10),r=parseInt(t[2],10);return n<=0||r<=0||(this.invalidate(),this.requestRender(),!0)}resolveOverlayLayout(e,t,n,r){let i=e??{},a=typeof i.margin==`number`?{top:i.margin,right:i.margin,bottom:i.margin,left:i.margin}:i.margin??{},o=Math.max(0,a.top??0),s=Math.max(0,a.right??0),c=Math.max(0,a.bottom??0),l=Math.max(0,a.left??0),u=Math.max(1,n-l-s),d=Math.max(1,r-o-c),f=Md(i.width,n)??Math.min(80,u);i.minWidth!==void 0&&(f=Math.max(f,i.minWidth)),f=Math.max(1,Math.min(f,u));let p=Md(i.maxHeight,r);p!==void 0&&(p=Math.max(1,Math.min(p,d)));let m=p===void 0?t:Math.min(t,p),h,g;if(i.row!==void 0){if(typeof i.row==`string`){let e=i.row.match(/^(\d+(?:\.\d+)?)%$/);if(e){let t=Math.max(0,d-m),n=parseFloat(e[1])/100;h=o+Math.floor(t*n)}else h=this.resolveAnchorRow(`center`,m,d,o)}else h=i.row}else{let e=i.anchor??`center`;h=this.resolveAnchorRow(e,m,d,o)}if(i.col!==void 0){if(typeof i.col==`string`){let e=i.col.match(/^(\d+(?:\.\d+)?)%$/);if(e){let t=Math.max(0,u-f),n=parseFloat(e[1])/100;g=l+Math.floor(t*n)}else g=this.resolveAnchorCol(`center`,f,u,l)}else g=i.col}else{let e=i.anchor??`center`;g=this.resolveAnchorCol(e,f,u,l)}return i.offsetY!==void 0&&(h+=i.offsetY),i.offsetX!==void 0&&(g+=i.offsetX),h=Math.max(o,Math.min(h,r-c-m)),g=Math.max(l,Math.min(g,n-s-f)),{width:f,row:h,col:g,maxHeight:p}}resolveAnchorRow(e,t,n,r){switch(e){case`top-left`:case`top-center`:case`top-right`:return r;case`bottom-left`:case`bottom-center`:case`bottom-right`:return r+n-t;case`left-center`:case`center`:case`right-center`:return r+Math.floor((n-t)/2)}}resolveAnchorCol(e,t,n,r){switch(e){case`top-left`:case`left-center`:case`bottom-left`:return r;case`top-right`:case`right-center`:case`bottom-right`:return r+n-t;case`top-center`:case`center`:case`bottom-center`:return r+Math.floor((n-t)/2)}}compositeOverlays(e,t,n){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],e;let r=[...e];for(let e of this.overlayStack)e.bounds=void 0;let i=[],a=r.length,o=this.overlayStack.filter(e=>this.isOverlayVisible(e));o.sort((e,t)=>e.focusOrder-t.focusOrder);for(let e of o){let{component:r,options:o}=e,{width:s,maxHeight:c}=this.resolveOverlayLayout(o,0,t,n),l=r.render(s);c!==void 0&&l.length>c&&(l=l.slice(0,c));let{row:u,col:d}=this.resolveOverlayLayout(o,l.length,t,n);e.bounds={row:u,col:d,width:s,height:l.length},i.push({entry:e,overlayLines:l,row:u,col:d,w:s}),a=Math.max(a,u+l.length)}this.renderedOverlayLayouts=i.map(({entry:e,row:t,col:n,w:r,overlayLines:i})=>({entry:e,row:t,col:n,width:r,height:i.length}));let s=Math.max(r.length,n,a);for(;r.length=0&&so?wd(e[i],0,o,!0):e[i];r[s]=this.compositeLineAt(r[s],n,a,o,t)}}return r}applyLineResets(e){let t=Pd;for(let n=0;n=n;t--){let n=e[t],r=n.indexOf(jd);if(r!==-1){let i=X(n.slice(0,r));return e[t]=n.slice(0,r)+n.slice(r+7),{row:t,col:i}}}return null}queryTerminalBackgroundColor({timeoutMs:e}){return new Promise(t=>{let n={settled:!1,resolve:t,timer:void 0};n.timer=setTimeout(()=>{n.settled||(n.settled=!0,n.timer=void 0,n.resolve?.(void 0),n.resolve=void 0)},e),this.pendingOsc11BackgroundQueries.push(n),this.pendingOsc11BackgroundReplies+=1,this.terminal.write(`\x1B]11;?\x07`)})}queryTerminalColorScheme({timeoutMs:e}){return new Promise(t=>{let n=!1,r,i=()=>{},a=e=>{n||(n=!0,r&&=(clearTimeout(r),void 0),i(),t(e))};i=this.onTerminalColorSchemeChange(a),r=setTimeout(()=>a(void 0),e),this.terminal.write(`\x1B[?996n`)})}},Rd=class{stack=[];push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}},zd=Vu();function Bd(e,t,n){if(t<=0)return 0;let r=e.slice(0,t),i=n?.segment,a=n?.isAtomicSegment,o=i?[...i(r)]:[...zd.segment(r)],s=t;for(;o.length>0&&!a?.(o[o.length-1]?.segment||``)&&bd(o[o.length-1]?.segment||``);)s-=o.pop()?.segment.length||0;if(o.length===0)return s;let c=o[o.length-1];if(a?.(c.segment))s-=c.segment.length;else if(c.isWordLike){let e=c.segment,t=[...e.matchAll(new RegExp(yd,`g`))];if(t.length<=0)s-=e.length;else{let n=t[t.length-1];s-=e.length-(n.index+n[0].length)}}else for(;o.length>0&&!a?.(o[o.length-1]?.segment||``)&&!o[o.length-1]?.isWordLike&&!bd(o[o.length-1]?.segment||``);)s-=o.pop()?.segment.length||0;return s}function Vd(e,t,n){if(t>=e.length)return e.length;let r=e.slice(t),i=n?.segment,a=n?.isAtomicSegment,o=(i?i(r):zd.segment(r))[Symbol.iterator](),s=o.next(),c=t;for(;!s.done&&!a?.(s.value.segment)&&bd(s.value.segment);)c+=s.value.segment.length,s=o.next();if(s.done)return c;if(a?.(s.value.segment))c+=s.value.segment.length;else if(s.value.isWordLike)c+=yd.exec(s.value.segment)?.index??s.value.segment.length;else for(;!s.done&&!a?.(s.value.segment)&&!s.value.isWordLike&&!bd(s.value.segment);)c+=s.value.segment.length,s=o.next();return c}var Hd=Bu(),Ud=class{value=``;cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer=``;isInPaste=!1;killRing=new ou;lastAction=null;undoStack=new Rd;constructor(e={}){this.prompt=e.prompt??`> `,this.placeholder=e.placeholder??``,this.placeholderStyle=e.placeholderStyle??(e=>e)}getValue(){return this.value}setValue(e){this.value=e,this.cursor=Math.min(this.cursor,e.length)}handleInput(e){if(e.includes(`\x1B[200~`)&&(this.isInPaste=!0,this.pasteBuffer=``,e=e.replace(`\x1B[200~`,``)),this.isInPaste){this.pasteBuffer+=e;let t=this.pasteBuffer.indexOf(`\x1B[201~`);if(t!==-1){let e=this.pasteBuffer.substring(0,t);this.handlePaste(e),this.isInPaste=!1;let n=this.pasteBuffer.substring(t+6);this.pasteBuffer=``,n&&this.handleInput(n)}return}let t=au();if(t.matches(e,`tui.select.cancel`)){this.onEscape&&this.onEscape();return}if(t.matches(e,`tui.editor.undo`)){this.undo();return}if(t.matches(e,`tui.input.submit`)||e===` +`){this.onSubmit&&this.onSubmit(this.value);return}if(t.matches(e,`tui.editor.deleteCharBackward`)){this.handleBackspace();return}if(t.matches(e,`tui.editor.deleteCharForward`)){this.handleForwardDelete();return}if(t.matches(e,`tui.editor.deleteWordBackward`)){this.deleteWordBackwards();return}if(t.matches(e,`tui.editor.deleteWordForward`)){this.deleteWordForward();return}if(t.matches(e,`tui.editor.deleteToLineStart`)){this.deleteToLineStart();return}if(t.matches(e,`tui.editor.deleteToLineEnd`)){this.deleteToLineEnd();return}if(t.matches(e,`tui.editor.yank`)){this.yank();return}if(t.matches(e,`tui.editor.yankPop`)){this.yankPop();return}if(t.matches(e,`tui.editor.cursorLeft`)){if(this.lastAction=null,this.cursor>0){let e=this.value.slice(0,this.cursor),t=[...Hd.segment(e)],n=t[t.length-1];this.cursor-=n?n.segment.length:1}return}if(t.matches(e,`tui.editor.cursorRight`)){if(this.lastAction=null,this.cursor{let t=e.charCodeAt(0);return t<32||t===127||t>=128&&t<=159})||this.insertCharacter(e)}handleMouse(e){if(e.type!==`press`||e.button!==`left`||e.y!==0)return;let t=Math.max(0,e.x-2),n=this.renderedStartColumn+t,r=0;this.cursor=this.value.length;for(let e of Hd.segment(this.value)){let t=r+X(e.segment);if(n0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...Hd.segment(e)],n=t[t.length-1],r=n?n.segment.length:1;this.value=this.value.slice(0,this.cursor-r)+this.value.slice(this.cursor),this.cursor-=r}}handleForwardDelete(){if(this.lastAction=null,this.cursor=this.value.length)return;this.pushUndo();let e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`,this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction===`kill`;this.pushUndo();let t=this.cursor;this.moveWordBackwards();let n=this.cursor;this.cursor=t;let r=this.value.slice(n,this.cursor);this.killRing.push(r,{prepend:!0,accumulate:e}),this.lastAction=`kill`,this.value=this.value.slice(0,n)+this.value.slice(this.cursor),this.cursor=n}deleteWordForward(){if(this.cursor>=this.value.length)return;let e=this.lastAction===`kill`;this.pushUndo();let t=this.cursor;this.moveWordForwards();let n=this.cursor;this.cursor=t;let r=this.value.slice(this.cursor,n);this.killRing.push(r,{prepend:!1,accumulate:e}),this.lastAction=`kill`,this.value=this.value.slice(0,this.cursor)+this.value.slice(n)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction=`yank`)}yankPop(){if(this.lastAction!==`yank`||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||``;this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||``;this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction=`yank`}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=Bd(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=Vd(this.value,this.cursor))}handlePaste(e){this.lastAction=null,this.pushUndo();let t=e.replace(/\r\n/g,``).replace(/\r/g,``).replace(/\n/g,``).replace(/\t/g,` `);this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}invalidate(){}render(e){let t=e-X(this.prompt);if(t<=0)return[Cd(this.prompt,e,``)];if(this.value.length===0&&this.placeholder){let e=Cd(this.placeholder,t,``),n=[...Hd.segment(e)][0]?.segment??` `,r=e.slice(n.length),i=(this.focused?jd:``)+`\x1b[7m${this.placeholderStyle(n)}\x1b[27m`+this.placeholderStyle(r),a=` `.repeat(Math.max(0,t-X(i)));return[this.prompt+i+a]}let n=``,r=this.cursor;this.renderedStartColumn=0;let i=X(this.value);if(i0){let t=Math.floor(e/2),o=0;o=ai-t?Math.max(0,i-e):Math.max(0,a-t),this.renderedStartColumn=o,n=wd(this.value,o,e,!0),r=wd(this.value,o,Math.max(0,a-o),!0).length}else n=``,r=0}let a=[...Hd.segment(n.slice(r))][0],o=n.slice(0,r),s=a?.segment??` `,c=n.slice(r+s.length),l=this.focused?jd:``,u=`\x1b[7m${s}\x1b[27m`,d=o+l+u+c,f=X(d),p=` `.repeat(Math.max(0,t-f));return[this.prompt+d+p]}},Wd=Bu(),Gd=/^[\x20-\x7e]*$/;function Kd(e){let t=[],n=[],r=0,i=!1,a=()=>{i&&=(t.push(` `),r+=1,!1)};for(let o=0;o0&&(i=!0),c+=1,e+=1;continue}let l=e+1;for(;l0&&(i=!0),c+=l;continue}a(),t.push(s),n.push({textStart:r,textEnd:r+s.length,row:o,startCol:c,endCol:c+l,linearColumns:!1}),r+=s.length,c+=l}r>0&&(i=!0)}return{text:t.join(``),spans:n}}function qd(e){return e.replace(/\s+/gu,` `).trim()}function Jd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Yd(e,t){if(!t)return[];let n=new RegExp(Jd(t),`giu`),r=[],i=0;for(let t of e.text.matchAll(n)){let n=t.index,a=n+t[0].length;for(;i=a)break;if(r.textEnd<=n)continue;let i=r.linearColumns?r.startCol+Math.max(n,r.textStart)-r.textStart:r.startCol,s=r.linearColumns?r.startCol+Math.min(a,r.textEnd)-r.textStart:r.endCol,c=o[o.length-1];c&&c.row===r.row&&i<=c.endCol?c.endCol=Math.max(c.endCol,s):o.push({row:r.row,startCol:i,endCol:s})}for(;i0&&r.push({segments:o})}return r}var Xd=class{sourceLines;corpus;normalizedQuery;matches=[];search(e,t){let n=this.sourceLines?.length!==e.length;if(!n&&this.sourceLines){for(let t=0;t`\x1b[2m${e}\x1b[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(e,t=e=>e){this.onQueryChange=e,this.navigationButtonStyle=t}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}setResult(e,t){this.resultIndex=e,this.resultCount=t}getNavigationDirectionAt(e,t){if(e===2){if(t>=this.previousButtonStart&&t=this.nextButtonStart&&te?e.split(`+`).map(e=>wl.platform===`darwin`&&e.toLowerCase()===`alt`?`Option`:e.charAt(0).toUpperCase()+e.slice(1)).join(`+`):`Unbound`,i=au(),a=r(i.getKeys(`tui.altScreen.searchPrevious`)[0]),o=r(i.getKeys(`tui.altScreen.searchNext`)[0]),s=Cd(this.input.getValue()?this.resultCount===0?`No matches`:`${this.resultIndex+1}/${this.resultCount}`:``,Math.max(0,n-3),``),c=s?`\x1b[2m ${s} \x1b[22m`:``,l=Math.max(0,n-X(c)),u=Cd(this.input.render(Math.max(1,l))[0]??``,l,``),d=`${u}${` `.repeat(Math.max(0,l-X(u)))}${c}`,f=`↑ ${a}`,p=`↓ ${o}`,m=` · `,h=Math.max(0,n-2-1),g=X(f)+X(m)+X(p);g>h&&(f=`↑`,p=`↓`,m=` `,g=X(f)+X(m)+X(p));let _=g<=h,v=_?this.navigationButtonStyle(f,this.hoveredNavigationDirection===-1)+m+this.navigationButtonStyle(p,this.hoveredNavigationDirection===1):``,y=_?2:0,b=v&&n>g+y?1:0,x=Math.max(0,n-(_?g:0)-y-b),S=1+x+1;return this.previousButtonStart=_?S:-1,this.previousButtonEnd=_?S+X(f):-1,this.nextButtonStart=_?this.previousButtonEnd+X(m):-1,this.nextButtonEnd=_?this.nextButtonStart+X(p):-1,t===1?[`┌`,`│`,`└`]:[`┌${`─`.repeat(n)}┐`,`│${d}│`,`└${`─`.repeat(x)}${v?` `:``}${v}${v?` `:``}${`─`.repeat(b)}┘`]}},$d=1e3,ef=class{entries=[];nextId=0;requestRender;constructor(e){this.requestRender=e}flash(e,t=$d){let n=this.nextId++,r=setTimeout(()=>{let e=this.entries.findIndex(e=>e.id===n);e!==-1&&(this.entries.splice(e,1),this.requestRender())},Math.max(0,t));r.unref?.(),this.entries.push({id:n,message:e,timer:r}),this.requestRender()}dispose(){for(let e of this.entries)clearTimeout(e.timer);this.entries.length=0}invalidate(){}render(e){return this.entries.map(t=>`\x1b[7m${Cd(` ${t.message} `,e,``)}\x1b[27m`)}},tf=Symbol.for(`@earendil-works/pi-tui/layout-node`);function nf(e){let t=e;return typeof t[tf]==`function`?t[tf]():void 0}var rf=class extends Nd{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(e,t={}){if(super(),t.axis!==void 0&&t.axis!==`vertical`)throw Error(`Unsupported ScrollView axis: ${t.axis}`);this.child=e,this.children.push(e),this.followEnd=(t.follow??`none`)===`end`,this.followingEnd=this.followEnd,this.primary=t.primary??!1,this.overscroll=t.overscroll??`chain`,this.currentScrollbar=t.scrollbar??`hidden`,this.scrollbarTrackStyle=t.scrollbarTrackStyle??(e=>`\x1b[90m${e}\x1b[39m`),this.scrollbarThumbStyle=t.scrollbarThumbStyle??(e=>`\x1b[37m${e}\x1b[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(t.scrollbarHideDelayMs??1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar===`always`?this.currentViewportHeight>0:this.scrollbar===`auto`&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(e){e!==this.currentScrollbar&&(this.currentScrollbar=e,e===`auto`?this.scrollbarActive&&this.markScrollbarActivity():this.hideTransientScrollbar(),this.requestRenderCallback?.())}getContentWidth(e){return this.scrollbar===`always`&&e>1?e-1:e}markScrollbarActivity(){this.scrollbar!==`auto`||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&=(clearTimeout(this.scrollbarHideTimer),void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref?.()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&=(clearTimeout(this.scrollbarHideTimer),void 0)}setScrollbarActive(e){e!==this.scrollbarActive&&(this.scrollbarActive=e,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(e,t={}){let n=Number.isFinite(e)?Math.trunc(e):this.currentScrollTop,r=Math.max(0,this.contentHeight-this.currentViewportHeight),i=Math.max(0,Math.min(r,n)),a=t.disableFollow===!0&&i===r,o=!a&&this.followEnd&&i===r;if(i===this.currentScrollTop&&o===this.followingEnd&&a===this.followSuppressedAtEnd)return;let s=i!==this.currentScrollTop;this.currentScrollTop=i,this.followingEnd=o,this.followSuppressedAtEnd=a,s&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(e){let t=Number.isFinite(e)?Math.trunc(e):0;if(t===0)return 0;let n=Math.max(0,this.contentHeight-this.currentViewportHeight),r=this.followingEnd?n:this.currentScrollTop,i=Math.max(0,Math.min(n,r+t)),a=i-r,o=this.followingEnd;return this.currentScrollTop=i,this.followingEnd=this.followEnd&&i===n,this.followSuppressedAtEnd=!1,a!==0&&this.markScrollbarActivity(),(a!==0||this.followingEnd!==o)&&this.requestRenderCallback?.(),t-a}scrollToStart(){let e=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=!1,e&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let e=Math.max(0,this.contentHeight-this.currentViewportHeight),t=this.currentScrollTop!==e||this.followingEnd!==this.followEnd;this.currentScrollTop=e,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,t&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(e,t,n){this.contentHeight=Math.max(0,Math.floor(e)),this.currentViewportHeight=Math.max(0,Math.floor(t)),this.requestRenderCallback=n;let r=Math.max(0,this.contentHeight-this.currentViewportHeight);this.currentScrollTop=this.followingEnd?r:Math.max(0,Math.min(this.currentScrollTop,r)),this.currentScrollTop`${e} `)}[tf](){return{type:`scroll`,component:this.child,state:this}}};function af(e){return!(`render`in e)}function of(e,t){return e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}var sf=class extends Nd{entries=[];gap;align;constructor(e=[],t={}){super(),this.gap=of(t.gap,0),this.align=t.align??`stretch`;for(let t of e)af(t)?this.addChild(t.component,t):this.addChild(t)}addChild(e,t={}){super.addChild(e),this.entries.push({component:e,...t.basis===void 0?{}:{basis:t.basis},...t.grow===void 0?{}:{grow:of(t.grow,0)},...t.shrink===void 0?{}:{shrink:of(t.shrink,1)},...t.minSize===void 0?{}:{minSize:of(t.minSize,0)},...t.maxSize===void 0?{}:{maxSize:of(t.maxSize,2**53-1)},...t.visible===void 0?{}:{visible:t.visible}})}removeChild(e){super.removeChild(e);let t=this.entries.findIndex(t=>t.component===e);t!==-1&&this.entries.splice(t,1)}clear(){super.clear(),this.entries.length=0}[tf](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function cf(e,t){return e.filter(e=>e.visible?.(t)??!0)}function lf(e,t){let n=Math.max(0,Math.floor(t.minSize??0)),r=Math.max(n,Math.floor(t.maxSize??2**53-1));return Math.max(n,Math.min(r,Math.max(0,Math.floor(e))))}function uf(e,t,n,r){let i=n;for(;i>0;){let n=t.map((e,t)=>({entry:e,index:t})).filter(({entry:t,index:n})=>r===`grow`?(t.grow??0)>0&&e[n]<(t.maxSize??2**53-1):(t.shrink??1)>0&&e[n]>(t.minSize??0));if(n.length===0)return;let a=n.reduce((t,{entry:n,index:i})=>t+(r===`grow`?n.grow??0:(n.shrink??1)*Math.max(1,e[i])),0),o=0;for(let{entry:t,index:s}of n){if(i<=0)break;let n=r===`grow`?t.grow??0:(t.shrink??1)*Math.max(1,e[s]),c=Math.max(1,Math.floor(i*n/a)),l=r===`grow`?(t.maxSize??2**53-1)-e[s]:e[s]-(t.minSize??0),u=Math.min(i,c,l);u<=0||(e[s]=e[s]+(r===`grow`?u:-u),i-=u,o+=u)}if(o===0)return}}function df(e,t,n,r){let i=e.map((e,n)=>lf(e.basis===void 0||e.basis===`auto`?t[n]??0:e.basis,e));if(n===void 0)return i;let a=Math.max(0,Math.floor(n)-Math.max(0,e.length-1)*r),o=i.reduce((e,t)=>e+t,0);return oa&&uf(i,e,o-a,`shrink`),i}var ff=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function pf(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return{x:n,y:r,width:Math.max(0,i-n),height:Math.max(0,a-r)}}function mf(e,t,n){let r=Math.max(1,Math.floor(n)),i=e.renderCache.get(t);i||(i=new Map,e.renderCache.set(t,i));let a=i.get(r);return a||(a=t.render(r),i.set(r,a)),a}function hf(e,t,n){return mf(e,t,n).length}function gf(e,t,n){return mf(e,t,n).reduce((e,t)=>Math.max(e,X(t)),0)}function _f(e,t){return e.parent=t,e}function vf(e,t){e.rect.y+=t;for(let n of e.children)vf(n,t)}function yf(e,t){e.clip=pf(t,e.rect);for(let t of e.children)yf(t,e.clip)}function bf(e,t,n,r,i,a,o){let s=Math.max(1,Math.floor(i)),c=nf(t);if(!c){let i=mf(e,t,s),c=a===void 0?i.length:Math.max(0,Math.floor(a)),l=0;if(i.length>c&&c>0){let e=i.findIndex(e=>e.includes(jd));e>=c&&(l=e-c+1)}return{component:t,rect:{x:n,y:r,width:s,height:c},clip:pf(o,{x:n,y:r,width:s,height:c}),children:[],lines:i,lineOffset:l,layer:0}}if(c.type===`scroll`){let i=c.state.scrollTop,l=c.state.getContentWidth(s),u=bf(e,c.component,n,r-i,l,void 0,o),d=u.rect.height,f=a===void 0?d:Math.max(0,Math.floor(a));c.state.updateLayout(d,f,e.requestRender),vf(u,i-c.state.scrollTop);let p=c.state;(c.state.primary||!e.primaryScrollView)&&(e.primaryScrollView=p);let m={x:n,y:r,width:s,height:f},h=pf(o,m),g={component:t,rect:m,clip:h,children:[u],scrollView:p,scrollContentLines:mf(e,c.component,l),layer:0};return u.parent=g,yf(u,h),g}let l=cf(c.entries,e.viewport),u=Math.max(0,l.length-1)*c.gap;if(c.type===`vstack`){let i=df(l,l.map(t=>typeof t.basis==`number`?t.basis:hf(e,t.component,s)),a,c.gap),d=i.reduce((e,t)=>e+t,0)+u,f={x:n,y:r,width:s,height:a===void 0?d:Math.max(0,Math.floor(a))},p={component:t,rect:f,clip:pf(o,f),children:[],layer:0},m=r;for(let t=0;ttypeof t.basis==`number`?t.basis:gf(e,t.component,s)),s,c.gap),f=l.map((t,n)=>hf(e,t.component,Math.max(1,d[n]))),p=a===void 0?f.reduce((e,t)=>Math.max(e,t),0):Math.max(0,a),m={x:n,y:r,width:s,height:p},h={component:t,rect:m,clip:pf(o,m),children:[],layer:0},g=n;for(let t=0;tr;if(!e.scrollView.isScrollbarVisible&&!i)return;let a=Math.max(Math.min(2,r),Math.min(r,Math.round(r*r/n))),o=Math.max(0,n-r),s=r-a,c=o===0?0:Math.round(e.scrollView.scrollTop/o*s),l=e.rect.x+e.rect.width-1;if(!(l=e.clip.x+e.clip.width))return{column:l,trackTop:e.rect.y,trackHeight:r,thumbTop:e.rect.y+c,thumbHeight:a,maxScrollTop:o}}function Cf(e,t,n){let r=Sf(e);if(r&&e.scrollView)for(let i=0;i=e.clip.y+e.clip.height||a<0||a>=t.length)continue;let o=a>=r.thumbTop&&a=n&&(_u(a)||!t[o])?t[o]=a:t[o]=Fd(t[o]??``,a,e.rect.x,e.rect.width,n)}}for(let r of e.children)wf(r,t,n);if(e.scrollView&&e.scrollContentLines&&e.scrollView.scrollTop>0&&e.rect.height>0)for(let r=e.scrollView.scrollTop-1;r>=0;r--){let i=e.scrollContentLines[r]??``,a=yu(i);if(a){let o=e.scrollView.scrollTop-r;if(o=n&&(t[e.rect.y]=r)}break}if(i!==``)break}Cf(e,t,n)}function Tf(e,t,n,r){let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.floor(n)),o={viewport:{width:i,height:a},renderCache:new Map,requestRender:r,primaryScrollView:void 0},s=bf(o,e,0,0,i,a,{x:0,y:0,width:i,height:a}),c=Array.from({length:a},()=>``);return wf(s,c,i),{root:s,width:i,height:a,lines:c,...o.primaryScrollView===void 0?{}:{primaryScrollView:o.primaryScrollView}}}function Ef(e,t,n){return t>=e.x&&t=e.y&&n{if(Ef(e.clip,t,n)){r.push({box:e,depth:a});for(let t of e.children)i(t,a+1)}};return i(e.root,0),r.sort((e,t)=>t.box.layer-e.box.layer||t.depth-e.depth),r.map(({box:e})=>e)}function Of(e,t){let n=e=>{if(e.scrollView===t)return e;for(let t of e.children){let e=n(t);if(e)return e}};return n(e.root)}function kf(e,t,n){let r=[],i=(e,a)=>{if(Ef(e.clip,t,n)){e.scrollView&&Ef(e.rect,t,n)&&r.push({scrollView:e.scrollView,depth:a});for(let t of e.children)i(t,a+1)}};return i(e.root,0),r.sort((e,t)=>t.depth-e.depth),r.map(e=>e.scrollView)}var Af=`\x1B[?1049h`,jf=`\x1B[?1049l`,Mf=`\x1B[?7l`,Nf=`\x1B[?7h`,Pf=`\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h`,Ff=`\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h`,If=`\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l`,Lf=`\x1B[I`,Rf=`\x1B[O`,zf=`\x1B[?2026h`,Bf=`\x1B[?2026l`,Vf=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,Hf=/^\x1b\]133;A(?:\x07|\x1b\\)/,Uf=4,Wf=5,Gf=16,Kf=33554432,qf=67108864,Jf=500,Yf=new Set([`/`,`-`]),Xf=Vu(),Zf=class extends Ld{mode=`fullscreen`;[Id]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity=`character`;selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScrollLines;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(e,t,n,r={}){super(e,t,n),this.implicitDocument={render:e=>super.render(e),handleMouse:e=>super.handleMouse(e),invalidate:()=>{for(let e of this.children)e.invalidate()}},this.implicitScrollView=new rf(this.implicitDocument,{follow:`end`,primary:!0}),this.flashes=new ef(()=>this.requestRender()),this.wheelScrollLines=Math.max(1,Math.floor(r.wheelScrollLines??1)),this.mouseEnabled=r.mouse??!0,this.searchMatchStyle=r.searchMatchStyle??(e=>`\x1b[4m${e}\x1b[24m`),this.searchCurrentMatchStyle=r.searchCurrentMatchStyle??(e=>`\x1b[1;7m${e}\x1b[22;27m`),this.searchNavigationButtonStyle=r.searchNavigationButtonStyle??(e=>e),this.scrollToEndIndicator=r.scrollToEndIndicator,this.openUrl=r.openUrl,this.onRightClickPaste=r.onRightClickPaste,this.copyOnSelect=r.copyOnSelect??!0,this.copySelection=r.copySelection,this.addInputListener(e=>this.handleViewportInput(e))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(e){this.copyOnSelect=e}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}setLayoutRoot(e){this.layoutRoot!==e&&(this.layoutRoot=e,this.currentLayout=void 0,this.requestRender())}render(e){return this.layoutRoot?.render(e)??super.render(e)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let e=hu();this.imageProtocol=e.images,this.uploadedKittyImages.clear(),e.images===`iterm2`&&(this.savedCapabilities=e,gu({...e,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity=`character`,this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let t=wl.env.TERM?.toLowerCase()??``,n=wl.env.TMUX!==void 0||wl.env.ZELLIJ!==void 0||wl.env.STY!==void 0||t.startsWith(`tmux`)||t.startsWith(`screen`)?Pf:Ff;this.terminal.write(`${Af}${Mf}${this.mouseEnabled?n:``}\x1b[2J\x1b[H\x1b[?25l`)}beforeTerminalStop(e){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${zf}${this.deleteKittyImages()}${this.mouseEnabled?If:``}${Nf}${Bf}`),this.uploadedKittyImages.clear())}afterTerminalStop(e){if(this.altScreenActive){if(this.altScreenActive=!1,e.preserveScreen)this.terminal.write(`${zf}${jf}\x1b[?25h${Bf}`);else{let e=Math.max(1,this.terminal.columns),t=this.render(e).map(e=>e.replace(Vf,``));this.lastDocument=this.applyLineResets(t.map(e=>e.replaceAll(jd,``))).map(t=>_u(t)||X(t)<=e?t:wd(t,0,e,!0));let n=`${zf}${jf}${Mf}`;for(let e=0;e0&&(n+=`\r +`),n+=`\r\x1b[2K${this.lastDocument[e]??``}`;n+=`\x1b[0m${Nf}\r\n\x1b[?25h${Bf}`,this.terminal.write(n)}this.savedCapabilities&&=(gu(this.savedCapabilities),void 0)}}deleteKittyImages(){return this.imageProtocol===`kitty`?Su():``}prepareKittyScreen(e){let t=new Set,n=e.map(e=>{let n=vu(e);if(!n)return e;t.add(n.imageId);let r=this.uploadedKittyImages.get(n.imageId),i={transmissionGeneration:n.transmissionGeneration,transmissionBytes:n.transmissionBytes,estimatedDecodedBytes:n.estimatedDecodedBytes};return r&&this.uploadedKittyImages.delete(n.imageId),this.uploadedKittyImages.set(n.imageId,i),r?.transmissionGeneration===n.transmissionGeneration?n.replacementLine:e}),r=0,i=0,a=0;for(let[e,n]of this.uploadedKittyImages)t.has(e)||(r+=1,i+=n.transmissionBytes,a+=n.estimatedDecodedBytes);let o=``;for(let[e,n]of this.uploadedKittyImages){if(r<=Gf&&i<=Kf&&a<=qf)break;t.has(e)||(o+=xu(e),this.uploadedKittyImages.delete(e),--r,i-=n.transmissionBytes,a-=n.estimatedDecodedBytes)}return{lines:n,evictedImageDeletion:o}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(e){this.getPrimaryScrollView().scrollBy(e),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(e){if(!this.currentLayout)return;let t=this.getPrimaryScrollView(),n=Of(this.currentLayout,t)?.scrollContentLines;if(n){for(let r=t.scrollTop+e;r>=0&&rthis.updateSearchQuery(e),this.searchNavigationButtonStyle),t={component:e,index:new Xd,query:``,matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:`query`};this.activeSearch=t,t.overlay=this.showOverlay(e,{anchor:`top-right`,width:`40%`,minWidth:32,margin:1})}closeSearch(){let e=this.activeSearch;e&&(this.activeSearch=void 0,e.overlay?.hide(),this.requestRender())}updateSearchQuery(e){let t=this.activeSearch;t&&e!==t.query&&(t.anchorRow=t.matches[t.selectedIndex]?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,t.query=e,t.selectionMode=`query`,t.component.setResult(-1,0),this.requestRender())}navigateSearch(e){let t=this.activeSearch;t?.query&&(t.selectionMode=e<0?`previous`:`next`,this.requestRender())}getSearchNavigationDirectionAt(e,t){let n=this.activeSearch,r=n?.overlay?.getBounds();if(n&&r&&!(e=r.col+r.width||t=r.row+r.height))return n.component.getNavigationDirectionAt(t-r.row,e-r.col)}handleSearchMouseEvent(e){let t=this.activeSearch;if(!t)return!1;let n=this.getSearchNavigationDirectionAt(e.x,e.y);return t.component.setHoveredNavigationDirection(n)&&this.requestRender(),n===void 0||e.release||e.button&32||e.button&3?!1:(this.navigateSearch(n),!0)}refreshSearch(e){let t=this.activeSearch;if(!t)return!1;let n=e.primaryScrollView??this.implicitScrollView,r=Of(e,n),i=r?.scrollContentLines;if(!i||!t.query.trim())return t.matches=[],t.selectedIndex=-1,t.selectedKey=void 0,t.selectionMode=`retain`,t.component.setResult(-1,0),!1;let a=t.selectionMode!==`retain`,o=t.index.search(i,t.query),s=o.matches;if(t.matches=s,!o.changed&&t.selectionMode===`retain`)return!1;let c=o.changed?t.selectedKey?s.findIndex(e=>Zd(e)===t.selectedKey):-1:t.selectedIndex,l=-1;if(s.length>0){if(t.selectionMode===`query`){let e=0,n=s.length;for(;e=0?c:Math.min(t.selectedIndex,s.length-1);l=e<0?0:(e+1)%s.length}else if(t.selectionMode===`previous`){let e=c>=0?c:Math.min(t.selectedIndex,s.length-1);l=e<0?s.length-1:(e-1+s.length)%s.length}else l=c>=0?c:Math.min(Math.max(0,t.selectedIndex),s.length-1)}if(t.selectedIndex=l,t.selectedKey=l>=0?Zd(s[l]):void 0,t.selectionMode=`retain`,t.component.setResult(l,s.length),!a)return!1;let u=s[l],d=u?.segments[0],f=u?.segments[u.segments.length-1];if(!r||!d||!f||n.viewportHeight<=0)return!1;let p=n.scrollTop,m=p+n.viewportHeight-1,h=p;return(d.rowm)&&(h=d.row-Math.floor(n.viewportHeight/3)),n.scrollTo(h,{disableFollow:!0}),n.scrollTop!==p}flash(e,t){this.flashes.flash(e,t)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(e){if(e===Rf){let e=this.selectionPressActive,t=e&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,e&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity=`character`,this.selectionInitialRange=void 0,t&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(e===Lf)return{consume:!0};let t=this.parseWheelEvent(e);if(t){let e=this.createMouseEvent(`wheel`,t.button,t.x,t.y,{wheelDelta:t.direction*this.getWheelScrollLines(t.button)}),n=this.dispatchMouseToOverlay(e),r=n.result??(n.hit?void 0:this.dispatchMouseToLayout(e));return r?(this.applyMouseDispatchResult(e,r)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(t),{consume:!0})}let n=this.parseSgrMouseEvent(e);if(n)return this.handleMouseEvent(n),{consume:!0};if(this.isMouseSequence(e))return{consume:!0};let r=au(),i=Ll(e);if(r.matches(e,`tui.altScreen.search`))return i||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(r.matches(e,`tui.altScreen.searchNext`))return i||this.navigateSearch(1),{consume:!0};if(r.matches(e,`tui.altScreen.searchPrevious`))return i||this.navigateSearch(-1),{consume:!0};if(r.matches(e,`tui.altScreen.searchClose`))return i||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(r.matches(e,`tui.altScreen.pageUp`))return i||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-Uf)),{consume:!0};if(r.matches(e,`tui.altScreen.pageDown`))return i||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-Uf)),{consume:!0};if(r.matches(e,`tui.altScreen.halfPageUp`))return i||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(r.matches(e,`tui.altScreen.halfPageDown`))return i||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(r.matches(e,`tui.altScreen.lineUp`))return i||this.scrollBy(-1),{consume:!0};if(r.matches(e,`tui.altScreen.lineDown`))return i||this.scrollBy(1),{consume:!0};if(r.matches(e,`tui.altScreen.previousPrompt`))return i||this.scrollToPrompt(-1),{consume:!0};if(r.matches(e,`tui.altScreen.nextPrompt`))return i||this.scrollToPrompt(1),{consume:!0};if(r.matches(e,`tui.altScreen.top`))return i||this.scrollToTop(),{consume:!0};if(r.matches(e,`tui.altScreen.bottom`))return i||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(e){switch(e&3){case 0:return`left`;case 1:return`middle`;case 2:return`right`;default:return`none`}}createMouseEvent(e,t,n,r,i={}){return{type:e,button:e===`wheel`?`none`:this.decodeMouseButton(t),x:n,y:r,screenX:n,screenY:r,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:!!(t&4),alt:!!(t&8),ctrl:!!(t&16),...i.wheelDelta===void 0?{}:{wheelDelta:i.wheelDelta},...i.clickCount===void 0?{}:{clickCount:i.clickCount}}}dispatchMouseToLayout(e){if(!this.currentLayout)return;let t=new Set,n=Df(this.currentLayout,e.screenX,e.screenY);for(let r of n){if(t.has(r.component)||nf(r.component)&&r.component.handleMouse===Nd.prototype.handleMouse)continue;t.add(r.component);let n=Od(r.component,{...e,x:e.screenX-r.rect.x,y:e.screenY-r.rect.y,width:r.rect.width,height:r.rect.height});if(n)return n}}applyMouseDispatchResult(e,t){let n=this.resolveMouseFocusTarget(t.focusTarget??t.target.component),r=t.focus===!0&&this.getFocusedComponent()!==n;return t.focus&&this.setFocus(n),t.capture&&(this.mouseCapture=t.target),t.render??(r||e.type===`press`||e.type===`click`||e.type===`drag`||e.type===`wheel`)}dispatchMouseToTarget(e,t){return Od(t.component,kd(e,t))}getComponentClickCount(e,t,n){let r=Date.now(),i=this.lastComponentClick,a=i&&r-i.timestamp<=Jf&&i.component===e.component&&i.x===t&&i.y===n?i.count%3+1:1;return this.lastComponentClick={timestamp:r,count:a,component:e.component,x:t,y:n},a}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity=`character`,this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(e){let t=!!(e.button&32),n=e.release?`release`:t?this.decodeMouseButton(e.button)===`none`?`move`:`drag`:`press`,r=this.createMouseEvent(n,e.button,e.x,e.y);if(this.mouseCapture||this.mousePressTarget){let t=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(e.x!==this.mousePressPoint.x||e.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let n=!1,i=this.dispatchMouseToTarget(r,t);if(i&&(n=this.applyMouseDispatchResult(r,i)),e.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===e.x&&this.mousePressPoint.y===e.y){let r=this.createMouseEvent(`click`,e.button,e.x,e.y,{clickCount:this.getComponentClickCount(t,e.x,e.y)}),i=this.dispatchMouseToTarget(r,t);i&&(n=this.applyMouseDispatchResult(r,i)||n)}this.clearComponentMouseGesture()}n&&this.requestRender();return}if(this.handleSearchMouseEvent(e))return;let i=this.dispatchMouseToOverlay(r);if(i.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(e))return;let t=this.handleScrollbarMouseEvent(e);if(this.scrollbarDrag||this.updateScrollbarHover(e.x,e.y),t)return}let a=i.result??(i.hit?void 0:this.dispatchMouseToLayout(r));if(a){let t=this.applyMouseDispatchResult(r,a);n===`press`&&(this.clearTextSelection(),this.mousePressTarget=a.target,this.mousePressPoint={x:e.x,y:e.y},this.mousePressMoved=!1),t&&this.requestRender();return}this.handleRightClickPaste(e)||this.handleSelectionMouseEvent(e)}parseWheelEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(e);if(t){let e=Number.parseInt(t[1],10);if(!(e&64))return;let n=e&3;return n!==0&&n!==1?void 0:{direction:n===0?-1:1,x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,button:e}}if(e.length===6&&e.startsWith(`\x1B[M`)){let t=e.charCodeAt(3)-32;if(!(t&64))return;let n=t&3;return n!==0&&n!==1?void 0:{direction:n===0?-1:1,x:e.charCodeAt(4)-33,y:e.charCodeAt(5)-33,button:t}}}getWheelScrollLines(e){return e&8?this.wheelScrollLines*Wf:this.wheelScrollLines}routeWheel(e){let t=e.direction*this.getWheelScrollLines(e.button),n=new Set;for(let r of this.currentLayout?kf(this.currentLayout,e.x,e.y):[])if(n.add(r),t=r.scrollBy(t),t===0||r.overscroll===`contain`)break;let r=this.getPrimaryScrollView();t!==0&&!n.has(r)&&r.scrollBy(t),this.updateScrollbarHover(e.x,e.y),this.requestRender()}parseSgrMouseEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(t)return{button:Number.parseInt(t[1],10),x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,release:t[4]===`m`}}handleRightClickPaste(e){if(!this.onRightClickPaste||wl.platform!==`win32`||wl.env.TERM_PROGRAM?.toLowerCase()===`vscode`||e.release||e.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(e){let t=this.scrollToEndIndicatorRect;return!t||e.release||e.button&32||e.button&3||e.y!==t.row||e.x=t.column+t.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(e,t,n=!1){if(!this.hasOverlay()&&this.currentLayout)for(let r of kf(this.currentLayout,e,t)){let i=Of(this.currentLayout,r),a=i?Sf(i,n):void 0;if(a&&e===a.column&&t>=a.trackTop&&t=t.geometry.thumbTop&&e.ye.col>=t.start&&e.cole.selectable&&t.selectable&&(e.joiner||t.joiner),o=n[i].start,s=n[i].end;for(let e=i;e>0&&a(n[e-1],n[e]);e--)o=n[e-1].start;for(let e=i;e=i),this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref?.())}autoScrollSelection(){let e=this.selectionAnchor?.scrollView,t=this.selectionDragPointer,n=this.selectionAutoScrollDirection;if(!e||!t||n===0){this.stopSelectionAutoScroll();return}if(e.scrollBy(n)===n){this.stopSelectionAutoScroll();return}let r=this.getScrollSelectionPoint(e,t.x,t.y);r&&this.updateSelectionFocus(r),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&=(clearInterval(this.selectionAutoScrollTimer),void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(e){let t=e.button&3;if(t!==0&&!(e.release&&t===3))return;let n=this.selectionAnchor?.scrollView,r=this.getSelectionPoint(e,n);if(e.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(r);let t=!this.selectionDragged&&this.selectionAnchor.scrollView===r.scrollView&&this.selectionAnchor.row===r.row&&this.selectionAnchor.col===r.col,n=t?this.pressedUrl:void 0;if(this.pressedUrl=void 0,n&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(n)}catch{}this.requestRender();return}if(t){let t=this.createMouseEvent(`click`,e.button,e.x,e.y,{clickCount:this.lastClick?.count??1}),n=this.dispatchMouseToOverlay(t),r=n.result??(n.hit?void 0:this.dispatchMouseToLayout(t));if(r){let e=this.applyMouseDispatchResult(t,r);this.clearTextSelection(),e&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if(e.button&32){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(r),this.updateSelectionAutoScroll(e),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let i=!this.hasOverlay()&&this.currentLayout?kf(this.currentLayout,e.x,e.y)[0]:void 0,a=this.getSelectionPoint(e,i),o=this.getWordSelection(a),s=this.getClickCount(a,o),c=s===2?o:s===3?this.getLineSelection(a):void 0;this.selectionGranularity=c?s===2?`word`:`line`:`character`,this.selectionInitialRange=c,this.selectionAnchor=c?.start??a,this.selectionFocus=c?.end??a,this.selectionDragged=!1,this.pressedUrl=c?void 0:id(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,e.y))]??``,Math.max(0,Math.min(this.terminal.columns-1,e.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let e=this.selectionAnchor.rowi&&(r+=n(e.slice(i,a))),r+=t.code,a+=t.length,i=a}return if)break;for(let o of t.segments){let t=i.rect.y+o.row-r.scrollTop;if(t=c)continue;let d=Math.max(l,i.rect.x+o.startCol),f=Math.min(u,i.rect.x+o.endCol);if(f<=d)continue;let p=a.get(t)??[];p.push({startCol:d,endCol:f,current:e===n.selectedIndex}),a.set(t,p)}}let h=[...e];for(let[e,t]of a){let n=h[e]??``;if(_u(n))continue;let r=X(n);for(let e of t.sort((e,t)=>t.startCol-e.startCol)){let t=Math.min(e.startCol,r),i=Math.min(e.endCol,r);if(i<=t)continue;let a=wd(n,0,t,!0),o=wd(n,t,i-t,!0),s=wd(n,i,Math.max(0,r-i),!0);n=`${a}${this.applySearchTextHighlight(o,e.current)}${s}`}h[e]=n}return h}applySelectionHighlight(e){let t=`\x1B[7m`,n=0;for(;n{if(ta||tr.end.row||_u(e))return e;let n=X(e),c=this.getSelectionColumns(e,t,r,o,s);if(c.end<=c.start)return e;let l=wd(e,0,c.start,!0),u=wd(e,c.start,c.end-c.start,!0),d=wd(e,c.end,Math.max(0,n-c.end),!0);return`${l}${this.applySelectionHighlight(u)}${d}`})}isMouseSequence(e){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(e)||e.length===6&&e.startsWith(`\x1B[M`)}compositeScrollToEndIndicator(e,t,n){this.scrollToEndIndicatorRect=void 0;let r=t.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!r.followEnd||r.isFollowingEnd)return e;let i=Of(t,r),a=i?.clip;if(!a||a.width<=0||a.height<=0)return e;let o=a.y+a.height-1;if(o>=e.length||_u(e[o]??``))return e;let s=i?Sf(i)?.column:void 0,c=Math.max(0,(s??a.x+a.width)-a.x),l=Cd(this.scrollToEndIndicator(),c,``),u=X(l);if(u===0)return e;let d=a.x+Math.floor((c-u)/2),f=[...e];return f[o]=Fd(f[o]??``,l,d,u,n),this.scrollToEndIndicatorRect={row:o,column:d,width:u},f}compositeFlashes(e,t,n){let r=this.flashes.render(t).slice(-n);if(r.length===0)return e;let i=[...e];for(;i.lengththis.requestRender());this.refreshSearch(r)&&(r=Tf(n,e,t,()=>this.requestRender()));let i=r.lines.map(e=>e.replace(Vf,``));i=this.applySearchHighlights(i,r),i=this.compositeScrollToEndIndicator(i,r,e),i=this.compositeOverlays(i,e,t),i.length>t&&(i=i.slice(i.length-t)),i=this.applySelection(i,r),i=this.compositeFlashes(i,e,t);let a=this.extractCursorPosition(i,t);i=this.applyLineResets(i).map(t=>_u(t)||X(t)<=e?t:wd(t,0,e,!0));let o=this.previousScreen.length===0||this.previousScreenWidth!==e||this.previousScreenHeight!==t,s=i.some((e,t)=>e!==this.previousScreen[t]&&(_u(e)||_u(this.previousScreen[t]??``))),c=o||s,l=this.uploadedKittyImages.size>0,u=c&&this.imageProtocol===`kitty`?this.prepareKittyScreen(i):{lines:i,evictedImageDeletion:``},d=zf;if(o){this.fullRedrawCount+=1;let e=this.imageProtocol===`kitty`&&l?Cu():this.deleteKittyImages();d+=`${e}\x1b[2J`}else s&&(this.imageProtocol===`iterm2`?d+=`\x1B[2J`:this.imageProtocol===`kitty`&&(d+=Cu()));d+=u.evictedImageDeletion;for(let e=0;ee.replace(/[\r\n]+/g,` `).trim(),np=(e,t,n)=>Math.max(t,Math.min(e,n)),rp=class{items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(e,t,n,r={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.layout=r}setFilter(e){this.filteredItems=this.items.filter(t=>t.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let t=[];if(this.filteredItems.length===0)return t.push(this.theme.noMatch(` No matching commands`)),t;let n=this.getPrimaryColumnWidth(),{startIndex:r,endIndex:i}=this.getVisibleRange();for(let a=r;a0||i=n)){if(e.type===`press`)return this.mousePressedIndex=r,this.selectedIndex!==r&&(this.selectedIndex=r,this.notifySelectionChange()),{handled:!0,focus:!0};if(e.type===`click`){let e=this.mousePressedIndex??r;this.mousePressedIndex=void 0;let t=this.selectedIndex!==e;this.selectedIndex=e,t&&this.notifySelectionChange();let n=this.filteredItems[this.selectedIndex];return n&&this.onSelect?.(n),{handled:!0}}}}handleInput(e){let t=au();if(t.matches(e,`tui.select.up`))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(t.matches(e,`tui.select.down`))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(t.matches(e,`tui.select.confirm`)){let e=this.filteredItems[this.selectedIndex];e&&this.onSelect&&this.onSelect(e)}else t.matches(e,`tui.select.cancel`)&&this.onCancel&&this.onCancel()}getVisibleRange(){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex:e,endIndex:Math.min(e+this.maxVisible,this.filteredItems.length)}}renderItem(e,t,n,r,i){let a=t?`→ `:` `,o=X(a);if(r&&n>40){let s=Math.max(1,Math.min(i,n-o-4)),c=Math.max(1,s-$f),l=this.truncatePrimary(e,t,c,s),u=X(l),d=` `.repeat(Math.max(1,s-u)),f=n-(o+u+d.length)-2;if(f>ep){let e=Cd(r,f,``);if(t)return this.theme.selectedText(`${a}${l}${d}${e}`);let n=this.theme.description(d+e);return a+l+n}}let s=n-o-2,c=this.truncatePrimary(e,t,s,s);return t?this.theme.selectedText(`${a}${c}`):a+c}getPrimaryColumnWidth(){let{min:e,max:t}=this.getPrimaryColumnBounds();return np(this.filteredItems.reduce((e,t)=>Math.max(e,X(this.getDisplayValue(t))+$f),0),e,t)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??Qf,t=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??Qf;return{min:Math.max(1,Math.min(e,t)),max:Math.max(1,Math.max(e,t))}}truncatePrimary(e,t,n,r){let i=this.getDisplayValue(e);return Cd(this.layout.truncatePrimary?this.layout.truncatePrimary({text:i,maxWidth:n,columnWidth:r,item:e,isSelected:t}):Cd(i,n,``),n,``)}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}},ip=Bu(),ap=Vu(),op=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,sp=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function cp(e){return e.length>=10&&sp.test(e)}function lp(e,t,n){if(n.size===0||!e.includes(`[paste #`))return t.segment(e);let r=[];for(let t of e.matchAll(op)){let e=Number.parseInt(t[1],10);n.has(e)&&r.push({start:t.index,end:t.index+t[0].length})}if(r.length===0)return t.segment(e);let i=t.segment(e),a=[],o=0;for(let t of i){for(;o=n.start&&t.indext&&(s>=0&&a-c+d<=t?(r.push({text:e.slice(o,s),startIndex:o,endIndex:s}),o=s,a-=c):ot){let e=up(u,t);for(let t=0;te!==`@`).map(mp);return RegExp(`(?:^|[ \\t])(?:@(?:"[^"]*|[^\\s]*)|[${t.join(``)}][^\\s]*)$`)}function _p(e,t,n){let r=Math.max(0,n),i=` ${e} ${t} more `,a=X(i);if(a+2<=r){let e=Math.floor((r-a)/2);return`─`.repeat(e)+i+`─`.repeat(r-e-a)}let o=`─── ${e} ${t} more `,s=r-X(o);if(s>=0)return o+`─`.repeat(s);let c=`...`.slice(0,r);return wd(o,0,r-X(c),!0)+c}var vp=class{state={lines:[``],cursorLine:0,cursorCol:0};focused=!1;tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...pp];autocompleteTriggerPattern=hp(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=gp(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix=``;autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer=``;isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new ou;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new Rd;onSubmit;onChange;disableSubmit=!1;constructor(e,t,n={}){this.tui=e,this.theme=t,this.borderColor=t.borderColor;let r=n.paddingX??0;this.paddingX=Number.isFinite(r)?Math.max(0,Math.floor(r)):0;let i=n.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(i)?Math.max(3,Math.min(20,Math.floor(i))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(e,t){return lp(e,t===`word`?ap:ip,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==t&&(this.paddingX=t,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let t=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==t&&(this.autocompleteMaxVisible=t,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e,this.setAutocompleteTriggerCharacters(e.triggerCharacters??[])}addToHistory(e){let t=e.trim();t&&(this.history.length>0&&this.history[0]===t||(this.history.unshift(t),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===``}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let t=this.historyIndex-e;if(!(t<-1||t>=this.history.length)){if(this.historyIndex===-1&&t>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=t,this.historyIndex===-1){let e=this.historyDraft;this.historyDraft=null,e?(this.state=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal(``)}else this.setTextInternal(this.history[this.historyIndex]||``,e===-1?`start`:`end`)}}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(e,t=`end`){let n=e.split(` +`);this.state.lines=n.length===0?[``]:n,this.state.cursorLine=t===`start`?0:this.state.lines.length-1,this.setCursorCol(t===`start`?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(e,t){let n=t>0?_p(`↑`,t,e):`─`.repeat(e);return this.borderColor(n)}renderBottomBorder(e,t){let n=t>0?_p(`↓`,t,e):`─`.repeat(e);return this.borderColor(n)}render(e){let t=Math.max(0,Math.floor((e-1)/2)),n=Math.min(this.paddingX,t),r=Math.max(1,e-n*2),i=Math.max(1,r-+!n);this.lastWidth=i;let a=this.layoutText(i),o=this.tui.terminal.rows,s=Math.max(5,Math.floor(o*.3)),c=a.findIndex(e=>e.hasCursor);c===-1&&(c=0),c=this.scrollOffset+s&&(this.scrollOffset=c-s+1);let l=Math.max(0,a.length-s);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,l));let u=a.slice(this.scrollOffset,this.scrollOffset+s);this.renderedVisibleLineCount=u.length;let d=[],f=` `.repeat(n),p=f;d.push(this.renderTopBorder(e,this.scrollOffset));let m=this.focused;for(let e of u){let t=e.text,i=X(e.text),a=!1;if(e.hasCursor&&e.cursorPos!==void 0){let o=t.slice(0,e.cursorPos),s=t.slice(e.cursorPos),c=m?jd:``;if(s.length>0){let e=[...this.segment(s,`grapheme`)][0]?.segment||``,n=s.slice(e.length),r=`\x1b[7m${e}\x1b[0m`;t=o+c+r+n}else t=o+c+`\x1B[7m \x1B[0m`,i+=1,i>r&&n>0&&(a=!0)}let o=` `.repeat(Math.max(0,r-i)),s=a?p.slice(1):p;d.push(`${f}${t}${o}${s}`)}let h=a.length-(this.scrollOffset+u.length);if(d.push(this.renderBottomBorder(e,h)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let e=this.autocompleteList.render(r);this.renderedAutocompleteHeight=e.length;for(let t of e){let e=X(t),n=` `.repeat(Math.max(0,r-e));d.push(`${f}${t}${n}${p}`)}}return d}handleMouse(e){let t=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&e.y>=t&&e.ythis.renderedVisibleLineCount)return{handled:!0,focus:!0};let n=this.buildVisualLineMap(this.lastWidth),r=this.scrollOffset+e.y-1,i=n[r];if(!i)return{handled:!0,focus:!0};let a=this.state.lines[i.logicalLine]??``,o=i.startCol+i.length,s=a.slice(i.startCol,o),c=Math.max(0,Math.floor((e.width-1)/2)),l=Math.min(this.paddingX,c),u=Math.max(0,e.x-l),d=0,f=s.length,p=0;for(let e of this.segment(s,`grapheme`)){let t=d+X(e.segment);if(p=e.index,u0&&(f=p),this.state.cursorLine=i.logicalLine,this.setCursorCol(i.startCol+f),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(e){let t=au();if(this.jumpMode!==null){if(t.matches(e,`tui.editor.jumpForward`)||t.matches(e,`tui.editor.jumpBackward`)){this.jumpMode=null;return}let n=$l(e)??(e.charCodeAt(0)>=32?e:void 0);if(n!==void 0){let e=this.jumpMode;this.jumpMode=null,this.jumpToChar(n,e);return}this.jumpMode=null}if(e.includes(`\x1B[200~`)&&(this.isInPaste=!0,this.pasteBuffer=``,e=e.replace(`\x1B[200~`,``)),this.isInPaste){this.pasteBuffer+=e;let t=this.pasteBuffer.indexOf(`\x1B[201~`);if(t!==-1){let e=this.pasteBuffer.substring(0,t);e.length>0&&this.handlePaste(e),this.isInPaste=!1;let n=this.pasteBuffer.substring(t+6);this.pasteBuffer=``,n.length>0&&this.handleInput(n);return}return}if(t.matches(e,`tui.input.copy`))return;if(t.matches(e,`tui.editor.undo`)){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(t.matches(e,`tui.select.cancel`)){this.cancelAutocomplete();return}if(t.matches(e,`tui.select.up`)||t.matches(e,`tui.select.down`)){this.autocompleteList.handleInput(e);return}if(t.matches(e,`tui.input.tab`)){let e=this.autocompleteList.getSelectedItem();if(e&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(t.matches(e,`tui.select.confirm`)){let e=this.autocompleteList.getSelectedItem();if(e&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);if(this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.autocompletePrefix.startsWith(`/`))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(t.matches(e,`tui.input.tab`)&&!this.autocompleteState){this.handleTabCompletion();return}if(t.matches(e,`tui.editor.deleteToLineEnd`)){this.deleteToEndOfLine();return}if(t.matches(e,`tui.editor.deleteToLineStart`)){this.deleteToStartOfLine();return}if(t.matches(e,`tui.editor.deleteWordBackward`)){this.deleteWordBackwards();return}if(t.matches(e,`tui.editor.deleteWordForward`)){this.deleteWordForward();return}if(t.matches(e,`tui.editor.deleteCharBackward`)||Jl(e,`shift+backspace`)){this.handleBackspace();return}if(t.matches(e,`tui.editor.deleteCharForward`)||Jl(e,`shift+delete`)){this.handleForwardDelete();return}if(t.matches(e,`tui.editor.yank`)){this.yank();return}if(t.matches(e,`tui.editor.yankPop`)){this.yankPop();return}if(t.matches(e,`tui.editor.historyPrevious`)){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(t.matches(e,`tui.editor.historyNext`)){this.cancelAutocomplete(),this.navigateHistory(1);return}if(t.matches(e,`tui.editor.cursorLineStart`)){this.moveToLineStart();return}if(t.matches(e,`tui.editor.cursorLineEnd`)){this.moveToLineEnd();return}if(t.matches(e,`tui.editor.cursorWordLeft`)){this.moveWordBackwards();return}if(t.matches(e,`tui.editor.cursorWordRight`)){this.moveWordForwards();return}if(t.matches(e,`tui.input.newLine`)||e.charCodeAt(0)===10&&e.length>1||e===`\x1B\r`||e===`\x1B[13;2~`||e.length>1&&e.includes(`\x1B`)&&e.includes(`\r`)||e===` +`&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,t)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(t.matches(e,`tui.input.submit`)){if(this.disableSubmit)return;let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol>0&&e[this.state.cursorCol-1]===`\\`){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(t.matches(e,`tui.editor.cursorUp`)){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(t.matches(e,`tui.editor.cursorDown`)){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(t.matches(e,`tui.editor.cursorRight`)){this.moveCursor(0,1);return}if(t.matches(e,`tui.editor.cursorLeft`)){this.moveCursor(0,-1);return}if(t.matches(e,`tui.editor.pageUp`)){this.pageScroll(-1);return}if(t.matches(e,`tui.editor.pageDown`)){this.pageScroll(1);return}if(t.matches(e,`tui.editor.jumpForward`)){this.jumpMode=`forward`;return}if(t.matches(e,`tui.editor.jumpBackward`)){this.jumpMode=`backward`;return}if(Jl(e,`shift+space`)){this.insertCharacter(` `);return}let n=$l(e);if(n!==void 0){this.insertCharacter(n);return}e.charCodeAt(0)>=32&&this.insertCharacter(e)}layoutText(e){let t=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]===``)return t.push({text:``,hasCursor:!0,cursorPos:0}),t;for(let n=0;n=r.startIndex,c=a-r.startIndex):(s=a>=r.startIndex&&ar.text.length&&(c=r.text.length)))),s?t.push({text:r.text,hasCursor:!0,cursorPos:c}):t.push({text:r.text,hasCursor:!1})}}}return t}getText(){return this.state.lines.join(` +`)}expandPasteMarkers(e){let t=e;for(let[e,n]of this.pastes){let r=RegExp(`\\[paste #${e}( (\\+\\d+ lines|\\d+ chars))?\\]`,`g`);t=t.replace(r,()=>n)}return t}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(` +`))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(e){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let t=this.normalizeText(e);this.getText()!==t&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(t)}insertTextAtCursor(e){e&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(e))}normalizeText(e){return e.replace(/\r\n/g,` +`).replace(/\r/g,` +`).replace(/\t/g,` `)}insertTextAtCursorInternal(e){if(!e)return;let t=this.normalizeText(e),n=t.split(` +`),r=this.state.lines[this.state.cursorLine]||``,i=r.slice(0,this.state.cursorCol),a=r.slice(this.state.cursorCol);n.length===1?(this.state.lines[this.state.cursorLine]=i+t+a,this.setCursorCol(this.state.cursorCol+t.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),i+n[0],...n.slice(1,-1),n[n.length-1]+a,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=n.length-1,this.setCursorCol((n[n.length-1]||``).length)),this.onChange&&this.onChange(this.getText())}insertCharacter(e,t){this.exitHistoryBrowsing(),t||((bd(e)||this.lastAction!==`type-word`)&&this.pushUndoSnapshot(),this.lastAction=`type-word`);let n=this.state.lines[this.state.cursorLine]||``,r=n.slice(0,this.state.cursorCol),i=n.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=r+e+i,this.setCursorCol(this.state.cursorCol+e.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(e===`/`&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(e)){let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol),t=e[e.length-2];(e.length===1||t===` `||t===` `)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(e)){let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);(this.isInSlashCommandContext(e)||this.autocompleteTriggerPattern.test(e))&&this.tryTriggerAutocomplete()}}handlePaste(e){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let t=e.replace(/\x1b\[(\d+);5u/g,(e,t)=>{let n=Number(t);return n>=97&&n<=122?String.fromCharCode(n-96):n>=65&&n<=90?String.fromCharCode(n-64):e}),n=this.normalizeText(t).split(``).filter(e=>e===` +`||e.charCodeAt(0)>=32).join(``);if(/^[/~.]/.test(n)){let e=this.state.lines[this.state.cursorLine]||``,t=this.state.cursorCol>0?e[this.state.cursorCol-1]:``;t&&/\w/.test(t)&&(n=` ${n}`)}let r=n.split(` +`),i=n.length;if(r.length>10||i>1e3){this.pasteCounter++;let e=this.pasteCounter;this.pastes.set(e,n);let t=r.length>10?`[paste #${e} +${r.length} lines]`:`[paste #${e} ${i} chars]`;this.insertTextAtCursorInternal(t);return}if(r.length===1){this.insertTextAtCursorInternal(n);return}this.insertTextAtCursorInternal(n)}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=e.slice(0,this.state.cursorCol),n=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=t,this.state.lines.splice(this.state.cursorLine+1,0,n),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,t){if(this.disableSubmit||!Jl(e,`enter`))return!1;let n=t.getKeys(`tui.input.submit`);if(!(n.includes(`shift+enter`)||n.includes(`shift+return`)))return!1;let r=this.state.lines[this.state.cursorLine]||``;return this.state.cursorCol>0&&r[this.state.cursorCol-1]===`\\`}submitValue(){this.cancelAutocomplete();let e=this.expandPasteMarkers(this.state.lines.join(` +`)).trim();this.state={lines:[``],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(``),this.onSubmit&&this.onSubmit(e)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=e.slice(0,this.state.cursorCol),n=[...this.segment(t,`grapheme`)],r=n[n.length-1],i=r?r.segment.length:1,a=sp.exec(r.segment);if(a){let e=Number(a[1]);this.pastes.delete(e),this.pasteCounter--;let t=[...this.pastes.keys()].filter(t=>t>e).sort((e,t)=>e-t);for(let e of t)this.pastes.set(e-1,this.pastes.get(e)),this.pastes.delete(e);this.state.lines=this.state.lines.map(t=>t.replace(op,(t,n,r)=>{let i=Number(n);return i<=e?t:`[paste #${i-1}${r}]`}))}e=this.state.lines[this.state.cursorLine]||``;let o=e.slice(0,this.state.cursorCol-i),s=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=o+s,this.setCursorCol(this.state.cursorCol-i)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);(this.isInSlashCommandContext(e)||this.autocompleteTriggerPattern.test(e))&&this.tryTriggerAutocomplete()}}setCursorCol(e){this.state.cursorCol=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(e,t,n){let r=e[t],i=e[n];if(!(r&&i))return;let a;if(this.snappedFromCursorCol!==null){let t=this.findVisualLineAt(e,r.logicalLine,this.snappedFromCursorCol);a=this.snappedFromCursorCol-e[t].startCol}else a=this.state.cursorCol-r.startCol;let o=t===e.length-1||e[t+1]?.logicalLine!==r.logicalLine?r.length:Math.max(0,r.length-1),s=n===e.length-1||e[n+1]?.logicalLine!==i.logicalLine?i.length:Math.max(0,i.length-1),c=this.computeVerticalMoveColumn(a,o,s);this.state.cursorLine=i.logicalLine;let l=i.startCol+c,u=this.state.lines[i.logicalLine]||``;this.state.cursorCol=Math.min(l,u.length);let d=[...this.segment(u,`grapheme`)];for(let r of d){if(r.index>this.state.cursorCol)break;if(!(r.segment.length<=1)&&this.state.cursorColt){let a=r.index+r.segment.length,o=n+1;for(;o0){this.pushUndoSnapshot();let t=e.slice(0,this.state.cursorCol);this.killRing.push(t,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`,this.state.lines[this.state.cursorLine]=e.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(` +`,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`;let t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol0){this.pushUndoSnapshot(),this.killRing.push(` +`,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`;let t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}}else{this.pushUndoSnapshot();let t=this.lastAction===`kill`,n=this.state.cursorCol;this.moveWordBackwards();let r=this.state.cursorCol;this.setCursorCol(n);let i=e.slice(r,this.state.cursorCol);this.killRing.push(i,{prepend:!0,accumulate:t}),this.lastAction=`kill`,this.state.lines[this.state.cursorLine]=e.slice(0,r)+e.slice(this.state.cursorCol),this.setCursorCol(r)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol>=e.length){if(this.state.cursorLine=0&&(a=0&&t0){if(this.state.cursorCol0){let t=e.slice(0,this.state.cursorCol),n=[...this.segment(t,`grapheme`)],r=n[n.length-1];this.setCursorCol(this.state.cursorCol-(r?r.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let e=this.state.lines[this.state.cursorLine]||``;this.setCursorCol(e.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(e){this.lastAction=null;let t=this.tui.terminal.rows,n=Math.max(5,Math.floor(t*.3)),r=this.buildVisualLineMap(this.lastWidth),i=this.findCurrentVisualLine(r),a=Math.max(0,Math.min(r.length-1,i+e*n));this.moveToVisualLine(r,i,a)}moveWordBackwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let e=this.state.lines[this.state.cursorLine]||``;this.setCursorCol(e.length)}return}this.setCursorCol(Bd(e,this.state.cursorCol,{segment:e=>this.segment(e,`word`),isAtomicSegment:cp}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction=`yank`}yankPop(){if(this.lastAction!==`yank`||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction=`yank`}insertYankedText(e){this.exitHistoryBrowsing();let t=e.split(` +`);if(t.length===1){let t=this.state.lines[this.state.cursorLine]||``,n=t.slice(0,this.state.cursorCol),r=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+e+r,this.setCursorCol(this.state.cursorCol+e.length)}else{let e=this.state.lines[this.state.cursorLine]||``,n=e.slice(0,this.state.cursorCol),r=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+(t[0]||``);for(let e=1;e=e.length){this.state.cursorLinethis.segment(e,`word`),isAtomicSegment:cp}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);return e.trim()===``||e.trim()===`/`}isInSlashCommandContext(e){return this.isSlashMenuAllowed()&&e.trimStart().startsWith(`/`)}getBestAutocompleteMatchIndex(e,t){if(!t)return-1;let n=-1;for(let r=0;r{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},r}tryTriggerAutocomplete(e=!1){this.requestAutocomplete({force:!1,explicitTab:e})}handleTabCompletion(){if(!this.autocompleteProvider)return;let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);this.isInSlashCommandContext(e)&&!e.trimStart().includes(` `)?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(e=!1){this.requestAutocomplete({force:!0,explicitTab:e})}requestAutocomplete(e){if(!this.autocompleteProvider||e.force&&this.autocompleteProvider.shouldTriggerFileCompletion&&!this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol))return;this.cancelAutocompleteRequest();let t=++this.autocompleteStartToken,n=this.getAutocompleteDebounceMs(e);if(n>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(t,e)},n);return}this.startAutocompleteRequest(t,e)}async startAutocompleteRequest(e,t){let n=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await n,e!==this.autocompleteStartToken||!this.autocompleteProvider)return;let r=new AbortController;this.autocompleteAbort=r;let i=++this.autocompleteRequestId,a=this.getText(),o=this.state.cursorLine,s=this.state.cursorCol;await this.runAutocompleteRequest(i,r,a,o,s,t)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(e){let t=[...pp];for(let n of e)n.length!==1||n===`/`||bd(n)||t.includes(n)||t.push(n);this.autocompleteTriggerCharacters=t,this.autocompleteTriggerPattern=hp(t),this.autocompleteDebouncePattern=gp(t)}getAutocompleteDebounceMs(e){if(e.explicitTab||e.force)return 0;let t=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(t)?fp:0}async runAutocompleteRequest(e,t,n,r,i,a){if(!this.autocompleteProvider)return;let o=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:t.signal,force:a.force});if(this.isAutocompleteRequestCurrent(e,t,n,r,i)){if(this.autocompleteAbort=void 0,!o||!Array.isArray(o.items)||o.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(a.force&&a.explicitTab&&o.items.length===1){let e=o.items[0];this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,o.prefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(o,a.force?`force`:`regular`),this.tui.requestRender()}}isAutocompleteRequestCurrent(e,t,n,r,i){return!t.signal.aborted&&e===this.autocompleteRequestId&&this.getText()===n&&this.state.cursorLine===r&&this.state.cursorCol===i}applyAutocompleteSuggestions(e,t){this.autocompletePrefix=e.prefix,this.autocompleteList=this.createAutocompleteList(e.prefix,e.items);let n=this.getBestAutocompleteMatchIndex(e.items,e.prefix);n>=0&&this.autocompleteList.setSelectedIndex(n),this.autocompleteState=t}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&=(clearTimeout(this.autocompleteDebounceTimer),void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=``}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){this.autocompleteState&&this.autocompleteProvider&&this.requestAutocomplete({force:this.autocompleteState===`force`,explicitTab:!1})}},yp=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(e=``,t=1,n=1,r){this.text=e,this.paddingX=t,this.paddingY=n,this.customBgFn=r}setText(e){this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===``){let t=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=t,t}let t=this.text.replace(/\t/g,` `),n=Math.min(this.paddingX,Math.max(0,Math.floor((e-1)/2))),r=_d(t,Math.max(1,e-n*2)),i=` `.repeat(n),a=` `.repeat(n),o=[];for(let t of r){let n=i+t+a;if(this.customBgFn)o.push(Sd(n,e,this.customBgFn));else{let t=X(n),r=Math.max(0,e-t);o.push(n+` `.repeat(r))}}let s=` `.repeat(e),c=[];for(let t=0;t0?l:[``]}},bp=class{text;paddingX;paddingY;constructor(e,t=0,n=0){this.text=e,this.paddingX=t,this.paddingY=n}invalidate(){}render(e){let t=[],n=` `.repeat(e);for(let e=0;enull};function Tp(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function Z(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Dp.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Ep=((e=``)=>{try{return!!RegExp(`(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Tp(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Tp(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Tp(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Tp(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Tp(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Tp(e=>RegExp(`^ {0,${e}}>`))},Op=/^(?:[ \t]*(?:\n|$))+/,kp=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ap=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,jp=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Mp=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Np=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Pp=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Fp=Z(Pp).replace(/bull/g,Np).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),Ip=Z(Pp).replace(/bull/g,Np).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Lp=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Rp=/^[^\n]+/,zp=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Bp=Z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,zp).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Vp=Z(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Np).getRegex(),Hp=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,Up=/|$))/,Wp=Z(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,Up).replace(`tag`,Hp).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Gp=Z(Lp).replace(`hr`,jp).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Hp).getRegex(),Kp={blockquote:Z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Gp).getRegex(),code:kp,def:Bp,fences:Ap,heading:Mp,hr:jp,html:Wp,lheading:Fp,list:Vp,newline:Op,paragraph:Gp,table:wp,text:Rp},qp=Z(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,jp).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Hp).getRegex(),Jp={...Kp,lheading:Ip,table:qp,paragraph:Z(Lp).replace(`hr`,jp).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,qp).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Hp).getRegex()},Yp={...Kp,html:Z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Up).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:wp,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Z(Lp).replace(`hr`,jp).replace(`heading`,` *#{1,6} *[^ +]`).replace(`lheading`,Fp).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Xp=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Zp=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Qp=/^( {2,}|\\)\n(?!\s*$)/,$p=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Ep?"(?`+)[^`]+\k(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),cm=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,lm=Z(cm,`u`).replace(/punct/g,em).getRegex(),um=Z(cm,`u`).replace(/punct/g,im).getRegex(),dm=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,fm=Z(dm,`gu`).replace(/notPunctSpace/g,nm).replace(/punctSpace/g,tm).replace(/punct/g,em).getRegex(),pm=Z(dm,`gu`).replace(/notPunctSpace/g,om).replace(/punctSpace/g,am).replace(/punct/g,im).getRegex(),mm=Z(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,nm).replace(/punctSpace/g,tm).replace(/punct/g,em).getRegex(),hm=Z(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,em).getRegex(),gm=Z(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,nm).replace(/punctSpace/g,tm).replace(/punct/g,em).getRegex(),_m=Z(/\\(punct)/,`gu`).replace(/punct/g,em).getRegex(),vm=Z(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ym=Z(Up).replace(`(?:-->|$)`,`-->`).getRegex(),bm=Z(`^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^`).replace(`comment`,ym).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),xm=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Sm=Z(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,xm).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Cm=Z(/^!?\[(label)\]\[(ref)\]/).replace(`label`,xm).replace(`ref`,zp).getRegex(),wm=Z(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,zp).getRegex(),Tm=Z(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Cm).replace(`nolink`,wm).getRegex(),Em=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Dm={_backpedal:wp,anyPunctuation:_m,autolink:vm,blockSkip:sm,br:Qp,code:Zp,del:wp,delLDelim:wp,delRDelim:wp,emStrongLDelim:lm,emStrongRDelimAst:fm,emStrongRDelimUnd:mm,escape:Xp,link:Sm,nolink:wm,punctuation:rm,reflink:Cm,reflinkSearch:Tm,tag:bm,text:$p,url:wp},Om={...Dm,link:Z(/^!?\[(label)\]\((.*?)\)/).replace(`label`,xm).getRegex(),reflink:Z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,xm).getRegex()},km={...Dm,emStrongRDelimAst:pm,emStrongLDelim:um,delLDelim:hm,delRDelim:gm,url:Z(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Em).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Z(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":`>`,'"':`"`,"'":`'`},Pm=e=>Nm[e];function Fm(e,t){if(t){if(Dp.escapeTest.test(e))return e.replace(Dp.escapeReplace,Pm)}else if(Dp.escapeTestNoEncode.test(e))return e.replace(Dp.escapeReplaceNoEncode,Pm);return e}function Im(e){try{e=encodeURI(e).replace(Dp.percentDecode,`%`)}catch{return null}return e}function Lm(e,t){let n=e.replace(Dp.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Dp.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length=0&&Dp.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(` +`)}function Bm(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r0?-2:-1}function Vm(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Hm(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Um(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(` +`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(` +`)}var Wm=class{options;rules;lexer;constructor(e){this.options=e||Sp}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:zm(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=Um(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Rm(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:Rm(t[0],` +`),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Rm(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Rm(t[0],` +`).split(` +`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o=0;for(;o1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=Vm(t[2].split(` +`,1)[0],t[1].length),l=e.split(` +`,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+` +`,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(` +`,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=` +`+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=` +`+l}u=!l.trim(),r+=p+` +`,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=zm(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:Rm(t[0],` +`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Lm(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(` +`):[],a={type:`table`,raw:Rm(t[0],` +`),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:Rm(t[0],` +`),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Rm(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Bm(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Hm(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Hm(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},Gm=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Sp,this.options.tokenizer=this.options.tokenizer||new Wm,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:Dp,block:jm.normal,inline:Mm.normal};this.options.pedantic?(t.block=jm.pedantic,t.inline=Mm.pedantic):this.options.gfm&&(t.block=jm.gfm,t.inline=this.options.breaks?Mm.breaks:Mm.gfm),this.tokenizer.rules=t}static get rules(){return{block:jm,inline:Mm}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Dp.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let e=0;e(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=` +`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(` +`)?``:` +`)+i.raw,n.text+=` +`+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(` +`)?``:` +`)+i.raw,n.text+=` +`+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let r=t.at(-1);n&&r?.type===`paragraph`?(r.raw+=(r.raw.endsWith(` +`)?``:` +`)+i.raw,r.text+=` +`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(` +`)?``:` +`)+i.raw,n.text+=` +`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},Km=class{options;parser;constructor(e){this.options=e||Sp}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Dp.notSpaceStart)?.[0],i=e.replace(Dp.endingNewline,``)+` +`;return r?`
`+(n?i:Fm(i,!0))+`
+`:`
`+(n?i:Fm(i,!0))+`
+`}blockquote({tokens:e}){return`
+${this.parser.parse(e)}
+`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
+`}list(e){let t=e.ordered,n=e.start,r=``;for(let t=0;t +`+r+` +`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • +`}checkbox({checked:e}){return` `}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t=``,n=``;for(let t=0;t${r}`,` + +`+t+` +`+r+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${Fm(e,!0)}`}br(e){return`
    `}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Im(e);if(i===null)return r;e=i;let a=`
    `+r+``,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Im(e);if(i===null)return Fm(n);e=i;let a=`${Fm(n)}`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Fm(e.text)}},qm=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},Jm=class e{options;renderer;textRenderer;constructor(e){this.options=e||Sp,this.options.renderer=this.options.renderer||new Km,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new qm}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new Km(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Wm(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Ym;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=Ym.passThroughHooks.has(n)?e=>{if(this.defaults.async&&Ym.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Gm.lex(e,t??this.defaults)}parser(e,t){return Jm.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Gm.lex:Gm.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?Jm.parse:Jm.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Gm.lex:Gm.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?Jm.parse:Jm.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let e=`

    An error occurred:

    `+Fm(n.message+``,!0)+`
    `;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},Zm=new Xm;function Qm(e,t){return Zm.parse(e,t)}Qm.options=Qm.setOptions=function(e){return Zm.setOptions(e),Qm.defaults=Zm.defaults,Cp(Qm.defaults),Qm},Qm.getDefaults=xp,Qm.defaults=Sp,Qm.use=function(...e){return Zm.use(...e),Qm.defaults=Zm.defaults,Cp(Qm.defaults),Qm},Qm.walkTokens=function(e,t){return Zm.walkTokens(e,t)},Qm.parseInline=Zm.parseInline,Qm.Parser=Jm,Qm.parser=Jm.parse,Qm.Renderer=Km,Qm.TextRenderer=qm,Qm.Lexer=Gm,Qm.lexer=Gm.lex,Qm.Tokenizer=Wm,Qm.Hooks=Ym,Qm.parse=Qm,Qm.options,Qm.setOptions,Qm.use,Qm.walkTokens,Qm.parseInline,Jm.parse,Gm.lex;var $m={alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ϵ`,varepsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,vartheta:`ϑ`,iota:`ι`,kappa:`κ`,varkappa:`ϰ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,pi:`π`,varpi:`ϖ`,rho:`ρ`,varrho:`ϱ`,sigma:`σ`,varsigma:`ς`,tau:`τ`,upsilon:`υ`,phi:`ϕ`,varphi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,Gamma:`Γ`,Delta:`Δ`,Theta:`Θ`,Lambda:`Λ`,Xi:`Ξ`,Pi:`Π`,Sigma:`Σ`,Upsilon:`Υ`,Phi:`Φ`,Psi:`Ψ`,Omega:`Ω`,pm:`±`,mp:`∓`,times:`×`,div:`÷`,cdot:`·`,ast:`∗`,star:`⋆`,circ:`∘`,bullet:`•`,oplus:`⊕`,ominus:`⊖`,otimes:`⊗`,oslash:`⊘`,odot:`⊙`,bigcirc:`○`,dagger:`†`,ddagger:`‡`,amalg:`⨿`,uplus:`⊎`,sqcap:`⊓`,sqcup:`⊔`,bowtie:`⋈`,Join:`⋈`,ltimes:`⋉`,rtimes:`⋊`,leftouterjoin:`⟕`,rightouterjoin:`⟖`,fullouterjoin:`⟗`,triangleleft:`◁`,triangleright:`▷`,wr:`≀`,cap:`∩`,cup:`∪`,bigcap:`⋂`,bigcup:`⋃`,bigwedge:`⋀`,bigvee:`⋁`,bigsqcup:`⨆`,biguplus:`⨄`,bigoplus:`⨁`,bigotimes:`⨂`,bigodot:`⨀`,setminus:`∖`,in:`∈`,notin:`∉`,ni:`∋`,subset:`⊂`,supset:`⊃`,subseteq:`⊆`,supseteq:`⊇`,sqsubset:`⊏`,sqsupset:`⊐`,sqsubseteq:`⊑`,sqsupseteq:`⊒`,prec:`≺`,preceq:`≼`,succ:`≻`,succeq:`≽`,ll:`≪`,gg:`≫`,le:`≤`,leq:`≤`,leqslant:`≤`,ge:`≥`,geq:`≥`,geqslant:`≥`,ne:`≠`,neq:`≠`,equiv:`≡`,approx:`≈`,sim:`∼`,simeq:`≃`,cong:`≅`,asymp:`≍`,doteq:`≐`,propto:`∝`,parallel:`∥`,perp:`⊥`,mid:`∣`,vdash:`⊢`,dashv:`⊣`,models:`⊨`,Vdash:`⊩`,Vvdash:`⊪`,nvdash:`⊬`,nvDash:`⊭`,forall:`∀`,exists:`∃`,nexists:`∄`,neg:`¬`,land:`∧`,wedge:`∧`,lor:`∨`,vee:`∨`,to:`→`,rightarrow:`→`,longrightarrow:`→`,leftarrow:`←`,longleftarrow:`←`,gets:`←`,leftrightarrow:`↔`,longleftrightarrow:`↔`,hookleftarrow:`↩`,hookrightarrow:`↪`,twoheadleftarrow:`↞`,twoheadrightarrow:`↠`,leftharpoonup:`↼`,leftharpoondown:`↽`,rightharpoonup:`⇀`,rightharpoondown:`⇁`,rightleftharpoons:`⇌`,leftrightharpoons:`⇋`,nearrow:`↗`,searrow:`↘`,swarrow:`↙`,nwarrow:`↖`,rightsquigarrow:`⇝`,leadsto:`⇝`,Rightarrow:`⇒`,Longrightarrow:`⇒`,Leftarrow:`⇐`,Longleftarrow:`⇐`,Leftrightarrow:`⇔`,Longleftrightarrow:`⇔`,implies:`⇒`,iff:`⇔`,mapsto:`↦`,longmapsto:`↦`,uparrow:`↑`,downarrow:`↓`,partial:`∂`,nabla:`∇`,int:`∫`,iint:`∬`,iiint:`∭`,oint:`∮`,sum:`∑`,prod:`∏`,coprod:`∐`,infty:`∞`,emptyset:`∅`,varnothing:`∅`,angle:`∠`,therefore:`∴`,because:`∵`,aleph:`ℵ`,beth:`ℶ`,gimel:`ℷ`,daleth:`ℸ`,top:`⊤`,bot:`⊥`,triangle:`△`,square:`□`,lozenge:`◊`,checkmark:`✓`,complement:`∁`,wp:`℘`,prime:`′`,ldots:`…`,dots:`…`,cdots:`⋯`,vdots:`⋮`,ddots:`⋱`,ell:`ℓ`,hbar:`ℏ`,Im:`ℑ`,Re:`ℜ`,langle:`⟨`,rangle:`⟩`,vert:`|`,lvert:`|`,rvert:`|`,Vert:`‖`,lVert:`‖`,rVert:`‖`,lbrace:`{`,rbrace:`}`,backslash:`\\`,lfloor:`⌊`,rfloor:`⌋`,lceil:`⌈`,rceil:`⌉`,colon:`:`},eh=new Set(`arccos.arcsin.arctan.arg.cos.cosh.cot.coth.csc.deg.det.dim.exp.gcd.hom.inf.ker.lg.lim.liminf.limsup.ln.log.max.min.Pr.sec.sin.sinh.sup.tan.tanh`.split(`.`)),th=new Set([`argmax`,`argmin`,`inf`,`injlim`,`lim`,`liminf`,`limsup`,`max`,`min`,`projlim`,`sup`]),nh=new Set([`bigcap`,`bigcup`,`bigodot`,`bigoplus`,`bigotimes`,`bigsqcup`,`biguplus`,`bigvee`,`bigwedge`,`coprod`,`int`,`iint`,`iiint`,`oint`,`prod`,`sum`]),rh=new Set(`Leftarrow.Leftrightarrow.Longleftarrow.Longleftrightarrow.Longrightarrow.Rightarrow.Join.Vdash.Vvdash.approx.asymp.bowtie.cong.dashv.fullouterjoin.doteq.downarrow.equiv.ge.geq.geqslant.gets.gg.hookleftarrow.hookrightarrow.iff.implies.in.leadsto.le.leftarrow.leftharpoondown.leftharpoonup.leftrightarrow.leftrightharpoons.leftouterjoin.leq.leqslant.ll.longleftarrow.longleftrightarrow.longmapsto.longrightarrow.ltimes.mapsto.mid.models.ne.nearrow.neq.ni.notin.nvdash.nvDash.nwarrow.parallel.perp.prec.preceq.propto.rightharpoondown.rightharpoonup.rightleftharpoons.rightouterjoin.rightarrow.rightsquigarrow.rtimes.searrow.sim.simeq.sqsubset.sqsubseteq.sqsupset.sqsupseteq.subset.subseteq.succ.succeq.supset.supseteq.swarrow.to.triangleleft.triangleright.twoheadleftarrow.twoheadrightarrow.uparrow.vdash`.split(`.`)),ih={"<":`≮`,">":`≯`,"=":`≠`,"∈":`∉`,"∋":`∌`,"∣":`∤`,"∥":`∦`,"∼":`≁`,"≃":`≄`,"≅":`≇`,"≈":`≉`,"≡":`≢`,"≤":`≰`,"≥":`≱`,"≺":`⊀`,"≻":`⊁`,"⊂":`⊄`,"⊃":`⊅`,"⊆":`⊈`,"⊇":`⊉`,"⊢":`⊬`,"⊨":`⊭`,"↔":`↮`,"←":`↚`,"→":`↛`,"⇒":`⇏`,"⇐":`⇍`,"⇔":`⇎`,"≼":`⋠`,"≽":`⋡`},ah={C:`ℂ`,H:`ℍ`,N:`ℕ`,P:`ℙ`,Q:`ℚ`,R:`ℝ`,Z:`ℤ`},oh={0:`⁰`,1:`¹`,2:`²`,3:`³`,4:`⁴`,5:`⁵`,6:`⁶`,7:`⁷`,8:`⁸`,9:`⁹`,"+":`⁺`,"-":`⁻`,"=":`⁼`,"(":`⁽`,")":`⁾`,a:`ᵃ`,b:`ᵇ`,c:`ᶜ`,d:`ᵈ`,e:`ᵉ`,f:`ᶠ`,g:`ᵍ`,h:`ʰ`,i:`ⁱ`,j:`ʲ`,k:`ᵏ`,l:`ˡ`,m:`ᵐ`,n:`ⁿ`,o:`ᵒ`,p:`ᵖ`,r:`ʳ`,s:`ˢ`,t:`ᵗ`,u:`ᵘ`,v:`ᵛ`,w:`ʷ`,x:`ˣ`,y:`ʸ`,z:`ᶻ`},sh={0:`₀`,1:`₁`,2:`₂`,3:`₃`,4:`₄`,5:`₅`,6:`₆`,7:`₇`,8:`₈`,9:`₉`,"+":`₊`,"-":`₋`,"=":`₌`,"(":`₍`,")":`₎`,a:`ₐ`,e:`ₑ`,h:`ₕ`,i:`ᵢ`,j:`ⱼ`,k:`ₖ`,l:`ₗ`,m:`ₘ`,n:`ₙ`,o:`ₒ`,p:`ₚ`,r:`ᵣ`,s:`ₛ`,t:`ₜ`,u:`ᵤ`,v:`ᵥ`,x:`ₓ`},ch=new Set([`,`,`:`,`;`,` `,`>`,`enspace`,`enskip`,`medspace`,`quad`,`qquad`,`thickspace`,`thinspace`]),lh=new Set([`!`,`negmedspace`,`negthickspace`,`negthinspace`]),uh=`\0`,dh=new Set([`displaystyle`,`limits`,`nolimits`,`scriptstyle`,`scriptscriptstyle`,`textstyle`]),fh=new Set([`big`,`Big`,`bigg`,`Bigg`,`bigl`,`Bigl`,`biggl`,`Biggl`,`bigr`,`Bigr`,`biggr`,`Biggr`]),ph=new Set(`emph.mathcal.mathbf.mathfrak.mathit.mathrm.mathnormal.mathscr.mathsf.mathtt.mathup.mbox.overbrace.pmb.smash.substack.text.textbf.textit.textmd.textnormal.textrm.textsc.textsf.textsl.texttt.textup.underbrace.bm.boldsymbol`.split(`.`)),mh={acute:`́`,bar:`̅`,breve:`̆`,check:`̌`,ddot:`̈`,dot:`̇`,grave:`̀`,hat:`̂`,mathring:`̊`,overleftarrow:`⃖`,overleftrightarrow:`⃡`,overline:`̅`,overrightarrow:`⃗`,tilde:`̃`,underline:`̲`,vec:`⃗`,widehat:`̂`,widetilde:`̃`};function hh(e,t){let n=``;for(let r of e){let e=t[r];if(e===void 0)return;n+=e}return n}function gh(e,t){e=e.trim();let n=t===`sub`?sh:oh,r=hh(e.replace(/\s*([=+-])\s*/g,`$1`),n);if(r!==void 0)return r;let i=t===`sub`?`_`:`^`;return Array.from(e).length===1||t===`sub`&&/^[A-Za-z]+$/.test(e)?`${i}${e}`:`${i}(${e})`}function _h(e,t){e=e.trim(),t=t.trim();let n=/^[\p{L}\p{N}.]+$/u.test(e),r=/^[\p{N}.]+$/u.test(t)||Array.from(t).length===1;return`${n?e:`(${e})`}/${r?t:`(${t})`}`}function vh(e,t=`√`){return e=e.trim(),/^[\p{L}\p{N}.]+$/u.test(e)?`${t}${e}`:`${t}(${e})`}var yh=`󰀄`,bh=`󰀅`,xh=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,Sh=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function Ch(e){return e.replace(xh,` `).replaceAll(yh,``).replace(Sh,` `).replaceAll(bh,``).split(` +`).map(e=>e.replace(/[ \t]+/g,` `).trim()).filter((e,t,n)=>e.length>0||t>0&&te.baseline)),n=Math.max(...e.map(e=>e.lines.length-e.baseline-1)),r=[];for(let i=0;i<=t+n;i++){let n=``;for(let r of e){let e=i-t+r.baseline;n+=e>=0&&ee+t.width,0),baseline:t}}function jh(e,t){let n=[],r=0;for(let i of e.split(` +`)){let e=[],a=0,o;for(let n of i.matchAll(Eh)){let r=n.index,s=t[Number(n[1])];if(s){if(r>a){let t=i.slice(a,r),n=(o?t.trimStart():t).trimEnd(),c=o?.type===`matrix`&&/^\s/.test(t),l=s.type===`matrix`&&/\s$/.test(t),u=n?`${c?` `:``}${n}${l?` `:``}`:c||l?` `:``;e.push({lines:[u],width:X(u),baseline:0})}if(s.type===`fraction`){let n=jh(s.numerator,t),r=jh(s.denominator,t),i=Math.max(n.width,r.width,1),a=i+2;e.push({lines:[...n.lines.map(e=>kh(e,a,!0)),` ${`─`.repeat(i)} `,...r.lines.map(e=>kh(e,a,!0))],width:a,baseline:n.lines.length})}else if(s.type===`operator`){let t=Math.max(X(s.operator),s.lower===void 0?0:X(s.lower),s.upper===void 0?0:X(s.upper)),n=[];s.upper!==void 0&&n.push(`${kh(s.upper,t,!0)} `),n.push(`${kh(s.operator,t,!0)} `),s.lower!==void 0&&n.push(`${kh(s.lower,t,!0)} `),e.push({lines:n,width:t+1,baseline:s.upper===void 0?0:1})}else{let t=Math.max(0,...s.lines.map(e=>X(e)));e.push({lines:s.lines.map(e=>kh(e,t)),width:t,baseline:s.baseline})}a=r+n[0].length,o=s}}if(aX(e))),baseline:r}}var Mh=class e{source;layoutNodes;display;position=0;supported=!0;stackFractions=!0;constructor(e,t,n){this.source=e,this.layoutNodes=t,this.display=n}render(){let e=this.parseSequence();if(this.supported&&this.position===this.source.length)return Ch(e)}parseSequence(e){let t=``;for(;this.position`){t=`${t.trimEnd()} ${n} `,this.position++;continue}if(n===`&`){this.position++;continue}if(n===`~`){this.position++,t+=` `;continue}if(n===`.`){let e=Dh.exec(t),r=e?this.layoutNodes[Number(e[1])]:void 0;if(r?.type===`matrix`){let e=r.lines.length-1;r.lines[e]=`${r.lines[e]??``}${n}`,this.position++;continue}}t+=n,this.position++}return e&&(this.supported=!1),t}parseWhitespace(){for(;this.position=this.source.length)return this.supported=!1,``;let e=``,t=this.source[this.position]??``;if(t===` +`||t===`\r`)return this.position++,t===`\r`&&this.source[this.position]===` +`&&this.position++,` `;if(/[A-Za-z]/.test(t)){let t=this.position;for(;this.positionah[e]??e).join(``)}if(e===`operatorname`){let e=this.source[this.position]===`*`;e&&this.position++;let t=Ch(this.parseRequiredArgument()).trim();return this.parseOperator(t,`bracket`,e,!0)}if(e===`mod`||e===`bmod`)return` mod `;if(e===`pmod`||e===`pod`){let t=this.parseRequiredArgument().trim();return e===`pmod`?` (mod ${t})`:` (${t})`}if(e===`overset`||e===`stackrel`){let e=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${gh(e,`sup`)}`}if(e===`underset`){let e=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${gh(e,`sub`)}`}if(ph.has(e)){let t=this.parseRequiredArgument();return e.startsWith(`text`)||e===`mbox`?t:t.trim()}return e===`begin`?this.parseEnvironment():e===`end`?(this.supported=!1,``):(this.supported=!1,`\\${e}`)}parseOperator(e,t,n,r=!1){let i=n,a=this.position;for(;a=this.source.length)return this.supported=!1,``;if(this.source[this.position]===`{`)return this.position++,this.parseSequence(`}`);if(this.source[this.position]===`\\`)return this.parseCommand();let e=this.source[this.position]??``;return this.position++,e}parseOptionalArgument(){for(;this.position{let n=e.split(`&`),r=t?Array.from({length:Math.ceil(n.length/2)},(e,t)=>n.slice(t*2,t*2+2).join(``)).join(` `):n.join(``);return this.renderNested(r).trim()}).filter(Boolean).join(` +`)}if(e===`cases`||e===`cases*`){let e=this.splitEnvironmentRows(r).map(e=>e.split(`&`).map(e=>this.renderNested(e,!1).trim())).filter(e=>e.some(Boolean));return e.map((t,n)=>{let r=(t[0]??``).replace(/,\s*$/,``),i=t[1]??``,a=n===0?`⎧`:n===e.length-1?`⎩`:`⎨`,o=/^(?:if|when|for|otherwise)\b/i.test(i)?` `:` if `;return`${a} ${r}${i?`${o}${i}`:``}`}).join(` +`)}if([`array`,`matrix`,`smallmatrix`,`pmatrix`,`bmatrix`,`Bmatrix`,`vmatrix`,`Vmatrix`].includes(e)){let t=e===`array`?r.replace(/^\s*\{[^}]*\}/,``):r;return this.renderMatrix(e,t)}return this.supported=!1,r}renderMatrix(e,t){let n=this.splitEnvironmentRows(t).map(e=>e.split(`&`).map(e=>this.renderNested(e,!1).trim())).filter(e=>e.some(Boolean)),r=Math.max(0,...n.map(e=>e.length)),i=Array.from({length:r},(e,t)=>Math.max(0,...n.map(e=>X(e[t]??``)))),a=n.map(e=>Array.from({length:r},(t,n)=>{let r=e[n]??``;return`${r}${Oh.repeat(Math.max(0,(i[n]??0)-X(r)))}`}).join(` │ `)),o;if(e===`array`||e===`matrix`||e===`smallmatrix`)o=a;else{let t={pmatrix:[`⎛`,`⎞`,`⎜`,`⎟`,`⎝`,`⎠`],bmatrix:[`⎡`,`⎤`,`⎢`,`⎥`,`⎣`,`⎦`],Bmatrix:[`⎧`,`⎫`,`⎨`,`⎬`,`⎩`,`⎭`],vmatrix:[`│`,`│`,`│`,`│`,`│`,`│`],Vmatrix:[`║`,`║`,`║`,`║`,`║`,`║`]}[e];if(!t)return this.supported=!1,a.join(` +`);o=a.map((e,n)=>`${n===0?t[0]:n===a.length-1?t[4]:t[2]} ${e} ${n===0?t[1]:n===a.length-1?t[5]:t[3]}`)}return o.length<=1?o[0]??``:`${wh}${this.layoutNodes.push({type:`matrix`,lines:o,baseline:0})-1}${Th}`}renderNested(t,n=!0){let r=new e(t,this.layoutNodes,this.display&&n).render();return r===void 0?(this.supported=!1,t):r}};function Nh(e,t={}){let n=[],r=new Mh(e,n,t.display===!0).render();if(r===void 0)return;if(n.length===0)return r.replaceAll(Oh,` `);let i=jh(r,n).lines,a=Math.min(...i.filter(e=>e.trim()).map(e=>e.length-e.trimStart().length));return i.map(e=>e.slice(a).trimEnd()).join(` +`).trimEnd().replaceAll(Oh,` `)}var Ph=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,Fh=class extends Wm{del(e){let t=Ph.exec(e);if(!t)return;let n=t[2];return{type:`del`,raw:t[0],text:n,tokens:this.lexer.inlineTokens(n)}}};function Ih(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;r--)n++;return n%2==1}function Lh(e,t,n){let r=e.indexOf(t,n);for(;r>=0&&Ih(e,r);)r=e.indexOf(t,r+t.length);return r}function Rh(e){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(e)}function zh(e){let t=``,n=``;if(e.startsWith(`$$`))t=`$$`,n=`$$`;else if(e.startsWith(`\\(`))t=`\\(`,n=`\\)`;else if(e.startsWith(`\\[`))t=`\\[`,n=`\\]`;else if(e.startsWith(`$`)&&!/^\$\s/.test(e))t=`$`,n=`$`;else return;let r=Lh(e,n,t.length);if(r>=0&&t===`$`&&(/\s$/.test(e.slice(t.length,r))||/^\d/.test(e.slice(r+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(e.slice(t.length,r))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(e.slice(r+1))||e.slice(t.length,r).includes("`")))return;if(r<0){let n=e.slice(t.length);return t.startsWith(`\\`)||Rh(n)?{type:`latex`,raw:e,text:n,pending:!0}:void 0}let i=e.slice(t.length,r);if(i&&!i.includes(` +`))return{type:`latex`,raw:e.slice(0,r+n.length),text:i}}function Bh(e){let t=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(e);if(t?.[1])return{type:`latexBlock`,raw:t[0],text:t[1].trim()};let n=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(e);if(n?.[1])return{type:`latexBlock`,raw:n[0],text:n[1].trim()};let r=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(e);if(r)return{type:`latexBlock`,raw:r[0],text:r[1],pending:!0};let i=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(e);if(i?.[1]&&Rh(i[1]))return{type:`latexBlock`,raw:i[0],text:i[1],pending:!0}}var Vh=[{name:`latexBlock`,level:`block`,start(e){let t=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(e);return t?t.index+ +!!t[0].startsWith(` +`):void 0},tokenizer:Bh},{name:`latex`,level:`inline`,start(e){let t=[e.indexOf(`$`),e.indexOf(`\\(`),e.indexOf(`\\[`)].filter(e=>e>=0);return t.length>0?Math.min(...t):void 0},tokenizer:zh}];function Hh(e){let t=e[e.length-1];if(t?.type===`list`){Hh(t.items[t.items.length-1]?.tokens??[]);return}if(t?.type===`blockquote`){Hh(t.tokens??[]);return}if(t?.type!==`code`)return;let n=/^(`{3,}|~{3,})/.exec(t.raw)?.[1],r=t.raw.split(` +`).pop();!n||!r||r.length>=n.length||r!==n[0]?.repeat(r.length)||(t.text=t.text.slice(0,-r.length).replace(/\n$/,``))}var Uh=new Xm;Uh.setOptions({tokenizer:new Fh}),Uh.use({extensions:[...Vh]});var Wh=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;constructor(e,t,n,r,i,a){this.text=e,this.paddingX=t,this.paddingY=n,this.theme=r,this.defaultTextStyle=i,this.options=a?{...a}:{}}setText(e){this.text=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,e-this.paddingX*2),n=this.options.transform?.(this.text,t)??this.text;if(!n||n.trim()===``){let t=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=t,t}let r=n.replace(/\t/g,` `),i=Uh.lexer(r);Hh(i);let a=[];for(let e=0;e0?p:[``]}applyDefaultStyle(e){if(!this.defaultTextStyle)return e;let t=e;return this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t)),t}getDefaultStylePrefix(){if(!this.defaultTextStyle)return``;if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let e=`\0`;this.defaultTextStyle.color&&(e=this.defaultTextStyle.color(e)),this.defaultTextStyle.bold&&(e=this.theme.bold(e)),this.defaultTextStyle.italic&&(e=this.theme.italic(e)),this.defaultTextStyle.strikethrough&&(e=this.theme.strikethrough(e)),this.defaultTextStyle.underline&&(e=this.theme.underline(e));let t=e.indexOf(`\0`);return this.defaultStylePrefix=t>=0?e.slice(0,t):``,this.defaultStylePrefix}getStylePrefix(e){let t=e(`\0`),n=t.indexOf(`\0`);return n>=0?t.slice(0,n):``}getDefaultInlineStyleContext(){return{applyText:e=>this.applyDefaultStyle(e),stylePrefix:this.getDefaultStylePrefix()}}renderToken(e,t,n,r){let i=[];switch(e.type){case`heading`:{let t=e.depth,r=`${`#`.repeat(t)} `,a;a=t===1?e=>this.theme.heading(this.theme.bold(this.theme.underline(e))):e=>this.theme.heading(this.theme.bold(e));let o={applyText:a,stylePrefix:this.getStylePrefix(a)},s=this.renderInlineTokens(e.tokens||[],o),c=t>=3?a(r)+s:s;i.push(c),n&&n!==`space`&&i.push(``);break}case`paragraph`:{let t=this.renderInlineTokens(e.tokens||[],r);i.push(t),n&&n!==`list`&&n!==`space`&&i.push(``);break}case`text`:i.push(this.renderInlineTokens([e],r));break;case`latexBlock`:{let t=e,r=!t.pending&&this.options.renderLatex!==!1?Nh(t.text,{display:!0})??t.raw.trim():t.raw.trim();for(let e of r.split(` +`))i.push(this.applyDefaultStyle(e));n&&n!==`space`&&i.push(``);break}case`code`:{let t=this.theme.codeBlockIndent??` `;if(i.push(this.theme.codeBlockBorder(`\`\`\`${e.lang||``}`)),this.theme.highlightCode){let n=this.theme.highlightCode(e.text,e.lang);for(let e of n)i.push(`${t}${e}`)}else{let n=e.text.split(` +`);for(let e of n)i.push(`${t}${this.theme.codeBlock(e)}`)}i.push(this.theme.codeBlockBorder("```")),n&&n!==`space`&&i.push(``);break}case`list`:{let n=this.renderList(e,0,t,r);i.push(...n);break}case`table`:{let a=this.renderTable(e,t,n,r);i.push(...a);break}case`blockquote`:{let r=e=>this.theme.quote(this.theme.italic(e)),a=this.getStylePrefix(r),o=e=>{if(!a)return r(e);let t=e.replace(/\x1b\[0m/g,`\x1b[0m${a}`);return r(t)},s=Math.max(1,t-2),c={applyText:e=>e,stylePrefix:a},l=e.tokens||[],u=[];for(let e=0;e0&&u[u.length-1]===``;)u.pop();for(let e of u){let t=_d(o(e),s);for(let e of t)i.push(this.theme.quoteBorder(`│ `)+e)}n&&n!==`space`&&i.push(``);break}case`hr`:i.push(this.theme.hr(`─`.repeat(Math.min(t,80)))),n&&n!==`space`&&i.push(``);break;case`html`:`raw`in e&&typeof e.raw==`string`&&i.push(this.applyDefaultStyle(e.raw.trim()));break;case`space`:i.push(``);break;default:`text`in e&&typeof e.text==`string`&&i.push(e.text)}return i}renderInlineTokens(e,t){let n=``,r=t??this.getDefaultInlineStyleContext(),{applyText:i,stylePrefix:a}=r,o=e=>e.split(` +`).map(e=>i(e)).join(` +`);for(let t of e)switch(t.type){case`latex`:{let e=t,r=!e.pending&&this.options.renderLatex!==!1?Nh(e.text)??e.raw:e.raw;n+=o(r);break}case`escape`:n+=o(this.options.preserveBackslashEscapes?t.raw:t.text);break;case`text`:t.tokens&&t.tokens.length>0?n+=this.renderInlineTokens(t.tokens,r):n+=o(t.text);break;case`paragraph`:n+=this.renderInlineTokens(t.tokens||[],r);break;case`strong`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.bold(e)+a;break}case`em`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.italic(e)+a;break}case`codespan`:n+=this.theme.code(t.text)+a;break;case`link`:{let e=this.renderInlineTokens(t.tokens||[],r),i=this.theme.link(this.theme.underline(e));if(hu().hyperlinks)n+=wu(i,t.href)+a;else{let e=t.href.startsWith(`mailto:`)?t.href.slice(7):t.href;t.text===t.href||t.text===e?n+=i+a:n+=i+this.theme.linkUrl(` (${t.href})`)+a}break}case`br`:n+=` +`;break;case`del`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.strikethrough(e)+a;break}case`html`:`raw`in t&&typeof t.raw==`string`&&(n+=o(t.raw));break;default:`text`in t&&typeof t.text==`string`&&(n+=o(t.text))}for(;a&&n.endsWith(a);)n=n.slice(0,-a.length);return n}getOrderedListMarker(e){let t=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(e.raw);return t?`${t[1]} `:void 0}getUnorderedListMarker(e){let t=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(e.raw);return t?`${t[1]} `:void 0}renderList(e,t,n,r){let i=[],a=` `.repeat(t),o=typeof e.start==`number`?e.start:1;for(let s=0;se.length>0),r=0;for(let e of n)r=Math.max(r,X(e));return t===void 0?r:Math.min(r,t)}wrapCellText(e,t,n=``){let r=_d(e,Math.max(1,t));return r.map((e,t)=>`${e}${te+t,0);if(d>s){u=Array(a).fill(1);let e=s-a;if(e>0){let t=l.reduce((e,t)=>e+Math.max(0,t-1),0),n=l.map(n=>{let r=Math.max(0,n-1);return t>0?Math.floor(r/t*e):0});for(let e=0;ee+t,0);for(let e=0;r>0&&ee+t,0)}let f=c.reduce((e,t)=>e+t,0)+o,p;if(f<=t)p=c.map((e,t)=>Math.max(e,u[t]));else{let e=c.reduce((e,t,n)=>e+Math.max(0,t-u[n]),0),t=Math.max(0,s-d);p=u.map((n,r)=>{let i=c[r],a=Math.max(0,i-n),o=0;return e>0&&(o=Math.floor(a/e*t)),n+o});let n=s-p.reduce((e,t)=>e+t,0);for(;n>0;){let e=!1;for(let t=0;t0;t++)p[t]`─`.repeat(e));i.push(`┌─${m.join(`─┬─`)}─┐`);let h=e.header.map((e,t)=>{let n=this.renderInlineTokens(e.tokens||[],r);return this.wrapCellText(n,p[t],r?.stylePrefix)}),g=Math.max(...h.map(e=>e.length));for(let e=0;e{let r=t[e]||``,i=r+` `.repeat(Math.max(0,p[n]-X(r)));return this.theme.bold(i)});i.push(`│ ${t.join(` │ `)} │`)}let _=`├─${p.map(e=>`─`.repeat(e)).join(`─┼─`)}─┤`;i.push(_);for(let t=0;t{let n=this.renderInlineTokens(e.tokens||[],r);return this.wrapCellText(n,p[t],r?.stylePrefix)}),a=Math.max(...n.map(e=>e.length));for(let e=0;e{let r=t[e]||``;return r+` `.repeat(Math.max(0,p[n]-X(r)))});i.push(`│ ${t.join(` │ `)} │`)}t`─`.repeat(e));return i.push(`└─${v.join(`─┴─`)}─┘`),n&&n!==`space`&&i.push(``),i}},Gh=class{children=[];paddingX;paddingY;bgFn;cache;mouseLayout;constructor(e=1,t=1,n){this.paddingX=e,this.paddingY=t,this.bgFn=n}addChild(e){this.children.push(e),this.invalidateCache()}removeChild(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(e){this.bgFn=e}invalidateCache(){this.cache=void 0}matchCache(e,t,n){let r=this.cache;return!!r&&r.width===e&&r.bgSample===n&&r.childLines.length===t.length&&r.childLines.every((e,n)=>e===t[n])}invalidate(){this.invalidateCache();for(let e of this.children)e.invalidate?.()}handleMouse(e){let t=Math.max(1,e.width-this.paddingX*2),n=e.y-this.paddingY,r=e.x-this.paddingX;if(n<0||r<0||r>=t)return;let i=this.mouseLayout?.width===t?this.mouseLayout.children:this.children.map(e=>({component:e,height:e.render(t).length})),a=0;for(let{component:o,height:s}of i){if(n>=a&&ne.component.render(t.width)),i=df(n,r.map(e=>e.length),void 0,this.gap),a=[];for(let e=0;e0)for(let e=0;e{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r=6?`complete`:`incomplete`:ng(e):t.startsWith(`]`)?rg(e):t.startsWith(`P`)?ig(e):t.startsWith(`_`)?ag(e):t.startsWith(`O`)?t.length>=2?`complete`:`incomplete`:(t.length,`complete`)}function ng(e){if(!e.startsWith(`${Xh}[`))return`complete`;if(e.length<3)return`incomplete`;let t=e.slice(2),n=t[t.length-1],r=n.charCodeAt(0);if(r>=64&&r<=126){if(t.startsWith(`<`)){if(/^<\d+;\d+;\d+[Mm]$/.test(t))return`complete`;if(n===`M`||n===`m`){let e=t.slice(1,-1).split(`;`);if(e.length===3&&e.every(e=>/^\d+$/.test(e)))return`complete`}return`incomplete`}return`complete`}return`incomplete`}function rg(e){return!e.startsWith(`${Xh}]`)||e.endsWith(`${Xh}\\`)||e.endsWith(`\x07`)?`complete`:`incomplete`}function ig(e){return!e.startsWith(`${Xh}P`)||e.endsWith(`${Xh}\\`)?`complete`:`incomplete`}function ag(e){return!e.startsWith(`${Xh}_`)||e.endsWith(`${Xh}\\`)?`complete`:`incomplete`}function og(e){let t=e.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!t)return;let n=parseInt(t[1],10);return n>=32?n:void 0}function sg(e){let t=[],n=0;for(;nr.length)return{sequences:t,remainder:r}}else t.push(r[0]),n++}return{sequences:t,remainder:``}}var cg=class extends Yh.EventEmitter{buffer=``;timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer=``;pendingKittyPrintableCodepoint;constructor(e={}){super(),this.timeoutMs=e.timeout??Zh,this.escapeTimeoutMs=e.escapeTimeout??Qh}process(e){this.timeout&&=(clearTimeout(this.timeout),null);let t;if(Sl.Buffer.isBuffer(e)){if(e.length===1&&e[0]>127){let n=e[0]-128;t=`\x1b${String.fromCharCode(n)}`}else t=e.toString()}else t=e;if(t.length===0&&this.buffer.length===0){this.emitDataSequence(``);return}if(this.buffer+=t,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer=``;let e=this.pasteBuffer.indexOf(eg);if(e!==-1){let t=this.pasteBuffer.slice(0,e),n=this.pasteBuffer.slice(e+6);this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0,this.emit(`paste`,t),n.length>0&&this.process(n)}return}let n=this.buffer.indexOf($h);if(n!==-1){if(n>0){let e=sg(this.buffer.slice(0,n));for(let t of e.sequences)this.emitDataSequence(t)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(n+6),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer=``;let e=this.pasteBuffer.indexOf(eg);if(e!==-1){let t=this.pasteBuffer.slice(0,e),n=this.pasteBuffer.slice(e+6);this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0,this.emit(`paste`,t),n.length>0&&this.process(n)}return}let r=sg(this.buffer);this.buffer=r.remainder;for(let e of r.sequences)this.emitDataSequence(e);if(this.buffer.length>0){let e=this.buffer===Xh?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let e=this.flush();for(let t of e)this.emitDataSequence(t)},e)}}emitDataSequence(e){let t=e.length===1?e.codePointAt(0):void 0;if(t!==void 0&&t===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=og(e),this.emit(`data`,e)}flush(){if(this.timeout&&=(clearTimeout(this.timeout),null),this.buffer.length===0)return[];let e=[this.buffer];return this.buffer=``,this.pendingKittyPrintableCodepoint=void 0,e}clear(){this.timeout&&=(clearTimeout(this.timeout),null),this.buffer=``,this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}},lg=class extends vp{keybindings;workingStatusIndicator;embedWorkingStatus;actionHandlers=new Map;onEscape;onCtrlD;onPasteImage;onExtensionShortcut;constructor(e,t,n,r){super(e,t,r),this.keybindings=n,this.embedWorkingStatus=r?.embedWorkingStatus??!1}setWorkingStatusIndicator(e){this.workingStatusIndicator=e}renderTopBorder(e,t){if(!this.embedWorkingStatus||!this.workingStatusIndicator||e<=0)return super.renderTopBorder(e,t);let n=this.workingStatusIndicator.renderInBorder(Math.max(1,e-5)),r=X(n);if(r===0)return super.renderTopBorder(e,t);let i=t>0?` ↑ ${t} more `:void 0,a=i?X(i):0,o=Math.floor((e-a)/2),s=()=>i!==void 0&&a+2<=e&&o-(3+r+1)>=1;if(i&&!s()&&(n=this.workingStatusIndicator.renderSpinnerInBorder(e),r=X(n)),s()){let t=3+r+1;return this.borderColor(`── `)+n+this.borderColor(` ${`─`.repeat(o-t)}${i}${`─`.repeat(e-o-a)}`)}if(e>=r+5)return this.borderColor(`── `)+n+this.borderColor(` ${`─`.repeat(e-r-4)}`);n=this.workingStatusIndicator.renderSpinnerInBorder(e),r=X(n);let c=Math.min(3,Math.max(0,e-r));return this.borderColor(`─`.repeat(c))+n+this.borderColor(`─`.repeat(Math.max(0,e-c-r)))}onAction(e,t){this.actionHandlers.set(e,t)}handleInput(e){if(!this.onExtensionShortcut?.(e)){if(this.keybindings.matches(e,`app.clipboard.pasteImage`)){this.onPasteImage?.();return}if(this.keybindings.matches(e,`app.interrupt`)){if(!this.isShowingAutocomplete()){let e=this.onEscape??this.actionHandlers.get(`app.interrupt`);if(e){e();return}}super.handleInput(e);return}if(this.keybindings.matches(e,`app.exit`)&&this.getText().length===0){let e=this.onCtrlD??this.actionHandlers.get(`app.exit`);e&&e();return}if(this.keybindings.matches(e,`tui.editor.historyPrevious`)||this.keybindings.matches(e,`tui.editor.historyNext`)){super.handleInput(e);return}for(let[t,n]of this.actionHandlers)if(t!==`app.interrupt`&&t!==`app.exit`&&this.keybindings.matches(e,t)){n();return}super.handleInput(e)}}},ug={$schema:`https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json`,name:`dark`,vars:{cyan:`#00d7ff`,blue:`#5f87ff`,green:`#b5bd68`,red:`#cc6666`,yellow:`#ffff00`,text:`#d4d4d4`,gray:`#808080`,dimGray:`#666666`,darkGray:`#505050`,accent:`#8abeb7`,selectedBg:`#3a3a4a`,userMsgBg:`#343541`,toolPendingBg:`#282832`,toolSuccessBg:`#283228`,toolErrorBg:`#3c2828`,customMsgBg:`#2d2838`},colors:{accent:`accent`,border:`blue`,borderAccent:`cyan`,borderMuted:`darkGray`,success:`green`,error:`red`,warning:`yellow`,muted:`gray`,dim:`dimGray`,text:`text`,thinkingText:`gray`,selectedBg:`selectedBg`,scrollbarTrack:`darkGray`,scrollbarThumb:`text`,searchMatchBg:`selectedBg`,searchMatchText:`text`,userMessageBg:`userMsgBg`,userMessageText:`text`,customMessageBg:`customMsgBg`,customMessageText:`text`,customMessageLabel:`#9575cd`,toolPendingBg:`toolPendingBg`,toolSuccessBg:`toolSuccessBg`,toolErrorBg:`toolErrorBg`,toolTitle:`text`,toolOutput:`gray`,mdHeading:`#f0c674`,mdLink:`#81a2be`,mdLinkUrl:`dimGray`,mdCode:`accent`,mdCodeBlock:`green`,mdCodeBlockBorder:`gray`,mdQuote:`gray`,mdQuoteBorder:`gray`,mdHr:`gray`,mdListBullet:`accent`,toolDiffAdded:`green`,toolDiffRemoved:`red`,toolDiffContext:`gray`,syntaxComment:`#6A9955`,syntaxKeyword:`#569CD6`,syntaxFunction:`#DCDCAA`,syntaxVariable:`#9CDCFE`,syntaxString:`#CE9178`,syntaxNumber:`#B5CEA8`,syntaxType:`#4EC9B0`,syntaxOperator:`#D4D4D4`,syntaxPunctuation:`#D4D4D4`,thinkingOff:`darkGray`,thinkingMinimal:`#6e6e6e`,thinkingLow:`#5f87af`,thinkingMedium:`#81a2be`,thinkingHigh:`#b294bb`,thinkingXhigh:`#d183e8`,thinkingMax:`#ff5fff`,bashMode:`green`},export:{pageBg:`#18181e`,cardBg:`#1e1e24`,infoBg:`#3c3728`}},dg={muted:`#b0b0bd`,toolOutput:`#b0b0bd`,thinkingText:`#b0b0bd`,dim:`#aaaab7`,mdLinkUrl:`#aaaab7`,mdCodeBlockBorder:`#aaaab7`,mdQuote:`#b0b0bd`};function fg(e,t,n=!1){let r=(dg[e]??ug.vars[ug.colors[e]]??ug.colors[e]??ug.vars.text).slice(1).match(/../g).map(e=>parseInt(e,16)).join(`;`),i=`\x1b[${n?48:38};2;${r}m`,a=`\x1b[${n?49:39}m`;return i+String(t).replaceAll(a,i)+a}var pg={background:ug.export.pageBg,foreground:ug.vars.text,cursor:ug.vars.accent,cursorAccent:ug.export.pageBg,selectionBackground:ug.vars.selectedBg,selectionForeground:ug.vars.text,black:`#18181e`,brightBlack:`#9696a4`,white:`#d4d4d4`,brightWhite:`#f2f2f4`},Q={fg:(e,t)=>fg(e,t),bg:(e,t)=>fg(e,t,!0),bold:e=>`\x1b[1m${e}\x1b[22m`,italic:e=>`\x1b[3m${e}\x1b[23m`,underline:e=>`\x1b[4m${e}\x1b[24m`};function mg(){return{...Object.fromEntries(Object.entries({heading:`mdHeading`,link:`mdLink`,linkUrl:`mdLinkUrl`,code:`mdCode`,codeBlock:`mdCodeBlock`,codeBlockBorder:`mdCodeBlockBorder`,quote:`mdQuote`,quoteBorder:`mdQuoteBorder`,hr:`mdHr`,listBullet:`mdListBullet`}).map(([e,t])=>[e,e=>Q.fg(t,e)])),bold:Q.bold,italic:Q.italic,underline:Q.underline,strikethrough:e=>`\x1b[9m${e}\x1b[29m`,highlightCode:e=>e.split(` +`).map(e=>Q.fg(`mdCodeBlock`,e))}}function hg(){return{borderColor:e=>Q.fg(`borderMuted`,e),selectList:{selectedPrefix:e=>Q.fg(`accent`,e),selectedText:e=>Q.fg(`accent`,e),description:e=>Q.fg(`muted`,e),scrollInfo:e=>Q.fg(`muted`,e),noMatch:e=>Q.fg(`muted`,e)}}}function gg(e,t,n){return(r,i)=>_g(r,{messageType:e,isStreaming:t,availableWidth:i},n)}function _g(e,t,n){let r=e;for(let e of n)try{let n=e(r,t);typeof n==`string`&&(r=n)}catch{}return r}var vg=`\x1B]133;A\x07`,yg=class extends Nd{text;markdownTheme;outputPad;markdownTransformers;constructor(e,t=mg(),n=1,r=[]){super(),this.text=e,this.markdownTheme=t,this.outputPad=n,this.markdownTransformers=r,this.rebuild()}setOutputPad(e){this.outputPad=e,this.rebuild()}rebuild(){this.clear();let e=new Gh(this.outputPad,1,e=>Q.bg(`userMessageBg`,e));e.addChild(new Wh(this.text,0,0,this.markdownTheme,{color:e=>Q.fg(`userMessageText`,e)},{preserveOrderedListMarkers:!0,preserveBackslashEscapes:!0,transform:gg(`user`,!1,this.markdownTransformers)})),this.addChild(e)}render(e){let t=super.render(e);return t.length===0?t:(t[0]=vg+t[0],t[t.length-1]=`\x1B]133;B\x07\x1B]133;C\x07`+t[t.length-1],t)}},bg=`\x1B]133;A\x07`,xg=class extends Nd{contentContainer;hideThinkingBlock;markdownTheme;hiddenThinkingLabel;outputPad;markdownTransformers;lastMessage;hasToolCalls=!1;isStreaming=!1;thinkingVisibilityOverrides=new Map;constructor(e,t=!1,n=mg(),r=`Thinking...`,i=1,a=[]){super(),this.hideThinkingBlock=t,this.markdownTheme=n,this.hiddenThinkingLabel=r,this.outputPad=i,this.markdownTransformers=a,this.contentContainer=new Nd,this.addChild(this.contentContainer),e&&this.updateContent(e)}invalidate(){super.invalidate(),this.lastMessage&&this.updateContent(this.lastMessage)}setHideThinkingBlock(e){this.hideThinkingBlock=e,this.thinkingVisibilityOverrides.clear(),this.lastMessage&&this.updateContent(this.lastMessage)}setHiddenThinkingLabel(e){this.hiddenThinkingLabel=e,this.lastMessage&&this.updateContent(this.lastMessage)}setOutputPad(e){this.outputPad=e,this.lastMessage&&this.updateContent(this.lastMessage)}render(e){let t=super.render(e);return this.hasToolCalls||t.length===0?t:(t[0]=bg+t[0],t[t.length-1]=`\x1B]133;B\x07\x1B]133;C\x07`+t[t.length-1],t)}updateContent(e,t=this.isStreaming){this.lastMessage=e,this.isStreaming=t,this.contentContainer.clear(),e.content.some(e=>e.type===`text`&&e.text.trim()||e.type===`thinking`&&e.thinking.trim())&&this.contentContainer.addChild(new Kh(1));let n=0;for(let t=0;te.type===`text`&&e.text.trim()||e.type===`thinking`&&e.thinking.trim()),a=n++,o=this.thinkingVisibilityOverrides.get(a)??this.hideThinkingBlock,s=o?new yp(Q.italic(Q.fg(`thinkingText`,this.hiddenThinkingLabel)),this.outputPad,0):new Wh(r.join(` + +`),this.outputPad,0,this.markdownTheme,{color:e=>Q.fg(`thinkingText`,e),italic:!0},{transform:gg(`assistant-thinking`,this.isStreaming,this.markdownTransformers)});this.contentContainer.addChild(new qh(s,e=>{if(e.type===`click`&&e.button===`left`)return this.thinkingVisibilityOverrides.set(a,!o),this.lastMessage&&this.updateContent(this.lastMessage),{handled:!0}})),i&&this.contentContainer.addChild(new Kh(1))}}let r=e.content.some(e=>e.type===`toolCall`);if(this.hasToolCalls=r,e.stopReason===`length`)this.contentContainer.addChild(new Kh(1)),this.contentContainer.addChild(new yp(Q.fg(`error`,`Response was truncated before completion.`),this.outputPad,0));else if(!r){if(e.stopReason===`aborted`){let t=e.errorMessage&&e.errorMessage!==`Request was aborted`?e.errorMessage:`Operation aborted`;this.contentContainer.addChild(new Kh(1)),this.contentContainer.addChild(new yp(Q.fg(`error`,t),this.outputPad,0))}else if(e.stopReason===`error`){let t=e.errorMessage||`Unknown error`;this.contentContainer.addChild(new Kh(1)),this.contentContainer.addChild(new yp(Q.fg(`error`,`Error: ${t}`),this.outputPad,0))}}}},Sg=class{constructor(e){this.xterm=e,this.subscriptions=[]}start(e,t){this.input=new cg,this.input.on(`data`,e),this.input.on(`paste`,t=>e(`\x1b[200~${t}\x1b[201~`)),this.subscriptions.push(this.xterm.onData(e=>this.input.process(e)),this.xterm.onResize(t)),this.write(`\x1B[?2004h`)}stop(){this.subscriptions.forEach(e=>e.dispose()),this.subscriptions=[],this.input?.destroy(),this.write(`\x1B[?2004l`)}async drainInput(){}write(e){this.xterm.write(e)}get columns(){return this.xterm.cols}get rows(){return this.xterm.rows}get kittyProtocolActive(){return!1}moveBy(e){e&&this.write(`\x1b[${Math.abs(e)}${e>0?`B`:`A`}`)}hideCursor(){this.write(`\x1B[?25l`)}showCursor(){this.write(`\x1B[?25h`)}clearLine(){this.write(`\x1B[K`)}clearFromCursor(){this.write(`\x1B[J`)}clearScreen(){this.write(`\x1B[2J\x1B[H`)}setTitle(e){this.xterm.element?.setAttribute(`aria-label`,e)}setProgress(e){this.xterm.element?.setAttribute(`aria-busy`,String(e))}inputData(e){this.input?.process(e)}},Cg=o((e=>{function t(e,t,n){if(n===void 0&&(n=Array.prototype),e&&typeof n.find==`function`)return n.find.call(e,t);for(var i=0;i-1}var _=n({HTML:`http://www.w3.org/1999/xhtml`,SVG:`http://www.w3.org/2000/svg`,XML:`http://www.w3.org/XML/1998/namespace`,XMLNS:`http://www.w3.org/2000/xmlns/`});e.assign=i,e.find=t,e.freeze=n,e.HTML_BOOLEAN_ATTRIBUTES=a,e.HTML_RAW_TEXT_ELEMENTS=l,e.HTML_VOID_ELEMENTS=s,e.hasDefaultHTMLNamespace=p,e.hasOwn=r,e.isHTMLBooleanAttribute=o,e.isHTMLRawTextElement=u,e.isHTMLEscapableRawTextElement=d,e.isHTMLMimeType=f,e.isHTMLVoidElement=c,e.isValidMimeType=g,e.MIME_TYPE=m,e.NAMESPACE=_})),wg=o((e=>{var t=Cg();function n(e,t){e.prototype=Object.create(Error.prototype,{constructor:{value:e},name:{value:e.name,enumerable:!0,writable:t}})}var r=t.freeze({Error:`Error`,IndexSizeError:`IndexSizeError`,DomstringSizeError:`DomstringSizeError`,HierarchyRequestError:`HierarchyRequestError`,WrongDocumentError:`WrongDocumentError`,InvalidCharacterError:`InvalidCharacterError`,NoDataAllowedError:`NoDataAllowedError`,NoModificationAllowedError:`NoModificationAllowedError`,NotFoundError:`NotFoundError`,NotSupportedError:`NotSupportedError`,InUseAttributeError:`InUseAttributeError`,InvalidStateError:`InvalidStateError`,SyntaxError:`SyntaxError`,InvalidModificationError:`InvalidModificationError`,NamespaceError:`NamespaceError`,InvalidAccessError:`InvalidAccessError`,ValidationError:`ValidationError`,TypeMismatchError:`TypeMismatchError`,SecurityError:`SecurityError`,NetworkError:`NetworkError`,AbortError:`AbortError`,URLMismatchError:`URLMismatchError`,QuotaExceededError:`QuotaExceededError`,TimeoutError:`TimeoutError`,InvalidNodeTypeError:`InvalidNodeTypeError`,DataCloneError:`DataCloneError`,EncodingError:`EncodingError`,NotReadableError:`NotReadableError`,UnknownError:`UnknownError`,ConstraintError:`ConstraintError`,DataError:`DataError`,TransactionInactiveError:`TransactionInactiveError`,ReadOnlyError:`ReadOnlyError`,VersionError:`VersionError`,OperationError:`OperationError`,NotAllowedError:`NotAllowedError`,OptOutError:`OptOutError`}),i=Object.keys(r);function a(e){return typeof e==`number`&&e>=1&&e<=25}function o(e){return typeof e==`string`&&e.substring(e.length-r.Error.length)===r.Error}function s(e,t){a(e)?(this.name=i[e],this.message=t||``):(this.message=e,this.name=o(t)?t:r.Error),Error.captureStackTrace&&Error.captureStackTrace(this,s)}n(s,!0),Object.defineProperties(s.prototype,{code:{enumerable:!0,get:function(){var e=i.indexOf(this.name);return a(e)?e:0}}});for(var c={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25},l=Object.entries(c),u=0;u{function t(e){try{typeof e!=`function`&&(e=RegExp);var t=new e(`𝌆`,`u`).exec(`𝌆`);return!!t&&t[0].length===2}catch{}return!1}var n=t();function r(e){if(e.source[0]!==`[`)throw Error(e+` can not be used with chars`);return e.source.slice(1,e.source.lastIndexOf(`]`))}function i(e,t){if(e.source[0]!==`[`)throw Error(`/`+e.source+`/ can not be used with chars_without`);if(!t||typeof t!=`string`)throw Error(JSON.stringify(t)+` is not a valid search`);if(e.source.indexOf(t)===-1)throw Error(`"`+t+`" is not is /`+e.source+`/`);if(t===`-`&&e.source.indexOf(t)!==1)throw Error(`"`+t+`" is not at the first postion of /`+e.source+`/`);return new RegExp(e.source.replace(t,``),n?`u`:``)}function a(e){var t=this;return new RegExp(Array.prototype.slice.call(arguments).map(function(e){var n=typeof e==`string`;if(n&&t===void 0&&e===`|`)throw Error("use regg instead of reg to wrap expressions with `|`!");return n?e:e.source}).join(``),n?`u`:``)}function o(e){if(arguments.length===0)throw Error(`no parameters provided`);return a.apply(o,[`(?:`].concat(Array.prototype.slice.call(arguments),[`)`]))}var s=`�`,c=/[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/;n&&(c=a(`[`,r(c),`\\u{10000}-\\u{10FFFF}`,`]`));var l=RegExp(`[^`+r(c)+`]`,n?`u`:``),u=/[\x20\x09\x0D\x0A]/,d=r(u),f=a(u,`+`),p=a(u,`*`),m=/[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;n&&(m=a(`[`,r(m),`\\u{10000}-\\u{10FFFF}`,`]`));var h=a(`[`,r(m),r(/[-.0-9\xB7]/),r(/[\u0300-\u036F\u203F-\u2040]/),`]`),g=a(m,h,`*`),_=a(`^`,g,`$`),v=a(h,`+`),y=o(a(`&`,g,`;`),`|`,o(/&#[0-9]+;|&#x[0-9a-fA-F]+;/)),b=a(`%`,g,`;`),x=o(a(`"`,o(/[^%&"]/,`|`,b,`|`,y),`*`,`"`),`|`,a(`'`,o(/[^%&']/,`|`,b,`|`,y),`*`,`'`)),S=o(`"`,o(/[^<&"]/,`|`,y),`*`,`"`,`|`,`'`,o(/[^<&']/,`|`,y),`*`,`'`),C=a(i(m,`:`),i(h,`:`),`*`),w=a(`^`,C,`$`),T=a(C,o(`:`,C),`?`),E=a(`^`,T,`$`),D=a(`(`,T,`)`),O=o(/"[^"]*"|'[^']*'/),k=a(/^<\?/,`(`,g,`)`,o(f,`(?!`,u,`)(`,c,`*?)`),`?`,/\?>/),ee=/[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/,te=o(`"`,ee,`*"`,`|`,`'`,i(ee,`'`),`*'`),ne=``,re=a(ne,o(i(c,`-`),`|`,a(`-`,i(c,`-`))),`*`,A),j=`#PCDATA`,M=o(`EMPTY`,`|`,`ANY`,`|`,o(a(/\(/,p,j,o(p,/\|/,p,T),`*`,p,/\)\*/),`|`,a(/\(/,p,j,p,/\)/)),`|`,a(/\([^>]+\)/,/[?*+]?/)),N=a(``),P=a(``),ie=`about:legacy-compat`,F=o(`"`+ie+`"`,`|`,`'`+ie+`'`),I=`SYSTEM`,L=`PUBLIC`,R=o(o(I,f,O),`|`,o(L,f,te,f,O)),ae=a(`^`,o(o(I,f,`(?`,O,`)`),`|`,o(L,f,`(?`,te,`)`,f,`(?`,O,`)`))),oe=a(`^`,te,`$`),z=a(`^`,O,`$`),se=o(x,`|`,o(R,o(f,`NDATA`,f,g),`?`)),ce=``),`|`,a(ce,f,`%`,f,g,f,o(x,`|`,R),p,`>`)),ue=a(``),de=a(p,`=`,p),fe=/1[.]\d+/,B=a(f,`version`,de,o(`'`,fe,`'`,`|`,`"`,fe,`"`)),pe=/[A-Za-z][-A-Za-z0-9._]*/,me=a(/^<\?xml/,B,o(f,`encoding`,de,o(`"`,pe,`"`,`|`,`'`,pe,`'`)),`?`,o(f,`standalone`,de,o(`'`,o(`yes`,`|`,`no`),`'`,`|`,`"`,o(`yes`,`|`,`no`),`"`)),`?`,p,/\?>/),he=``,ve=a(//));e.chars=r,e.chars_without=i,e.detectUnicodeSupport=t,e.reg=a,e.regg=o,e.ABOUT_LEGACY_COMPAT=ie,e.ABOUT_LEGACY_COMPAT_SystemLiteral=F,e.AttlistDecl=P,e.CDATA_START=ge,e.CDATA_END=_e,e.CDSect=ve,e.Char=c,e.Comment=re,e.COMMENT_START=ne,e.COMMENT_END=A,e.DOCTYPE_DECL_START=he,e.elementdecl=N,e.EntityDecl=le,e.EntityValue=x,e.ExternalID=R,e.ExternalID_match=ae,e.Name=g,e.Name_exact=_,e.NCName_exact=w,e.NotationDecl=ue,e.Reference=y,e.PEReference=b,e.PI=k,e.PUBLIC=L,e.PubidLiteral=te,e.PubidLiteral_match=oe,e.QName=T,e.QName_exact=E,e.QName_group=D,e.S=f,e.SChar_s=d,e.S_OPT=p,e.SYSTEM=I,e.SystemLiteral=O,e.SystemLiteral_match=z,e.InvalidChar=l,e.UNICODE_REPLACEMENT_CHARACTER=s,e.UNICODE_SUPPORT=n,e.XMLDecl=me})),Eg=o((e=>{var t=Cg(),n=t.find,r=t.hasDefaultHTMLNamespace,i=t.hasOwn,a=t.isHTMLMimeType,o=t.isHTMLRawTextElement,s=t.isHTMLVoidElement,c=t.MIME_TYPE,l=t.NAMESPACE,u=Symbol(),d=wg(),f=d.DOMException,p=d.DOMExceptionName,m=Tg();function h(e){if(e!==u)throw TypeError(`Illegal constructor`)}function g(e){return e!==``}function _(e){return e?e.split(/[\t\n\f\r ]+/).filter(g):[]}function v(e,t){return i(e,t)||(e[t]=!0),e}function y(e){if(!e)return[];var t=_(e);return Object.keys(t.reduce(v,{}))}function b(e){return function(t){return e&&e.indexOf(t)!==-1}}function x(e){if(!m.QName_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`invalid character in qualified name "`+e+`"`)}function S(e,n){x(n),e||=null;var r=null,i=n;if(n.indexOf(`:`)>=0){var a=n.split(`:`);r=a[0],i=a[1]}if(r!==null&&e===null)throw new f(f.NAMESPACE_ERR,`prefix is non-null and namespace is null`);if(r===`xml`&&e!==t.NAMESPACE.XML)throw new f(f.NAMESPACE_ERR,`prefix is "xml" and namespace is not the XML namespace`);if((r===`xmlns`||n===`xmlns`)&&e!==t.NAMESPACE.XMLNS)throw new f(f.NAMESPACE_ERR,`either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace`);if(e===t.NAMESPACE.XMLNS&&r!==`xmlns`&&n!==`xmlns`)throw new f(f.NAMESPACE_ERR,`namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"`);return[e,r,i]}function C(e,t){for(var n in e)i(e,n)&&(t[n]=e[n])}function w(e,t){var n=e.prototype;if(!(n instanceof t)){function r(){}r.prototype=t.prototype,r=new r,C(n,r),e.prototype=n=r}n.constructor!=e&&(typeof e!=`function`&&console.error(`unknown Class:`+e),n.constructor=e)}var T={},E=T.ELEMENT_NODE=1,D=T.ATTRIBUTE_NODE=2,O=T.TEXT_NODE=3,k=T.CDATA_SECTION_NODE=4,ee=T.ENTITY_REFERENCE_NODE=5,te=T.ENTITY_NODE=6,ne=T.PROCESSING_INSTRUCTION_NODE=7,A=T.COMMENT_NODE=8,re=T.DOCUMENT_NODE=9,j=T.DOCUMENT_TYPE_NODE=10,M=T.DOCUMENT_FRAGMENT_NODE=11,N=T.NOTATION_NODE=12,P=t.freeze({DOCUMENT_POSITION_DISCONNECTED:1,DOCUMENT_POSITION_PRECEDING:2,DOCUMENT_POSITION_FOLLOWING:4,DOCUMENT_POSITION_CONTAINS:8,DOCUMENT_POSITION_CONTAINED_BY:16,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC:32});function ie(e,t){if(t.length=0&&e=0){for(var i=t.length-1;r<=i;)t[r]=t[++r];if(t.length=i,le(t,n),e){var a=e.ownerDocument;a&&ve(a,e,n),n.ownerElement=null}}}ae.prototype={length:0,item:I.prototype.item,getNamedItem:function(e){this._ownerElement&&this._ownerElement._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase());for(var t=0;t0;){var n=t.pop(),r=n.node,i=n.other;if(r.nodeType!==i.nodeType)return!1;switch(r.nodeType){case r.DOCUMENT_TYPE_NODE:if(r.name!==i.name||r.publicId!==i.publicId||r.systemId!==i.systemId)return!1;break;case r.ELEMENT_NODE:if(r.namespaceURI!==i.namespaceURI||r.prefix!==i.prefix||r.localName!==i.localName||r.attributes.length!==i.attributes.length)return!1;for(var a=0;a=0;a--)t.push({node:r.childNodes[a],other:i.childNodes[a]})}return!0},isSameNode:function(e){return this===e},insertBefore:function(e,t){return je(this,e,t)},replaceChild:function(e,t){je(this,e,t,Ae),t&&this.removeChild(t)},removeChild:function(e){return be(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return Ye(this.ownerDocument||this,this,e)},normalize:function(){he(this,null,{enter:function(e){for(var t=e.firstChild;t;){var n=t.nextSibling;if(n!==null&&n.nodeType===O&&t.nodeType===O){for(var r=[],i=n;i!==null&&i.nodeType===O;)r.push(i.data),i=i.nextSibling;for(var a=t.nextSibling;a!==i;){var o=a.nextSibling;a.parentNode=null,a.previousSibling=null,a.nextSibling=null,a=o}t.nextSibling=i,i===null?e.lastChild=t:i.previousSibling=t,t.appendData(r.join(``)),ye(e.ownerDocument,e),t=i}else t=n}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},lookupPrefix:function(e){for(var t=this;t;){var n=t._nsMap;if(n){for(var r in n)if(i(n,r)&&n[r]===e)return r}t=t.nodeType==D?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var n=t._nsMap;if(n&&i(n,e))return n[e];t=t.nodeType==D?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){return this.lookupPrefix(e)==null},compareDocumentPosition:function(e){if(this===e)return 0;var t=e,n=this,r=null,i=null;if(t instanceof Ne&&(r=t,t=r.ownerElement),n instanceof Ne&&(i=n,n=i.ownerElement,r&&t&&n===t))for(var a=0,o;o=n.attributes[a];a++){if(o===r)return P.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+P.DOCUMENT_POSITION_PRECEDING;if(o===i)return P.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+P.DOCUMENT_POSITION_FOLLOWING}if(!t||!n||n.ownerDocument!==t.ownerDocument)return P.DOCUMENT_POSITION_DISCONNECTED+P.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+(F(n.ownerDocument)>F(t.ownerDocument)?P.DOCUMENT_POSITION_FOLLOWING:P.DOCUMENT_POSITION_PRECEDING);if(i&&t===n)return P.DOCUMENT_POSITION_CONTAINS+P.DOCUMENT_POSITION_PRECEDING;if(r&&t===n)return P.DOCUMENT_POSITION_CONTAINED_BY+P.DOCUMENT_POSITION_FOLLOWING;for(var s=[],c=t.parentNode;c;){if(!i&&c===n)return P.DOCUMENT_POSITION_CONTAINED_BY+P.DOCUMENT_POSITION_FOLLOWING;s.push(c),c=c.parentNode}s.reverse();for(var l=[],u=n.parentNode;u;){if(!r&&u===t)return P.DOCUMENT_POSITION_CONTAINS+P.DOCUMENT_POSITION_PRECEDING;l.push(u),u=u.parentNode}l.reverse();var d=ie(s,l);for(var f in d.childNodes){var p=d.childNodes[f];if(p===n)return P.DOCUMENT_POSITION_FOLLOWING;if(p===t)return P.DOCUMENT_POSITION_PRECEDING;if(l.indexOf(p)>=0)return P.DOCUMENT_POSITION_FOLLOWING;if(s.indexOf(p)>=0)return P.DOCUMENT_POSITION_PRECEDING}return 0}};function pe(e){return e==`<`&&`<`||e==`>`&&`>`||e==`&`&&`&`||e==`"`&&`"`||`&#`+e.charCodeAt()+`;`}C(T,B),C(T,B.prototype),C(P,B),C(P,B.prototype);function me(e,t){he(e,null,{enter:function(e){return!t(e)||he.STOP}})}function he(e,t,n){for(var r=[{node:e,context:t,phase:he.ENTER}];r.length>0;){var i=r.pop();if(i.phase===he.ENTER){var a=n.enter(i.node,i.context);if(a===he.STOP)return he.STOP;if(r.push({node:i.node,context:a,phase:he.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)r.push({node:o,context:a,phase:he.ENTER}),o=o.previousSibling}else n.exit&&n.exit(i.node,i.context)}}he.STOP=Symbol(`walkDOM.STOP`),he.ENTER=0,he.EXIT=1;function ge(e,t){h(e);var n=t||{};this.ownerDocument=this,this.contentType=n.contentType||c.XML_APPLICATION,this.type=a(this.contentType)?`html`:`xml`}function _e(e,t,n){e&&e._inc++,n.namespaceURI===l.XMLNS&&(t._nsMap[n.prefix?n.localName:``]=n.value)}function ve(e,t,n,r){e&&e._inc++,n.namespaceURI===l.XMLNS&&delete t._nsMap[n.prefix?n.localName:``]}function ye(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n&&!n.nextSibling)r[r.length++]=n;else{for(var i=t.firstChild,a=0;i;)r[a++]=i,i=i.nextSibling;r.length=a,delete r[r.length]}}}function be(e,t){if(e!==t.parentNode)throw new f(f.NOT_FOUND_ERR,`child's parent is not parent`);var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,ye(e.ownerDocument,e),t.parentNode=null,t.previousSibling=null,t.nextSibling=null,t}function xe(e){return e&&(e.nodeType===B.DOCUMENT_NODE||e.nodeType===B.DOCUMENT_FRAGMENT_NODE||e.nodeType===B.ELEMENT_NODE)}function Se(e){return e&&(e.nodeType===B.CDATA_SECTION_NODE||e.nodeType===B.COMMENT_NODE||e.nodeType===B.DOCUMENT_FRAGMENT_NODE||e.nodeType===B.DOCUMENT_TYPE_NODE||e.nodeType===B.ELEMENT_NODE||e.nodeType===B.PROCESSING_INSTRUCTION_NODE||e.nodeType===B.TEXT_NODE)}function Ce(e){return e&&e.nodeType===B.DOCUMENT_TYPE_NODE}function we(e){return e&&e.nodeType===B.ELEMENT_NODE}function Te(e){return e&&e.nodeType===B.TEXT_NODE}function Ee(e,t){var r=e.childNodes||[];if(n(r,we)||Ce(t))return!1;var i=n(r,Ce);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function De(e,t){var r=e.childNodes||[];function i(e){return we(e)&&e!==t}if(n(r,i))return!1;var a=n(r,Ce);return!(t&&a&&r.indexOf(a)>r.indexOf(t))}function Oe(e,t,n){if(!xe(e))throw new f(f.HIERARCHY_REQUEST_ERR,`Unexpected parent node type `+e.nodeType);if(n&&n.parentNode!==e)throw new f(f.NOT_FOUND_ERR,`child not in parent`);if(!Se(t)||Ce(t)&&e.nodeType!==B.DOCUMENT_NODE)throw new f(f.HIERARCHY_REQUEST_ERR,`Unexpected node type `+t.nodeType+` for parent node type `+e.nodeType)}function ke(e,t,r){var i=e.childNodes||[],a=t.childNodes||[];if(t.nodeType===B.DOCUMENT_FRAGMENT_NODE){var o=a.filter(we);if(o.length>1||n(a,Te))throw new f(f.HIERARCHY_REQUEST_ERR,`More than one element or text in fragment`);if(o.length===1&&!Ee(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Element in fragment can not be inserted before doctype`)}if(we(t)&&!Ee(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one element can be added and only after doctype`);if(Ce(t)){if(n(i,Ce))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one doctype is allowed`);var s=n(i,we);if(r&&i.indexOf(s)1||n(a,Te))throw new f(f.HIERARCHY_REQUEST_ERR,`More than one element or text in fragment`);if(o.length===1&&!De(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Element in fragment can not be inserted before doctype`)}if(we(t)&&!De(e,r))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one element can be added and only after doctype`);if(Ce(t)){function e(e){return Ce(e)&&e!==r}if(n(i,e))throw new f(f.HIERARCHY_REQUEST_ERR,`Only one doctype is allowed`);var s=n(i,we);if(r&&i.indexOf(s)`)!==-1)throw new f(f.INVALID_CHARACTER_ERR,`data contains "]]>"`);var t=new Le(u);return t.ownerDocument=this,t.childNodes=new I,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new He(u);return n.ownerDocument=this,n.childNodes=new I,n.nodeName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){if(!m.QName_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`invalid character in name "`+e+`"`);return this.type===`html`&&(e=e.toLowerCase()),this._createAttribute(e)},_createAttribute:function(e){var t=new Ne(u);return t.ownerDocument=this,t.childNodes=new I,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!m.Name_exact.test(e))throw new f(f.INVALID_CHARACTER_ERR,`not a valid xml name "`+e+`"`);if(this.type===`html`)throw new f(`document is an html document`,p.NotSupportedError);var t=new Ve(u);return t.ownerDocument=this,t.childNodes=new I,t.nodeName=e,t},createElementNS:function(e,t){var n=S(e,t),r=new Me(u),i=r.attributes=new ae;return r.childNodes=new I,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=n[0],r.prefix=n[1],r.localName=n[2],i._ownerElement=r,r},createAttributeNS:function(e,t){var n=S(e,t),r=new Ne(u);return r.ownerDocument=this,r.childNodes=new I,r.nodeName=t,r.name=t,r.specified=!0,r.namespaceURI=n[0],r.prefix=n[1],r.localName=n[2],r}},w(ge,B);function Me(e){h(e),this._nsMap=Object.create(null)}Me.prototype={nodeType:E,attributes:null,getQualifiedName:function(){return this.prefix?this.prefix+`:`+this.localName:this.localName},_isInHTMLDocumentAndNamespace:function(){return this.ownerDocument.type===`html`&&this.namespaceURI===l.HTML},hasAttributes:function(){return!!(this.attributes&&this.attributes.length)},hasAttribute:function(e){return!!this.getAttributeNode(e)},getAttribute:function(e){var t=this.getAttributeNode(e);return t?t.value:null},getAttributeNode:function(e){return this._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase()),this.attributes.getNamedItem(e)},setAttribute:function(e,t){this._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase());var n=this.getAttributeNode(e);n?n.value=n.nodeValue=``+t:(n=this.ownerDocument._createAttribute(e),n.value=n.nodeValue=``+t,this.setAttributeNode(n))},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n?n.value:null},setAttributeNS:function(e,t,n){var r=S(e,t)[2],i=this.getAttributeNodeNS(e,r);i?i.value=i.nodeValue=``+n:(i=this.ownerDocument.createAttributeNS(e,t),i.value=i.nodeValue=``+n,this.setAttributeNode(i))},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByClassName:function(e){var t=y(e);return new L(this,function(n){var r=[];return t.length>0&&me(n,function(i){if(i!==n&&i.nodeType===E){var a=i.getAttribute(`class`);if(a){var o=e===a;if(!o){var s=y(a);o=t.every(b(s))}o&&r.push(i)}}}),r})},getElementsByTagName:function(e){var t=(this.nodeType===re?this:this.ownerDocument).type===`html`,n=e.toLowerCase();return new L(this,function(r){var i=[];return me(r,function(a){a!==r&&a.nodeType===E&&(e===`*`||a.getQualifiedName()===(t&&a.namespaceURI===l.HTML?n:e))&&i.push(a)}),i})},getElementsByTagNameNS:function(e,t){return new L(this,function(n){var r=[];return me(n,function(i){i!==n&&i.nodeType===E&&(e===`*`||i.namespaceURI===e)&&(t===`*`||i.localName==t)&&r.push(i)}),r})}},ge.prototype.getElementsByClassName=Me.prototype.getElementsByClassName,ge.prototype.getElementsByTagName=Me.prototype.getElementsByTagName,ge.prototype.getElementsByTagNameNS=Me.prototype.getElementsByTagNameNS,w(Me,B);function Ne(e){h(e),this.namespaceURI=null,this.prefix=null,this.ownerElement=null}Ne.prototype.nodeType=D,w(Ne,B);function Pe(e){h(e)}Pe.prototype={data:``,substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},deleteData:function(e,t){this.replaceData(e,t,``)},replaceData:function(e,t,n){var r=this.data.substring(0,e),i=this.data.substring(e+t);n=r+n+i,this.nodeValue=this.data=n,this.length=n.length}},w(Pe,B);function Fe(e){h(e)}Fe.prototype={nodeName:`#text`,nodeType:O,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}},w(Fe,Pe);function Ie(e){h(e)}Ie.prototype={nodeName:`#comment`,nodeType:A},w(Ie,Pe);function Le(e){h(e)}Le.prototype={nodeName:`#cdata-section`,nodeType:k},w(Le,Fe);function Re(e){h(e)}Re.prototype.nodeType=j,w(Re,B);function ze(e){h(e)}ze.prototype.nodeType=N,w(ze,B);function Be(e){h(e)}Be.prototype.nodeType=te,w(Be,B);function Ve(e){h(e)}Ve.prototype.nodeType=ee,w(Ve,B);function V(e){h(e)}V.prototype.nodeName=`#document-fragment`,V.prototype.nodeType=M,w(V,B);function He(e){h(e)}He.prototype.nodeType=ne,w(He,Pe);function Ue(){}Ue.prototype.serializeToString=function(e,t){return We.call(e,t)},B.prototype.toString=We;function We(e){var t=typeof e==`function`?{requireWellFormed:!1,splitCDATASections:!0,nodeFilter:e}:e==null?{requireWellFormed:!1,splitCDATASections:!0,nodeFilter:null}:{requireWellFormed:!!e.requireWellFormed,splitCDATASections:e.splitCDATASections!==!1,nodeFilter:e.nodeFilter||null},n=[],r=this.nodeType===re&&this.documentElement||this,i=r.prefix,a=r.namespaceURI;if(a&&i==null){var i=r.lookupPrefix(a);if(i==null)var o=[{namespace:a,prefix:null}]}return qe(this,n,o,t),n.join(``)}function Ge(e,t,n){var r=e.prefix||``,i=e.namespaceURI;if(!i||r===`xml`&&i===l.XML||i===l.XMLNS)return!1;for(var a=n.length;a--;){var o=n[a];if(o.prefix===r)return o.namespace!==i}return!0}function Ke(e,t,n,r){if(r&&!m.QName_exact.test(t))throw new f(`The attribute name "`+t+`" is not a valid XML QName`,p.InvalidStateError);e.push(` `,t,`="`,n.replace(/[<>&"\t\n\r]/g,pe),`"`)}function qe(e,t,n,r){n||=[];var i=r.nodeFilter,a=r.requireWellFormed,c=r.splitCDATASections,u=(e.nodeType===re?e:e.ownerDocument).type===`html`;he(e,{ns:n},{enter:function(e,n){var d=n.ns;if(i){if(e=i(e),e){if(typeof e==`string`)return t.push(e),null}else return null}switch(e.nodeType){case E:var h=e.attributes,g=h.length,_=e.tagName,v=_;if(!u&&!e.prefix&&e.namespaceURI){for(var y,b=0;b=0;x--){var S=d[x];if(S.prefix===``&&S.namespace===e.namespaceURI){y=S.namespace;break}}if(y!==e.namespaceURI)for(var x=d.length-1;x>=0;x--){var S=d[x];if(S.namespace===e.namespaceURI){S.prefix&&(v=S.prefix+`:`+_);break}}}if(a&&!m.QName_exact.test(v))throw new f(`The element name "`+v+`" is not a valid XML QName`,p.InvalidStateError);t.push(`<`,v);for(var C=d.slice(),w=0;w`),null;if(t.push(`>`),u&&o(_)){for(var I=e.firstChild;I;)I.data?t.push(I.data):qe(I,t,C.slice(),r),I=I.nextSibling;return t.push(``),null}return{ns:C,tag:v};case re:case M:if(a&&e.nodeType===re&&e.documentElement==null)throw new f(`The Document has no documentElement`,p.InvalidStateError);return{ns:d};case D:return Ke(t,e.name,e.value,a),null;case O:if(a&&m.InvalidChar.test(e.data))throw new f(`The Text node data contains characters outside the XML Char production`,p.InvalidStateError);return t.push(e.data.replace(/[<&>]/g,pe)),null;case k:if(a&&e.data.indexOf(`]]>`)!==-1)throw new f(`The CDATASection data contains "]]>"`,p.InvalidStateError);return c?t.push(m.CDATA_START,e.data.replace(/]]>/g,`]]]]>`),m.CDATA_END):t.push(m.CDATA_START,e.data,m.CDATA_END),null;case A:if(a){if(m.InvalidChar.test(e.data))throw new f(`The comment node data contains characters outside the XML Char production`,p.InvalidStateError);if(e.data.indexOf(`--`)!==-1||e.data[e.data.length-1]===`-`)throw new f(`The comment node data contains "--" or ends with "-"`,p.InvalidStateError)}return t.push(m.COMMENT_START,e.data,m.COMMENT_END),null;case j:var L=e.publicId,R=e.systemId;if(a){if(!m.Name_exact.test(e.name))throw new f(`The doctype name "`+e.name+`" is not a valid XML Name`,p.InvalidStateError);if(L&&!m.PubidLiteral_match.test(L))throw new f(`DocumentType publicId is not a valid PubidLiteral`,p.InvalidStateError);if(R&&R!==`.`&&!m.SystemLiteral_match.test(R))throw new f(`DocumentType systemId is not a valid SystemLiteral`,p.InvalidStateError);if(e.internalSubset&&e.internalSubset.indexOf(`]>`)!==-1)throw new f(`DocumentType internalSubset contains "]>"`,p.InvalidStateError)}return t.push(m.DOCTYPE_DECL_START,` `,e.name),L?(t.push(` `,m.PUBLIC,` `,L),R&&R!==`.`&&t.push(` `,R)):R&&R!==`.`&&t.push(` `,m.SYSTEM,` `,R),e.internalSubset&&t.push(` [`,e.internalSubset,`]`),t.push(`>`),null;case ne:if(a){if(!m.NCName_exact.test(e.target)||e.target.toLowerCase()===`xml`)throw new f(`The processing instruction target "`+e.target+`" is not a valid XML NCName or is reserved`,p.InvalidStateError);if(m.InvalidChar.test(e.data))throw new f(`The ProcessingInstruction data contains characters outside the XML Char production`,p.InvalidStateError);if(e.data.indexOf(`?>`)!==-1)throw new f(`The ProcessingInstruction data contains "?>"`,p.InvalidStateError)}return t.push(``),null;case ee:if(a&&!m.Name_exact.test(e.nodeName))throw new f(`The entity reference name "`+e.nodeName+`" is not a valid XML Name`,p.InvalidStateError);return t.push(`&`,e.nodeName,`;`),null;default:return t.push(`??`,e.nodeName),null}},exit:function(e,n){n&&n.tag&&t.push(``)}})}function Je(e,t,n){var r;return he(t,null,{enter:function(t,i){var a=t.cloneNode(!1);return a.ownerDocument=e,a.parentNode=null,i===null?r=a:i.appendChild(a),t.nodeType===D||n?a:null}}),r}function Ye(e,t,n){var r;return he(t,null,{enter:function(t,a){var o=new t.constructor(u);for(var s in t)if(i(t,s)){var c=t[s];typeof c!=`object`&&c!=o[s]&&(o[s]=c)}t.childNodes&&(o.childNodes=new I),o.ownerDocument=e;var l=n;switch(o.nodeType){case E:var d=t.attributes,f=o.attributes=new ae,p=d.length;f._ownerElement=o;for(var m=0;m{var t=Cg().freeze;e.XML_ENTITIES=t({amp:`&`,apos:`'`,gt:`>`,lt:`<`,quot:`"`}),e.HTML_ENTITIES=t({Aacute:`Á`,aacute:`á`,Abreve:`Ă`,abreve:`ă`,ac:`∾`,acd:`∿`,acE:`∾̳`,Acirc:`Â`,acirc:`â`,acute:`´`,Acy:`А`,acy:`а`,AElig:`Æ`,aelig:`æ`,af:`⁡`,Afr:`𝔄`,afr:`𝔞`,Agrave:`À`,agrave:`à`,alefsym:`ℵ`,aleph:`ℵ`,Alpha:`Α`,alpha:`α`,Amacr:`Ā`,amacr:`ā`,amalg:`⨿`,AMP:`&`,amp:`&`,And:`⩓`,and:`∧`,andand:`⩕`,andd:`⩜`,andslope:`⩘`,andv:`⩚`,ang:`∠`,ange:`⦤`,angle:`∠`,angmsd:`∡`,angmsdaa:`⦨`,angmsdab:`⦩`,angmsdac:`⦪`,angmsdad:`⦫`,angmsdae:`⦬`,angmsdaf:`⦭`,angmsdag:`⦮`,angmsdah:`⦯`,angrt:`∟`,angrtvb:`⊾`,angrtvbd:`⦝`,angsph:`∢`,angst:`Å`,angzarr:`⍼`,Aogon:`Ą`,aogon:`ą`,Aopf:`𝔸`,aopf:`𝕒`,ap:`≈`,apacir:`⩯`,apE:`⩰`,ape:`≊`,apid:`≋`,apos:`'`,ApplyFunction:`⁡`,approx:`≈`,approxeq:`≊`,Aring:`Å`,aring:`å`,Ascr:`𝒜`,ascr:`𝒶`,Assign:`≔`,ast:`*`,asymp:`≈`,asympeq:`≍`,Atilde:`Ã`,atilde:`ã`,Auml:`Ä`,auml:`ä`,awconint:`∳`,awint:`⨑`,backcong:`≌`,backepsilon:`϶`,backprime:`‵`,backsim:`∽`,backsimeq:`⋍`,Backslash:`∖`,Barv:`⫧`,barvee:`⊽`,Barwed:`⌆`,barwed:`⌅`,barwedge:`⌅`,bbrk:`⎵`,bbrktbrk:`⎶`,bcong:`≌`,Bcy:`Б`,bcy:`б`,bdquo:`„`,becaus:`∵`,Because:`∵`,because:`∵`,bemptyv:`⦰`,bepsi:`϶`,bernou:`ℬ`,Bernoullis:`ℬ`,Beta:`Β`,beta:`β`,beth:`ℶ`,between:`≬`,Bfr:`𝔅`,bfr:`𝔟`,bigcap:`⋂`,bigcirc:`◯`,bigcup:`⋃`,bigodot:`⨀`,bigoplus:`⨁`,bigotimes:`⨂`,bigsqcup:`⨆`,bigstar:`★`,bigtriangledown:`▽`,bigtriangleup:`△`,biguplus:`⨄`,bigvee:`⋁`,bigwedge:`⋀`,bkarow:`⤍`,blacklozenge:`⧫`,blacksquare:`▪`,blacktriangle:`▴`,blacktriangledown:`▾`,blacktriangleleft:`◂`,blacktriangleright:`▸`,blank:`␣`,blk12:`▒`,blk14:`░`,blk34:`▓`,block:`█`,bne:`=⃥`,bnequiv:`≡⃥`,bNot:`⫭`,bnot:`⌐`,Bopf:`𝔹`,bopf:`𝕓`,bot:`⊥`,bottom:`⊥`,bowtie:`⋈`,boxbox:`⧉`,boxDL:`╗`,boxDl:`╖`,boxdL:`╕`,boxdl:`┐`,boxDR:`╔`,boxDr:`╓`,boxdR:`╒`,boxdr:`┌`,boxH:`═`,boxh:`─`,boxHD:`╦`,boxHd:`╤`,boxhD:`╥`,boxhd:`┬`,boxHU:`╩`,boxHu:`╧`,boxhU:`╨`,boxhu:`┴`,boxminus:`⊟`,boxplus:`⊞`,boxtimes:`⊠`,boxUL:`╝`,boxUl:`╜`,boxuL:`╛`,boxul:`┘`,boxUR:`╚`,boxUr:`╙`,boxuR:`╘`,boxur:`└`,boxV:`║`,boxv:`│`,boxVH:`╬`,boxVh:`╫`,boxvH:`╪`,boxvh:`┼`,boxVL:`╣`,boxVl:`╢`,boxvL:`╡`,boxvl:`┤`,boxVR:`╠`,boxVr:`╟`,boxvR:`╞`,boxvr:`├`,bprime:`‵`,Breve:`˘`,breve:`˘`,brvbar:`¦`,Bscr:`ℬ`,bscr:`𝒷`,bsemi:`⁏`,bsim:`∽`,bsime:`⋍`,bsol:`\\`,bsolb:`⧅`,bsolhsub:`⟈`,bull:`•`,bullet:`•`,bump:`≎`,bumpE:`⪮`,bumpe:`≏`,Bumpeq:`≎`,bumpeq:`≏`,Cacute:`Ć`,cacute:`ć`,Cap:`⋒`,cap:`∩`,capand:`⩄`,capbrcup:`⩉`,capcap:`⩋`,capcup:`⩇`,capdot:`⩀`,CapitalDifferentialD:`ⅅ`,caps:`∩︀`,caret:`⁁`,caron:`ˇ`,Cayleys:`ℭ`,ccaps:`⩍`,Ccaron:`Č`,ccaron:`č`,Ccedil:`Ç`,ccedil:`ç`,Ccirc:`Ĉ`,ccirc:`ĉ`,Cconint:`∰`,ccups:`⩌`,ccupssm:`⩐`,Cdot:`Ċ`,cdot:`ċ`,cedil:`¸`,Cedilla:`¸`,cemptyv:`⦲`,cent:`¢`,CenterDot:`·`,centerdot:`·`,Cfr:`ℭ`,cfr:`𝔠`,CHcy:`Ч`,chcy:`ч`,check:`✓`,checkmark:`✓`,Chi:`Χ`,chi:`χ`,cir:`○`,circ:`ˆ`,circeq:`≗`,circlearrowleft:`↺`,circlearrowright:`↻`,circledast:`⊛`,circledcirc:`⊚`,circleddash:`⊝`,CircleDot:`⊙`,circledR:`®`,circledS:`Ⓢ`,CircleMinus:`⊖`,CirclePlus:`⊕`,CircleTimes:`⊗`,cirE:`⧃`,cire:`≗`,cirfnint:`⨐`,cirmid:`⫯`,cirscir:`⧂`,ClockwiseContourIntegral:`∲`,CloseCurlyDoubleQuote:`”`,CloseCurlyQuote:`’`,clubs:`♣`,clubsuit:`♣`,Colon:`∷`,colon:`:`,Colone:`⩴`,colone:`≔`,coloneq:`≔`,comma:`,`,commat:`@`,comp:`∁`,compfn:`∘`,complement:`∁`,complexes:`ℂ`,cong:`≅`,congdot:`⩭`,Congruent:`≡`,Conint:`∯`,conint:`∮`,ContourIntegral:`∮`,Copf:`ℂ`,copf:`𝕔`,coprod:`∐`,Coproduct:`∐`,COPY:`©`,copy:`©`,copysr:`℗`,CounterClockwiseContourIntegral:`∳`,crarr:`↵`,Cross:`⨯`,cross:`✗`,Cscr:`𝒞`,cscr:`𝒸`,csub:`⫏`,csube:`⫑`,csup:`⫐`,csupe:`⫒`,ctdot:`⋯`,cudarrl:`⤸`,cudarrr:`⤵`,cuepr:`⋞`,cuesc:`⋟`,cularr:`↶`,cularrp:`⤽`,Cup:`⋓`,cup:`∪`,cupbrcap:`⩈`,CupCap:`≍`,cupcap:`⩆`,cupcup:`⩊`,cupdot:`⊍`,cupor:`⩅`,cups:`∪︀`,curarr:`↷`,curarrm:`⤼`,curlyeqprec:`⋞`,curlyeqsucc:`⋟`,curlyvee:`⋎`,curlywedge:`⋏`,curren:`¤`,curvearrowleft:`↶`,curvearrowright:`↷`,cuvee:`⋎`,cuwed:`⋏`,cwconint:`∲`,cwint:`∱`,cylcty:`⌭`,Dagger:`‡`,dagger:`†`,daleth:`ℸ`,Darr:`↡`,dArr:`⇓`,darr:`↓`,dash:`‐`,Dashv:`⫤`,dashv:`⊣`,dbkarow:`⤏`,dblac:`˝`,Dcaron:`Ď`,dcaron:`ď`,Dcy:`Д`,dcy:`д`,DD:`ⅅ`,dd:`ⅆ`,ddagger:`‡`,ddarr:`⇊`,DDotrahd:`⤑`,ddotseq:`⩷`,deg:`°`,Del:`∇`,Delta:`Δ`,delta:`δ`,demptyv:`⦱`,dfisht:`⥿`,Dfr:`𝔇`,dfr:`𝔡`,dHar:`⥥`,dharl:`⇃`,dharr:`⇂`,DiacriticalAcute:`´`,DiacriticalDot:`˙`,DiacriticalDoubleAcute:`˝`,DiacriticalGrave:"`",DiacriticalTilde:`˜`,diam:`⋄`,Diamond:`⋄`,diamond:`⋄`,diamondsuit:`♦`,diams:`♦`,die:`¨`,DifferentialD:`ⅆ`,digamma:`ϝ`,disin:`⋲`,div:`÷`,divide:`÷`,divideontimes:`⋇`,divonx:`⋇`,DJcy:`Ђ`,djcy:`ђ`,dlcorn:`⌞`,dlcrop:`⌍`,dollar:`$`,Dopf:`𝔻`,dopf:`𝕕`,Dot:`¨`,dot:`˙`,DotDot:`⃜`,doteq:`≐`,doteqdot:`≑`,DotEqual:`≐`,dotminus:`∸`,dotplus:`∔`,dotsquare:`⊡`,doublebarwedge:`⌆`,DoubleContourIntegral:`∯`,DoubleDot:`¨`,DoubleDownArrow:`⇓`,DoubleLeftArrow:`⇐`,DoubleLeftRightArrow:`⇔`,DoubleLeftTee:`⫤`,DoubleLongLeftArrow:`⟸`,DoubleLongLeftRightArrow:`⟺`,DoubleLongRightArrow:`⟹`,DoubleRightArrow:`⇒`,DoubleRightTee:`⊨`,DoubleUpArrow:`⇑`,DoubleUpDownArrow:`⇕`,DoubleVerticalBar:`∥`,DownArrow:`↓`,Downarrow:`⇓`,downarrow:`↓`,DownArrowBar:`⤓`,DownArrowUpArrow:`⇵`,DownBreve:`̑`,downdownarrows:`⇊`,downharpoonleft:`⇃`,downharpoonright:`⇂`,DownLeftRightVector:`⥐`,DownLeftTeeVector:`⥞`,DownLeftVector:`↽`,DownLeftVectorBar:`⥖`,DownRightTeeVector:`⥟`,DownRightVector:`⇁`,DownRightVectorBar:`⥗`,DownTee:`⊤`,DownTeeArrow:`↧`,drbkarow:`⤐`,drcorn:`⌟`,drcrop:`⌌`,Dscr:`𝒟`,dscr:`𝒹`,DScy:`Ѕ`,dscy:`ѕ`,dsol:`⧶`,Dstrok:`Đ`,dstrok:`đ`,dtdot:`⋱`,dtri:`▿`,dtrif:`▾`,duarr:`⇵`,duhar:`⥯`,dwangle:`⦦`,DZcy:`Џ`,dzcy:`џ`,dzigrarr:`⟿`,Eacute:`É`,eacute:`é`,easter:`⩮`,Ecaron:`Ě`,ecaron:`ě`,ecir:`≖`,Ecirc:`Ê`,ecirc:`ê`,ecolon:`≕`,Ecy:`Э`,ecy:`э`,eDDot:`⩷`,Edot:`Ė`,eDot:`≑`,edot:`ė`,ee:`ⅇ`,efDot:`≒`,Efr:`𝔈`,efr:`𝔢`,eg:`⪚`,Egrave:`È`,egrave:`è`,egs:`⪖`,egsdot:`⪘`,el:`⪙`,Element:`∈`,elinters:`⏧`,ell:`ℓ`,els:`⪕`,elsdot:`⪗`,Emacr:`Ē`,emacr:`ē`,empty:`∅`,emptyset:`∅`,EmptySmallSquare:`◻`,emptyv:`∅`,EmptyVerySmallSquare:`▫`,emsp:` `,emsp13:` `,emsp14:` `,ENG:`Ŋ`,eng:`ŋ`,ensp:` `,Eogon:`Ę`,eogon:`ę`,Eopf:`𝔼`,eopf:`𝕖`,epar:`⋕`,eparsl:`⧣`,eplus:`⩱`,epsi:`ε`,Epsilon:`Ε`,epsilon:`ε`,epsiv:`ϵ`,eqcirc:`≖`,eqcolon:`≕`,eqsim:`≂`,eqslantgtr:`⪖`,eqslantless:`⪕`,Equal:`⩵`,equals:`=`,EqualTilde:`≂`,equest:`≟`,Equilibrium:`⇌`,equiv:`≡`,equivDD:`⩸`,eqvparsl:`⧥`,erarr:`⥱`,erDot:`≓`,Escr:`ℰ`,escr:`ℯ`,esdot:`≐`,Esim:`⩳`,esim:`≂`,Eta:`Η`,eta:`η`,ETH:`Ð`,eth:`ð`,Euml:`Ë`,euml:`ë`,euro:`€`,excl:`!`,exist:`∃`,Exists:`∃`,expectation:`ℰ`,ExponentialE:`ⅇ`,exponentiale:`ⅇ`,fallingdotseq:`≒`,Fcy:`Ф`,fcy:`ф`,female:`♀`,ffilig:`ffi`,fflig:`ff`,ffllig:`ffl`,Ffr:`𝔉`,ffr:`𝔣`,filig:`fi`,FilledSmallSquare:`◼`,FilledVerySmallSquare:`▪`,fjlig:`fj`,flat:`♭`,fllig:`fl`,fltns:`▱`,fnof:`ƒ`,Fopf:`𝔽`,fopf:`𝕗`,ForAll:`∀`,forall:`∀`,fork:`⋔`,forkv:`⫙`,Fouriertrf:`ℱ`,fpartint:`⨍`,frac12:`½`,frac13:`⅓`,frac14:`¼`,frac15:`⅕`,frac16:`⅙`,frac18:`⅛`,frac23:`⅔`,frac25:`⅖`,frac34:`¾`,frac35:`⅗`,frac38:`⅜`,frac45:`⅘`,frac56:`⅚`,frac58:`⅝`,frac78:`⅞`,frasl:`⁄`,frown:`⌢`,Fscr:`ℱ`,fscr:`𝒻`,gacute:`ǵ`,Gamma:`Γ`,gamma:`γ`,Gammad:`Ϝ`,gammad:`ϝ`,gap:`⪆`,Gbreve:`Ğ`,gbreve:`ğ`,Gcedil:`Ģ`,Gcirc:`Ĝ`,gcirc:`ĝ`,Gcy:`Г`,gcy:`г`,Gdot:`Ġ`,gdot:`ġ`,gE:`≧`,ge:`≥`,gEl:`⪌`,gel:`⋛`,geq:`≥`,geqq:`≧`,geqslant:`⩾`,ges:`⩾`,gescc:`⪩`,gesdot:`⪀`,gesdoto:`⪂`,gesdotol:`⪄`,gesl:`⋛︀`,gesles:`⪔`,Gfr:`𝔊`,gfr:`𝔤`,Gg:`⋙`,gg:`≫`,ggg:`⋙`,gimel:`ℷ`,GJcy:`Ѓ`,gjcy:`ѓ`,gl:`≷`,gla:`⪥`,glE:`⪒`,glj:`⪤`,gnap:`⪊`,gnapprox:`⪊`,gnE:`≩`,gne:`⪈`,gneq:`⪈`,gneqq:`≩`,gnsim:`⋧`,Gopf:`𝔾`,gopf:`𝕘`,grave:"`",GreaterEqual:`≥`,GreaterEqualLess:`⋛`,GreaterFullEqual:`≧`,GreaterGreater:`⪢`,GreaterLess:`≷`,GreaterSlantEqual:`⩾`,GreaterTilde:`≳`,Gscr:`𝒢`,gscr:`ℊ`,gsim:`≳`,gsime:`⪎`,gsiml:`⪐`,Gt:`≫`,GT:`>`,gt:`>`,gtcc:`⪧`,gtcir:`⩺`,gtdot:`⋗`,gtlPar:`⦕`,gtquest:`⩼`,gtrapprox:`⪆`,gtrarr:`⥸`,gtrdot:`⋗`,gtreqless:`⋛`,gtreqqless:`⪌`,gtrless:`≷`,gtrsim:`≳`,gvertneqq:`≩︀`,gvnE:`≩︀`,Hacek:`ˇ`,hairsp:` `,half:`½`,hamilt:`ℋ`,HARDcy:`Ъ`,hardcy:`ъ`,hArr:`⇔`,harr:`↔`,harrcir:`⥈`,harrw:`↭`,Hat:`^`,hbar:`ℏ`,Hcirc:`Ĥ`,hcirc:`ĥ`,hearts:`♥`,heartsuit:`♥`,hellip:`…`,hercon:`⊹`,Hfr:`ℌ`,hfr:`𝔥`,HilbertSpace:`ℋ`,hksearow:`⤥`,hkswarow:`⤦`,hoarr:`⇿`,homtht:`∻`,hookleftarrow:`↩`,hookrightarrow:`↪`,Hopf:`ℍ`,hopf:`𝕙`,horbar:`―`,HorizontalLine:`─`,Hscr:`ℋ`,hscr:`𝒽`,hslash:`ℏ`,Hstrok:`Ħ`,hstrok:`ħ`,HumpDownHump:`≎`,HumpEqual:`≏`,hybull:`⁃`,hyphen:`‐`,Iacute:`Í`,iacute:`í`,ic:`⁣`,Icirc:`Î`,icirc:`î`,Icy:`И`,icy:`и`,Idot:`İ`,IEcy:`Е`,iecy:`е`,iexcl:`¡`,iff:`⇔`,Ifr:`ℑ`,ifr:`𝔦`,Igrave:`Ì`,igrave:`ì`,ii:`ⅈ`,iiiint:`⨌`,iiint:`∭`,iinfin:`⧜`,iiota:`℩`,IJlig:`IJ`,ijlig:`ij`,Im:`ℑ`,Imacr:`Ī`,imacr:`ī`,image:`ℑ`,ImaginaryI:`ⅈ`,imagline:`ℐ`,imagpart:`ℑ`,imath:`ı`,imof:`⊷`,imped:`Ƶ`,Implies:`⇒`,in:`∈`,incare:`℅`,infin:`∞`,infintie:`⧝`,inodot:`ı`,Int:`∬`,int:`∫`,intcal:`⊺`,integers:`ℤ`,Integral:`∫`,intercal:`⊺`,Intersection:`⋂`,intlarhk:`⨗`,intprod:`⨼`,InvisibleComma:`⁣`,InvisibleTimes:`⁢`,IOcy:`Ё`,iocy:`ё`,Iogon:`Į`,iogon:`į`,Iopf:`𝕀`,iopf:`𝕚`,Iota:`Ι`,iota:`ι`,iprod:`⨼`,iquest:`¿`,Iscr:`ℐ`,iscr:`𝒾`,isin:`∈`,isindot:`⋵`,isinE:`⋹`,isins:`⋴`,isinsv:`⋳`,isinv:`∈`,it:`⁢`,Itilde:`Ĩ`,itilde:`ĩ`,Iukcy:`І`,iukcy:`і`,Iuml:`Ï`,iuml:`ï`,Jcirc:`Ĵ`,jcirc:`ĵ`,Jcy:`Й`,jcy:`й`,Jfr:`𝔍`,jfr:`𝔧`,jmath:`ȷ`,Jopf:`𝕁`,jopf:`𝕛`,Jscr:`𝒥`,jscr:`𝒿`,Jsercy:`Ј`,jsercy:`ј`,Jukcy:`Є`,jukcy:`є`,Kappa:`Κ`,kappa:`κ`,kappav:`ϰ`,Kcedil:`Ķ`,kcedil:`ķ`,Kcy:`К`,kcy:`к`,Kfr:`𝔎`,kfr:`𝔨`,kgreen:`ĸ`,KHcy:`Х`,khcy:`х`,KJcy:`Ќ`,kjcy:`ќ`,Kopf:`𝕂`,kopf:`𝕜`,Kscr:`𝒦`,kscr:`𝓀`,lAarr:`⇚`,Lacute:`Ĺ`,lacute:`ĺ`,laemptyv:`⦴`,lagran:`ℒ`,Lambda:`Λ`,lambda:`λ`,Lang:`⟪`,lang:`⟨`,langd:`⦑`,langle:`⟨`,lap:`⪅`,Laplacetrf:`ℒ`,laquo:`«`,Larr:`↞`,lArr:`⇐`,larr:`←`,larrb:`⇤`,larrbfs:`⤟`,larrfs:`⤝`,larrhk:`↩`,larrlp:`↫`,larrpl:`⤹`,larrsim:`⥳`,larrtl:`↢`,lat:`⪫`,lAtail:`⤛`,latail:`⤙`,late:`⪭`,lates:`⪭︀`,lBarr:`⤎`,lbarr:`⤌`,lbbrk:`❲`,lbrace:`{`,lbrack:`[`,lbrke:`⦋`,lbrksld:`⦏`,lbrkslu:`⦍`,Lcaron:`Ľ`,lcaron:`ľ`,Lcedil:`Ļ`,lcedil:`ļ`,lceil:`⌈`,lcub:`{`,Lcy:`Л`,lcy:`л`,ldca:`⤶`,ldquo:`“`,ldquor:`„`,ldrdhar:`⥧`,ldrushar:`⥋`,ldsh:`↲`,lE:`≦`,le:`≤`,LeftAngleBracket:`⟨`,LeftArrow:`←`,Leftarrow:`⇐`,leftarrow:`←`,LeftArrowBar:`⇤`,LeftArrowRightArrow:`⇆`,leftarrowtail:`↢`,LeftCeiling:`⌈`,LeftDoubleBracket:`⟦`,LeftDownTeeVector:`⥡`,LeftDownVector:`⇃`,LeftDownVectorBar:`⥙`,LeftFloor:`⌊`,leftharpoondown:`↽`,leftharpoonup:`↼`,leftleftarrows:`⇇`,LeftRightArrow:`↔`,Leftrightarrow:`⇔`,leftrightarrow:`↔`,leftrightarrows:`⇆`,leftrightharpoons:`⇋`,leftrightsquigarrow:`↭`,LeftRightVector:`⥎`,LeftTee:`⊣`,LeftTeeArrow:`↤`,LeftTeeVector:`⥚`,leftthreetimes:`⋋`,LeftTriangle:`⊲`,LeftTriangleBar:`⧏`,LeftTriangleEqual:`⊴`,LeftUpDownVector:`⥑`,LeftUpTeeVector:`⥠`,LeftUpVector:`↿`,LeftUpVectorBar:`⥘`,LeftVector:`↼`,LeftVectorBar:`⥒`,lEg:`⪋`,leg:`⋚`,leq:`≤`,leqq:`≦`,leqslant:`⩽`,les:`⩽`,lescc:`⪨`,lesdot:`⩿`,lesdoto:`⪁`,lesdotor:`⪃`,lesg:`⋚︀`,lesges:`⪓`,lessapprox:`⪅`,lessdot:`⋖`,lesseqgtr:`⋚`,lesseqqgtr:`⪋`,LessEqualGreater:`⋚`,LessFullEqual:`≦`,LessGreater:`≶`,lessgtr:`≶`,LessLess:`⪡`,lesssim:`≲`,LessSlantEqual:`⩽`,LessTilde:`≲`,lfisht:`⥼`,lfloor:`⌊`,Lfr:`𝔏`,lfr:`𝔩`,lg:`≶`,lgE:`⪑`,lHar:`⥢`,lhard:`↽`,lharu:`↼`,lharul:`⥪`,lhblk:`▄`,LJcy:`Љ`,ljcy:`љ`,Ll:`⋘`,ll:`≪`,llarr:`⇇`,llcorner:`⌞`,Lleftarrow:`⇚`,llhard:`⥫`,lltri:`◺`,Lmidot:`Ŀ`,lmidot:`ŀ`,lmoust:`⎰`,lmoustache:`⎰`,lnap:`⪉`,lnapprox:`⪉`,lnE:`≨`,lne:`⪇`,lneq:`⪇`,lneqq:`≨`,lnsim:`⋦`,loang:`⟬`,loarr:`⇽`,lobrk:`⟦`,LongLeftArrow:`⟵`,Longleftarrow:`⟸`,longleftarrow:`⟵`,LongLeftRightArrow:`⟷`,Longleftrightarrow:`⟺`,longleftrightarrow:`⟷`,longmapsto:`⟼`,LongRightArrow:`⟶`,Longrightarrow:`⟹`,longrightarrow:`⟶`,looparrowleft:`↫`,looparrowright:`↬`,lopar:`⦅`,Lopf:`𝕃`,lopf:`𝕝`,loplus:`⨭`,lotimes:`⨴`,lowast:`∗`,lowbar:`_`,LowerLeftArrow:`↙`,LowerRightArrow:`↘`,loz:`◊`,lozenge:`◊`,lozf:`⧫`,lpar:`(`,lparlt:`⦓`,lrarr:`⇆`,lrcorner:`⌟`,lrhar:`⇋`,lrhard:`⥭`,lrm:`‎`,lrtri:`⊿`,lsaquo:`‹`,Lscr:`ℒ`,lscr:`𝓁`,Lsh:`↰`,lsh:`↰`,lsim:`≲`,lsime:`⪍`,lsimg:`⪏`,lsqb:`[`,lsquo:`‘`,lsquor:`‚`,Lstrok:`Ł`,lstrok:`ł`,Lt:`≪`,LT:`<`,lt:`<`,ltcc:`⪦`,ltcir:`⩹`,ltdot:`⋖`,lthree:`⋋`,ltimes:`⋉`,ltlarr:`⥶`,ltquest:`⩻`,ltri:`◃`,ltrie:`⊴`,ltrif:`◂`,ltrPar:`⦖`,lurdshar:`⥊`,luruhar:`⥦`,lvertneqq:`≨︀`,lvnE:`≨︀`,macr:`¯`,male:`♂`,malt:`✠`,maltese:`✠`,Map:`⤅`,map:`↦`,mapsto:`↦`,mapstodown:`↧`,mapstoleft:`↤`,mapstoup:`↥`,marker:`▮`,mcomma:`⨩`,Mcy:`М`,mcy:`м`,mdash:`—`,mDDot:`∺`,measuredangle:`∡`,MediumSpace:` `,Mellintrf:`ℳ`,Mfr:`𝔐`,mfr:`𝔪`,mho:`℧`,micro:`µ`,mid:`∣`,midast:`*`,midcir:`⫰`,middot:`·`,minus:`−`,minusb:`⊟`,minusd:`∸`,minusdu:`⨪`,MinusPlus:`∓`,mlcp:`⫛`,mldr:`…`,mnplus:`∓`,models:`⊧`,Mopf:`𝕄`,mopf:`𝕞`,mp:`∓`,Mscr:`ℳ`,mscr:`𝓂`,mstpos:`∾`,Mu:`Μ`,mu:`μ`,multimap:`⊸`,mumap:`⊸`,nabla:`∇`,Nacute:`Ń`,nacute:`ń`,nang:`∠⃒`,nap:`≉`,napE:`⩰̸`,napid:`≋̸`,napos:`ʼn`,napprox:`≉`,natur:`♮`,natural:`♮`,naturals:`ℕ`,nbsp:`\xA0`,nbump:`≎̸`,nbumpe:`≏̸`,ncap:`⩃`,Ncaron:`Ň`,ncaron:`ň`,Ncedil:`Ņ`,ncedil:`ņ`,ncong:`≇`,ncongdot:`⩭̸`,ncup:`⩂`,Ncy:`Н`,ncy:`н`,ndash:`–`,ne:`≠`,nearhk:`⤤`,neArr:`⇗`,nearr:`↗`,nearrow:`↗`,nedot:`≐̸`,NegativeMediumSpace:`​`,NegativeThickSpace:`​`,NegativeThinSpace:`​`,NegativeVeryThinSpace:`​`,nequiv:`≢`,nesear:`⤨`,nesim:`≂̸`,NestedGreaterGreater:`≫`,NestedLessLess:`≪`,NewLine:` +`,nexist:`∄`,nexists:`∄`,Nfr:`𝔑`,nfr:`𝔫`,ngE:`≧̸`,nge:`≱`,ngeq:`≱`,ngeqq:`≧̸`,ngeqslant:`⩾̸`,nges:`⩾̸`,nGg:`⋙̸`,ngsim:`≵`,nGt:`≫⃒`,ngt:`≯`,ngtr:`≯`,nGtv:`≫̸`,nhArr:`⇎`,nharr:`↮`,nhpar:`⫲`,ni:`∋`,nis:`⋼`,nisd:`⋺`,niv:`∋`,NJcy:`Њ`,njcy:`њ`,nlArr:`⇍`,nlarr:`↚`,nldr:`‥`,nlE:`≦̸`,nle:`≰`,nLeftarrow:`⇍`,nleftarrow:`↚`,nLeftrightarrow:`⇎`,nleftrightarrow:`↮`,nleq:`≰`,nleqq:`≦̸`,nleqslant:`⩽̸`,nles:`⩽̸`,nless:`≮`,nLl:`⋘̸`,nlsim:`≴`,nLt:`≪⃒`,nlt:`≮`,nltri:`⋪`,nltrie:`⋬`,nLtv:`≪̸`,nmid:`∤`,NoBreak:`⁠`,NonBreakingSpace:`\xA0`,Nopf:`ℕ`,nopf:`𝕟`,Not:`⫬`,not:`¬`,NotCongruent:`≢`,NotCupCap:`≭`,NotDoubleVerticalBar:`∦`,NotElement:`∉`,NotEqual:`≠`,NotEqualTilde:`≂̸`,NotExists:`∄`,NotGreater:`≯`,NotGreaterEqual:`≱`,NotGreaterFullEqual:`≧̸`,NotGreaterGreater:`≫̸`,NotGreaterLess:`≹`,NotGreaterSlantEqual:`⩾̸`,NotGreaterTilde:`≵`,NotHumpDownHump:`≎̸`,NotHumpEqual:`≏̸`,notin:`∉`,notindot:`⋵̸`,notinE:`⋹̸`,notinva:`∉`,notinvb:`⋷`,notinvc:`⋶`,NotLeftTriangle:`⋪`,NotLeftTriangleBar:`⧏̸`,NotLeftTriangleEqual:`⋬`,NotLess:`≮`,NotLessEqual:`≰`,NotLessGreater:`≸`,NotLessLess:`≪̸`,NotLessSlantEqual:`⩽̸`,NotLessTilde:`≴`,NotNestedGreaterGreater:`⪢̸`,NotNestedLessLess:`⪡̸`,notni:`∌`,notniva:`∌`,notnivb:`⋾`,notnivc:`⋽`,NotPrecedes:`⊀`,NotPrecedesEqual:`⪯̸`,NotPrecedesSlantEqual:`⋠`,NotReverseElement:`∌`,NotRightTriangle:`⋫`,NotRightTriangleBar:`⧐̸`,NotRightTriangleEqual:`⋭`,NotSquareSubset:`⊏̸`,NotSquareSubsetEqual:`⋢`,NotSquareSuperset:`⊐̸`,NotSquareSupersetEqual:`⋣`,NotSubset:`⊂⃒`,NotSubsetEqual:`⊈`,NotSucceeds:`⊁`,NotSucceedsEqual:`⪰̸`,NotSucceedsSlantEqual:`⋡`,NotSucceedsTilde:`≿̸`,NotSuperset:`⊃⃒`,NotSupersetEqual:`⊉`,NotTilde:`≁`,NotTildeEqual:`≄`,NotTildeFullEqual:`≇`,NotTildeTilde:`≉`,NotVerticalBar:`∤`,npar:`∦`,nparallel:`∦`,nparsl:`⫽⃥`,npart:`∂̸`,npolint:`⨔`,npr:`⊀`,nprcue:`⋠`,npre:`⪯̸`,nprec:`⊀`,npreceq:`⪯̸`,nrArr:`⇏`,nrarr:`↛`,nrarrc:`⤳̸`,nrarrw:`↝̸`,nRightarrow:`⇏`,nrightarrow:`↛`,nrtri:`⋫`,nrtrie:`⋭`,nsc:`⊁`,nsccue:`⋡`,nsce:`⪰̸`,Nscr:`𝒩`,nscr:`𝓃`,nshortmid:`∤`,nshortparallel:`∦`,nsim:`≁`,nsime:`≄`,nsimeq:`≄`,nsmid:`∤`,nspar:`∦`,nsqsube:`⋢`,nsqsupe:`⋣`,nsub:`⊄`,nsubE:`⫅̸`,nsube:`⊈`,nsubset:`⊂⃒`,nsubseteq:`⊈`,nsubseteqq:`⫅̸`,nsucc:`⊁`,nsucceq:`⪰̸`,nsup:`⊅`,nsupE:`⫆̸`,nsupe:`⊉`,nsupset:`⊃⃒`,nsupseteq:`⊉`,nsupseteqq:`⫆̸`,ntgl:`≹`,Ntilde:`Ñ`,ntilde:`ñ`,ntlg:`≸`,ntriangleleft:`⋪`,ntrianglelefteq:`⋬`,ntriangleright:`⋫`,ntrianglerighteq:`⋭`,Nu:`Ν`,nu:`ν`,num:`#`,numero:`№`,numsp:` `,nvap:`≍⃒`,nVDash:`⊯`,nVdash:`⊮`,nvDash:`⊭`,nvdash:`⊬`,nvge:`≥⃒`,nvgt:`>⃒`,nvHarr:`⤄`,nvinfin:`⧞`,nvlArr:`⤂`,nvle:`≤⃒`,nvlt:`<⃒`,nvltrie:`⊴⃒`,nvrArr:`⤃`,nvrtrie:`⊵⃒`,nvsim:`∼⃒`,nwarhk:`⤣`,nwArr:`⇖`,nwarr:`↖`,nwarrow:`↖`,nwnear:`⤧`,Oacute:`Ó`,oacute:`ó`,oast:`⊛`,ocir:`⊚`,Ocirc:`Ô`,ocirc:`ô`,Ocy:`О`,ocy:`о`,odash:`⊝`,Odblac:`Ő`,odblac:`ő`,odiv:`⨸`,odot:`⊙`,odsold:`⦼`,OElig:`Œ`,oelig:`œ`,ofcir:`⦿`,Ofr:`𝔒`,ofr:`𝔬`,ogon:`˛`,Ograve:`Ò`,ograve:`ò`,ogt:`⧁`,ohbar:`⦵`,ohm:`Ω`,oint:`∮`,olarr:`↺`,olcir:`⦾`,olcross:`⦻`,oline:`‾`,olt:`⧀`,Omacr:`Ō`,omacr:`ō`,Omega:`Ω`,omega:`ω`,Omicron:`Ο`,omicron:`ο`,omid:`⦶`,ominus:`⊖`,Oopf:`𝕆`,oopf:`𝕠`,opar:`⦷`,OpenCurlyDoubleQuote:`“`,OpenCurlyQuote:`‘`,operp:`⦹`,oplus:`⊕`,Or:`⩔`,or:`∨`,orarr:`↻`,ord:`⩝`,order:`ℴ`,orderof:`ℴ`,ordf:`ª`,ordm:`º`,origof:`⊶`,oror:`⩖`,orslope:`⩗`,orv:`⩛`,oS:`Ⓢ`,Oscr:`𝒪`,oscr:`ℴ`,Oslash:`Ø`,oslash:`ø`,osol:`⊘`,Otilde:`Õ`,otilde:`õ`,Otimes:`⨷`,otimes:`⊗`,otimesas:`⨶`,Ouml:`Ö`,ouml:`ö`,ovbar:`⌽`,OverBar:`‾`,OverBrace:`⏞`,OverBracket:`⎴`,OverParenthesis:`⏜`,par:`∥`,para:`¶`,parallel:`∥`,parsim:`⫳`,parsl:`⫽`,part:`∂`,PartialD:`∂`,Pcy:`П`,pcy:`п`,percnt:`%`,period:`.`,permil:`‰`,perp:`⊥`,pertenk:`‱`,Pfr:`𝔓`,pfr:`𝔭`,Phi:`Φ`,phi:`φ`,phiv:`ϕ`,phmmat:`ℳ`,phone:`☎`,Pi:`Π`,pi:`π`,pitchfork:`⋔`,piv:`ϖ`,planck:`ℏ`,planckh:`ℎ`,plankv:`ℏ`,plus:`+`,plusacir:`⨣`,plusb:`⊞`,pluscir:`⨢`,plusdo:`∔`,plusdu:`⨥`,pluse:`⩲`,PlusMinus:`±`,plusmn:`±`,plussim:`⨦`,plustwo:`⨧`,pm:`±`,Poincareplane:`ℌ`,pointint:`⨕`,Popf:`ℙ`,popf:`𝕡`,pound:`£`,Pr:`⪻`,pr:`≺`,prap:`⪷`,prcue:`≼`,prE:`⪳`,pre:`⪯`,prec:`≺`,precapprox:`⪷`,preccurlyeq:`≼`,Precedes:`≺`,PrecedesEqual:`⪯`,PrecedesSlantEqual:`≼`,PrecedesTilde:`≾`,preceq:`⪯`,precnapprox:`⪹`,precneqq:`⪵`,precnsim:`⋨`,precsim:`≾`,Prime:`″`,prime:`′`,primes:`ℙ`,prnap:`⪹`,prnE:`⪵`,prnsim:`⋨`,prod:`∏`,Product:`∏`,profalar:`⌮`,profline:`⌒`,profsurf:`⌓`,prop:`∝`,Proportion:`∷`,Proportional:`∝`,propto:`∝`,prsim:`≾`,prurel:`⊰`,Pscr:`𝒫`,pscr:`𝓅`,Psi:`Ψ`,psi:`ψ`,puncsp:` `,Qfr:`𝔔`,qfr:`𝔮`,qint:`⨌`,Qopf:`ℚ`,qopf:`𝕢`,qprime:`⁗`,Qscr:`𝒬`,qscr:`𝓆`,quaternions:`ℍ`,quatint:`⨖`,quest:`?`,questeq:`≟`,QUOT:`"`,quot:`"`,rAarr:`⇛`,race:`∽̱`,Racute:`Ŕ`,racute:`ŕ`,radic:`√`,raemptyv:`⦳`,Rang:`⟫`,rang:`⟩`,rangd:`⦒`,range:`⦥`,rangle:`⟩`,raquo:`»`,Rarr:`↠`,rArr:`⇒`,rarr:`→`,rarrap:`⥵`,rarrb:`⇥`,rarrbfs:`⤠`,rarrc:`⤳`,rarrfs:`⤞`,rarrhk:`↪`,rarrlp:`↬`,rarrpl:`⥅`,rarrsim:`⥴`,Rarrtl:`⤖`,rarrtl:`↣`,rarrw:`↝`,rAtail:`⤜`,ratail:`⤚`,ratio:`∶`,rationals:`ℚ`,RBarr:`⤐`,rBarr:`⤏`,rbarr:`⤍`,rbbrk:`❳`,rbrace:`}`,rbrack:`]`,rbrke:`⦌`,rbrksld:`⦎`,rbrkslu:`⦐`,Rcaron:`Ř`,rcaron:`ř`,Rcedil:`Ŗ`,rcedil:`ŗ`,rceil:`⌉`,rcub:`}`,Rcy:`Р`,rcy:`р`,rdca:`⤷`,rdldhar:`⥩`,rdquo:`”`,rdquor:`”`,rdsh:`↳`,Re:`ℜ`,real:`ℜ`,realine:`ℛ`,realpart:`ℜ`,reals:`ℝ`,rect:`▭`,REG:`®`,reg:`®`,ReverseElement:`∋`,ReverseEquilibrium:`⇋`,ReverseUpEquilibrium:`⥯`,rfisht:`⥽`,rfloor:`⌋`,Rfr:`ℜ`,rfr:`𝔯`,rHar:`⥤`,rhard:`⇁`,rharu:`⇀`,rharul:`⥬`,Rho:`Ρ`,rho:`ρ`,rhov:`ϱ`,RightAngleBracket:`⟩`,RightArrow:`→`,Rightarrow:`⇒`,rightarrow:`→`,RightArrowBar:`⇥`,RightArrowLeftArrow:`⇄`,rightarrowtail:`↣`,RightCeiling:`⌉`,RightDoubleBracket:`⟧`,RightDownTeeVector:`⥝`,RightDownVector:`⇂`,RightDownVectorBar:`⥕`,RightFloor:`⌋`,rightharpoondown:`⇁`,rightharpoonup:`⇀`,rightleftarrows:`⇄`,rightleftharpoons:`⇌`,rightrightarrows:`⇉`,rightsquigarrow:`↝`,RightTee:`⊢`,RightTeeArrow:`↦`,RightTeeVector:`⥛`,rightthreetimes:`⋌`,RightTriangle:`⊳`,RightTriangleBar:`⧐`,RightTriangleEqual:`⊵`,RightUpDownVector:`⥏`,RightUpTeeVector:`⥜`,RightUpVector:`↾`,RightUpVectorBar:`⥔`,RightVector:`⇀`,RightVectorBar:`⥓`,ring:`˚`,risingdotseq:`≓`,rlarr:`⇄`,rlhar:`⇌`,rlm:`‏`,rmoust:`⎱`,rmoustache:`⎱`,rnmid:`⫮`,roang:`⟭`,roarr:`⇾`,robrk:`⟧`,ropar:`⦆`,Ropf:`ℝ`,ropf:`𝕣`,roplus:`⨮`,rotimes:`⨵`,RoundImplies:`⥰`,rpar:`)`,rpargt:`⦔`,rppolint:`⨒`,rrarr:`⇉`,Rrightarrow:`⇛`,rsaquo:`›`,Rscr:`ℛ`,rscr:`𝓇`,Rsh:`↱`,rsh:`↱`,rsqb:`]`,rsquo:`’`,rsquor:`’`,rthree:`⋌`,rtimes:`⋊`,rtri:`▹`,rtrie:`⊵`,rtrif:`▸`,rtriltri:`⧎`,RuleDelayed:`⧴`,ruluhar:`⥨`,rx:`℞`,Sacute:`Ś`,sacute:`ś`,sbquo:`‚`,Sc:`⪼`,sc:`≻`,scap:`⪸`,Scaron:`Š`,scaron:`š`,sccue:`≽`,scE:`⪴`,sce:`⪰`,Scedil:`Ş`,scedil:`ş`,Scirc:`Ŝ`,scirc:`ŝ`,scnap:`⪺`,scnE:`⪶`,scnsim:`⋩`,scpolint:`⨓`,scsim:`≿`,Scy:`С`,scy:`с`,sdot:`⋅`,sdotb:`⊡`,sdote:`⩦`,searhk:`⤥`,seArr:`⇘`,searr:`↘`,searrow:`↘`,sect:`§`,semi:`;`,seswar:`⤩`,setminus:`∖`,setmn:`∖`,sext:`✶`,Sfr:`𝔖`,sfr:`𝔰`,sfrown:`⌢`,sharp:`♯`,SHCHcy:`Щ`,shchcy:`щ`,SHcy:`Ш`,shcy:`ш`,ShortDownArrow:`↓`,ShortLeftArrow:`←`,shortmid:`∣`,shortparallel:`∥`,ShortRightArrow:`→`,ShortUpArrow:`↑`,shy:`­`,Sigma:`Σ`,sigma:`σ`,sigmaf:`ς`,sigmav:`ς`,sim:`∼`,simdot:`⩪`,sime:`≃`,simeq:`≃`,simg:`⪞`,simgE:`⪠`,siml:`⪝`,simlE:`⪟`,simne:`≆`,simplus:`⨤`,simrarr:`⥲`,slarr:`←`,SmallCircle:`∘`,smallsetminus:`∖`,smashp:`⨳`,smeparsl:`⧤`,smid:`∣`,smile:`⌣`,smt:`⪪`,smte:`⪬`,smtes:`⪬︀`,SOFTcy:`Ь`,softcy:`ь`,sol:`/`,solb:`⧄`,solbar:`⌿`,Sopf:`𝕊`,sopf:`𝕤`,spades:`♠`,spadesuit:`♠`,spar:`∥`,sqcap:`⊓`,sqcaps:`⊓︀`,sqcup:`⊔`,sqcups:`⊔︀`,Sqrt:`√`,sqsub:`⊏`,sqsube:`⊑`,sqsubset:`⊏`,sqsubseteq:`⊑`,sqsup:`⊐`,sqsupe:`⊒`,sqsupset:`⊐`,sqsupseteq:`⊒`,squ:`□`,Square:`□`,square:`□`,SquareIntersection:`⊓`,SquareSubset:`⊏`,SquareSubsetEqual:`⊑`,SquareSuperset:`⊐`,SquareSupersetEqual:`⊒`,SquareUnion:`⊔`,squarf:`▪`,squf:`▪`,srarr:`→`,Sscr:`𝒮`,sscr:`𝓈`,ssetmn:`∖`,ssmile:`⌣`,sstarf:`⋆`,Star:`⋆`,star:`☆`,starf:`★`,straightepsilon:`ϵ`,straightphi:`ϕ`,strns:`¯`,Sub:`⋐`,sub:`⊂`,subdot:`⪽`,subE:`⫅`,sube:`⊆`,subedot:`⫃`,submult:`⫁`,subnE:`⫋`,subne:`⊊`,subplus:`⪿`,subrarr:`⥹`,Subset:`⋐`,subset:`⊂`,subseteq:`⊆`,subseteqq:`⫅`,SubsetEqual:`⊆`,subsetneq:`⊊`,subsetneqq:`⫋`,subsim:`⫇`,subsub:`⫕`,subsup:`⫓`,succ:`≻`,succapprox:`⪸`,succcurlyeq:`≽`,Succeeds:`≻`,SucceedsEqual:`⪰`,SucceedsSlantEqual:`≽`,SucceedsTilde:`≿`,succeq:`⪰`,succnapprox:`⪺`,succneqq:`⪶`,succnsim:`⋩`,succsim:`≿`,SuchThat:`∋`,Sum:`∑`,sum:`∑`,sung:`♪`,Sup:`⋑`,sup:`⊃`,sup1:`¹`,sup2:`²`,sup3:`³`,supdot:`⪾`,supdsub:`⫘`,supE:`⫆`,supe:`⊇`,supedot:`⫄`,Superset:`⊃`,SupersetEqual:`⊇`,suphsol:`⟉`,suphsub:`⫗`,suplarr:`⥻`,supmult:`⫂`,supnE:`⫌`,supne:`⊋`,supplus:`⫀`,Supset:`⋑`,supset:`⊃`,supseteq:`⊇`,supseteqq:`⫆`,supsetneq:`⊋`,supsetneqq:`⫌`,supsim:`⫈`,supsub:`⫔`,supsup:`⫖`,swarhk:`⤦`,swArr:`⇙`,swarr:`↙`,swarrow:`↙`,swnwar:`⤪`,szlig:`ß`,Tab:` `,target:`⌖`,Tau:`Τ`,tau:`τ`,tbrk:`⎴`,Tcaron:`Ť`,tcaron:`ť`,Tcedil:`Ţ`,tcedil:`ţ`,Tcy:`Т`,tcy:`т`,tdot:`⃛`,telrec:`⌕`,Tfr:`𝔗`,tfr:`𝔱`,there4:`∴`,Therefore:`∴`,therefore:`∴`,Theta:`Θ`,theta:`θ`,thetasym:`ϑ`,thetav:`ϑ`,thickapprox:`≈`,thicksim:`∼`,ThickSpace:`  `,thinsp:` `,ThinSpace:` `,thkap:`≈`,thksim:`∼`,THORN:`Þ`,thorn:`þ`,Tilde:`∼`,tilde:`˜`,TildeEqual:`≃`,TildeFullEqual:`≅`,TildeTilde:`≈`,times:`×`,timesb:`⊠`,timesbar:`⨱`,timesd:`⨰`,tint:`∭`,toea:`⤨`,top:`⊤`,topbot:`⌶`,topcir:`⫱`,Topf:`𝕋`,topf:`𝕥`,topfork:`⫚`,tosa:`⤩`,tprime:`‴`,TRADE:`™`,trade:`™`,triangle:`▵`,triangledown:`▿`,triangleleft:`◃`,trianglelefteq:`⊴`,triangleq:`≜`,triangleright:`▹`,trianglerighteq:`⊵`,tridot:`◬`,trie:`≜`,triminus:`⨺`,TripleDot:`⃛`,triplus:`⨹`,trisb:`⧍`,tritime:`⨻`,trpezium:`⏢`,Tscr:`𝒯`,tscr:`𝓉`,TScy:`Ц`,tscy:`ц`,TSHcy:`Ћ`,tshcy:`ћ`,Tstrok:`Ŧ`,tstrok:`ŧ`,twixt:`≬`,twoheadleftarrow:`↞`,twoheadrightarrow:`↠`,Uacute:`Ú`,uacute:`ú`,Uarr:`↟`,uArr:`⇑`,uarr:`↑`,Uarrocir:`⥉`,Ubrcy:`Ў`,ubrcy:`ў`,Ubreve:`Ŭ`,ubreve:`ŭ`,Ucirc:`Û`,ucirc:`û`,Ucy:`У`,ucy:`у`,udarr:`⇅`,Udblac:`Ű`,udblac:`ű`,udhar:`⥮`,ufisht:`⥾`,Ufr:`𝔘`,ufr:`𝔲`,Ugrave:`Ù`,ugrave:`ù`,uHar:`⥣`,uharl:`↿`,uharr:`↾`,uhblk:`▀`,ulcorn:`⌜`,ulcorner:`⌜`,ulcrop:`⌏`,ultri:`◸`,Umacr:`Ū`,umacr:`ū`,uml:`¨`,UnderBar:`_`,UnderBrace:`⏟`,UnderBracket:`⎵`,UnderParenthesis:`⏝`,Union:`⋃`,UnionPlus:`⊎`,Uogon:`Ų`,uogon:`ų`,Uopf:`𝕌`,uopf:`𝕦`,UpArrow:`↑`,Uparrow:`⇑`,uparrow:`↑`,UpArrowBar:`⤒`,UpArrowDownArrow:`⇅`,UpDownArrow:`↕`,Updownarrow:`⇕`,updownarrow:`↕`,UpEquilibrium:`⥮`,upharpoonleft:`↿`,upharpoonright:`↾`,uplus:`⊎`,UpperLeftArrow:`↖`,UpperRightArrow:`↗`,Upsi:`ϒ`,upsi:`υ`,upsih:`ϒ`,Upsilon:`Υ`,upsilon:`υ`,UpTee:`⊥`,UpTeeArrow:`↥`,upuparrows:`⇈`,urcorn:`⌝`,urcorner:`⌝`,urcrop:`⌎`,Uring:`Ů`,uring:`ů`,urtri:`◹`,Uscr:`𝒰`,uscr:`𝓊`,utdot:`⋰`,Utilde:`Ũ`,utilde:`ũ`,utri:`▵`,utrif:`▴`,uuarr:`⇈`,Uuml:`Ü`,uuml:`ü`,uwangle:`⦧`,vangrt:`⦜`,varepsilon:`ϵ`,varkappa:`ϰ`,varnothing:`∅`,varphi:`ϕ`,varpi:`ϖ`,varpropto:`∝`,vArr:`⇕`,varr:`↕`,varrho:`ϱ`,varsigma:`ς`,varsubsetneq:`⊊︀`,varsubsetneqq:`⫋︀`,varsupsetneq:`⊋︀`,varsupsetneqq:`⫌︀`,vartheta:`ϑ`,vartriangleleft:`⊲`,vartriangleright:`⊳`,Vbar:`⫫`,vBar:`⫨`,vBarv:`⫩`,Vcy:`В`,vcy:`в`,VDash:`⊫`,Vdash:`⊩`,vDash:`⊨`,vdash:`⊢`,Vdashl:`⫦`,Vee:`⋁`,vee:`∨`,veebar:`⊻`,veeeq:`≚`,vellip:`⋮`,Verbar:`‖`,verbar:`|`,Vert:`‖`,vert:`|`,VerticalBar:`∣`,VerticalLine:`|`,VerticalSeparator:`❘`,VerticalTilde:`≀`,VeryThinSpace:` `,Vfr:`𝔙`,vfr:`𝔳`,vltri:`⊲`,vnsub:`⊂⃒`,vnsup:`⊃⃒`,Vopf:`𝕍`,vopf:`𝕧`,vprop:`∝`,vrtri:`⊳`,Vscr:`𝒱`,vscr:`𝓋`,vsubnE:`⫋︀`,vsubne:`⊊︀`,vsupnE:`⫌︀`,vsupne:`⊋︀`,Vvdash:`⊪`,vzigzag:`⦚`,Wcirc:`Ŵ`,wcirc:`ŵ`,wedbar:`⩟`,Wedge:`⋀`,wedge:`∧`,wedgeq:`≙`,weierp:`℘`,Wfr:`𝔚`,wfr:`𝔴`,Wopf:`𝕎`,wopf:`𝕨`,wp:`℘`,wr:`≀`,wreath:`≀`,Wscr:`𝒲`,wscr:`𝓌`,xcap:`⋂`,xcirc:`◯`,xcup:`⋃`,xdtri:`▽`,Xfr:`𝔛`,xfr:`𝔵`,xhArr:`⟺`,xharr:`⟷`,Xi:`Ξ`,xi:`ξ`,xlArr:`⟸`,xlarr:`⟵`,xmap:`⟼`,xnis:`⋻`,xodot:`⨀`,Xopf:`𝕏`,xopf:`𝕩`,xoplus:`⨁`,xotime:`⨂`,xrArr:`⟹`,xrarr:`⟶`,Xscr:`𝒳`,xscr:`𝓍`,xsqcup:`⨆`,xuplus:`⨄`,xutri:`△`,xvee:`⋁`,xwedge:`⋀`,Yacute:`Ý`,yacute:`ý`,YAcy:`Я`,yacy:`я`,Ycirc:`Ŷ`,ycirc:`ŷ`,Ycy:`Ы`,ycy:`ы`,yen:`¥`,Yfr:`𝔜`,yfr:`𝔶`,YIcy:`Ї`,yicy:`ї`,Yopf:`𝕐`,yopf:`𝕪`,Yscr:`𝒴`,yscr:`𝓎`,YUcy:`Ю`,yucy:`ю`,Yuml:`Ÿ`,yuml:`ÿ`,Zacute:`Ź`,zacute:`ź`,Zcaron:`Ž`,zcaron:`ž`,Zcy:`З`,zcy:`з`,Zdot:`Ż`,zdot:`ż`,zeetrf:`ℨ`,ZeroWidthSpace:`​`,Zeta:`Ζ`,zeta:`ζ`,Zfr:`ℨ`,zfr:`𝔷`,ZHcy:`Ж`,zhcy:`ж`,zigrarr:`⇝`,Zopf:`ℤ`,zopf:`𝕫`,Zscr:`𝒵`,zscr:`𝓏`,zwj:`‍`,zwnj:`‌`}),e.entityMap=e.HTML_ENTITIES})),Og=o((e=>{var t=Cg(),n=Tg(),r=wg(),i=t.isHTMLEscapableRawTextElement,a=t.isHTMLMimeType,o=t.isHTMLRawTextElement,s=t.hasOwn,c=t.NAMESPACE,l=r.ParseError,u=r.DOMException,d=0,f=1,p=2,m=3,h=4,g=5,_=6,v=7;function y(){}y.prototype={parse:function(e,t,n){var r=this.domBuilder;r.startDocument(),E(t,t=Object.create(null)),x(e,t,n,r,this.errorHandler),r.endDocument()}};var b=/&#?\w+;?/g;function x(e,r,i,o,c){var d=a(o.mimeType);e.indexOf(n.UNICODE_REPLACEMENT_CHARACTER)>=0&&c.warning(`Unicode replacement character detected, source encoding issues?`);function f(e){if(e>65535){e-=65536;var t=55296+(e>>10),n=56320+(e&1023);return String.fromCharCode(t,n)}return String.fromCharCode(e)}function p(e){var t=e[e.length-1]===`;`?e:e+`;`;if(!d&&t!==e)return c.error(`EntityRef: expecting ;`),e;var r=n.Reference.exec(t);if(!r||r[0].length!==t.length)return c.error(`entity not matching Reference production: `+e),e;var a=t.slice(1,-1);return s(i,a)?i[a]:a.charAt(0)===`#`?f(parseInt(a.substring(1).replace(`x`,`0x`))):(c.error(`entity not found:`+e),e)}function m(t){if(t>D){var n=e.substring(D,t).replace(b,p);v&&y(D),o.characters(n,0,t-D),D=t}}var h=0,g=0,_=/\r\n?|\n|$/g,v=o.locator;function y(t,n){for(;t>=g&&(n=_.exec(e));)h=g,g=n.index+n[0].length,v.lineNumber++;v.columnNumber=t-h+1}for(var x=[{currentNSMap:r}],E=[],D=0;;){try{var O=e.indexOf(`<`,D);if(O<0){if(!d&&E.length>0)return c.fatalError(`unclosed xml tag(s): `+E.join(`, `));if(!e.substring(D).match(/^\s*$/)){var ne=o.doc,A=ne.createTextNode(e.substring(D));if(ne.documentElement)return c.error(`Extra content at the end of the document`);ne.appendChild(A),o.currentElement=A}return}if(O>D){var re=e.substring(D,O);!d&&E.length===0&&(re=re.replace(new RegExp(n.S_OPT.source,`g`),``),re&&c.error(`Unexpected content outside root element: '`+re+`'`)),m(O)}switch(e.charAt(O+1)){case`/`:var j=e.indexOf(`>`,O+2),M=e.substring(O+2,j>0?j:void 0);if(!M)return c.fatalError(`end tag name missing`);var N=n.reg(`^`,n.QName_group,n.S_OPT,`$`),P=j>0&&N.exec(M);if(!P){var ie=j>0&&n.reg(`^`,n.QName_group).exec(M);if(d&&ie)c.warning(`end tag name contains invalid trailing characters: "`+M+`"`),P=ie;else if(ie&&new RegExp(N.source,N.flags+`m`).test(M))c.error(`end tag name is followed by a line break and trailing content: "`+M+`"`),P=ie;else return c.fatalError(`end tag name contains invalid characters: "`+M+`"`)}if(!o.currentElement&&!o.doc.documentElement)return;var F=E[E.length-1]||o.currentElement.tagName||o.doc.documentElement.tagName||``;if(F!==P[1]){var I=P[1].toLowerCase();if(!d||F.toLowerCase()!==I)return c.fatalError(`Opening and ending tag mismatch: "`+F+`" != "`+M+`"`)}var L=x.pop();E.pop();var R=L.localNSMap;if(o.endElement(L.uri,L.localName,F),R)for(var ae in R)s(R,ae)&&o.endPrefixMapping(ae);j++;break;case`?`:v&&y(O),j=ee(e,O,o,c);break;case`!`:v&&y(O),j=k(e,O,o,c,d);break;default:v&&y(O);var oe=new te,z=x[x.length-1].currentNSMap,j=C(e,O,oe,z,p,c,d),se=oe.length;if(oe.closed||(d&&t.isHTMLVoidElement(oe.tagName)?oe.closed=!0:E.push(oe.tagName)),v&&se){for(var ce=S(v,{}),le=0;leD?D=j:m(Math.max(O,D)+1)}}function S(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function C(e,t,n,r,i,a,o){function c(e,t,r){if(s(n.attributeNames,e))return a.fatalError(`Attribute `+e+` redefined`);if(!o&&t.indexOf(`<`)>=0)return a.fatalError(`Unescaped '<' not allowed in attributes values`);n.addValue(e,t.replace(/[\t\n\r]/g,` `).replace(b,i),r)}for(var l,u,y=++t,x=d;;){var S=e.charAt(y);if(x===d&&S===`<`)throw Error(`unexpected < in tag name: `+e.slice(t,y));switch(S){case`=`:if(x===f)l=e.slice(t,y),x=m;else if(x===p)x=m;else throw Error(`attribute equal must after attrName`);break;case`'`:case`"`:if(x===m||x===f){if(x===f&&(a.warning(`attribute value must after "="`),l=e.slice(t,y)),t=y+1,y=e.indexOf(S,t),y>0)u=e.slice(t,y),c(l,u,t-1),x=g;else throw Error(`attribute value no end '`+S+`' match`)}else if(x==h)u=e.slice(t,y),c(l,u,t),a.warning(`attribute "`+l+`" missed start quot(`+S+`)!!`),t=y+1,x=g;else throw Error(`attribute value must after "="`);break;case`/`:switch(x){case d:n.setTagName(e.slice(t,y));case g:case _:case v:x=v,n.closed=!0;case h:case f:break;case p:n.closed=!0;break;default:throw Error(`attribute invalid close char('/')`)}break;case``:return a.error(`unexpected end of input`),x==d&&n.setTagName(e.slice(t,y)),y;case`>`:switch(x){case d:n.setTagName(e.slice(t,y));case g:case _:case v:break;case h:case f:u=e.slice(t,y),u.slice(-1)===`/`&&(n.closed=!0,u=u.slice(0,-1));case p:x===p&&(u=l),x==h?(a.warning(`attribute "`+u+`" missed quot(")!`),c(l,u,t)):(o||a.warning(`attribute "`+u+`" missed value!! "`+u+`" instead!!`),c(u,u,t));break;case m:if(!o)return a.fatalError(`AttValue: ' or " expected`)}return y;case`€`:S=` `;default:if(S<=` `)switch(x){case d:n.setTagName(e.slice(t,y)),x=_;break;case f:l=e.slice(t,y),x=p;break;case h:var u=e.slice(t,y);a.warning(`attribute "`+u+`" missed quot(")!!`),c(l,u,t);case g:x=_}else switch(x){case p:o||a.warning(`attribute "`+l+`" missed value!! "`+l+`" instead2!!`),c(l,l,t),t=y,x=f;break;case g:a.warning(`attribute space is required"`+l+`"!!`);case _:x=f,t=y;break;case m:x=h,t=y;break;case v:throw Error(`elements closed character '/' and '>' must be connected to`)}}y++}}function w(e,t,n){for(var r=e.tagName,i=null,a=e.length;a--;){var o=e[a],l=o.qName,u=o.value,d=l.indexOf(`:`);if(d>0)var f=o.prefix=l.slice(0,d),p=l.slice(d+1),m=f===`xmlns`&&p;else p=l,f=null,m=l===`xmlns`&&``;o.localName=p,m!==!1&&(i??(i=Object.create(null),n=Object.create(n)),n[m]=i[m]=u,o.uri=c.XMLNS,t.startPrefixMapping(m,u))}for(var a=e.length;a--;)o=e[a],o.prefix&&(o.prefix===`xml`&&(o.uri=c.XML),o.prefix!==`xmlns`&&(o.uri=n[o.prefix]));var d=r.indexOf(`:`);d>0?(f=e.prefix=r.slice(0,d),p=e.localName=r.slice(d+1)):(f=null,p=e.localName=r);var h=e.uri=n[f||``];if(t.startElement(h,p,r,e),e.closed){if(t.endElement(h,p,r),i)for(f in i)s(i,f)&&t.endPrefixMapping(f)}else return e.currentNSMap=n,e.localNSMap=i,!0}function T(e,t,n,r,a){var s=i(n);if(s||o(n)){var c=RegExp(``,`ig`);c.lastIndex=t;var l=c.exec(e),u=l?l.index:-1;if(u<0)return t+1;var d=e.substring(t+1,u);return s&&(d=d.replace(b,r)),a.characters(d,0,d.length),u}return t+1}function E(e,t){for(var n in e)s(e,n)&&(t[n]=e[n])}function D(e,t){var r=t;function i(t){return t||=0,e.charAt(r+t)}function a(e){e||=1,r+=e}function o(){for(var t=0;r`?(o.skip(1),r.startDTD(l.name,l.publicId,l.systemId,l.internalSubset),r.endDTD(),o.getIndex()):i.fatalError(`doctype not terminated with > at position `+o.getIndex());default:return i.fatalError(`Not well-formed XML starting with "0)return i.fatalError(`processing instruction at position `+t+` is an xml declaration which is only at the start of the document`);if(!n.XMLDecl.test(e.substring(t)))return i.fatalError(`xml declaration is not well-formed`)}return r.processingInstruction(a[1],a[2]),t+a[0].length}function te(){this.attributeNames=Object.create(null)}te.prototype={setTagName:function(e){if(!n.QName_exact.test(e))throw Error(`invalid tagName:`+e);this.tagName=e},addValue:function(e,t,r){if(!n.QName_exact.test(e))throw Error(`invalid attribute:`+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}},e.XMLReader=y,e.parseUtils=D,e.parseDoctypeCommentOrCData=k})),kg=o((e=>{var t=Cg(),n=Eg(),r=wg(),i=Dg(),a=Og(),o=n.DOMImplementation,s=t.hasDefaultHTMLNamespace,c=t.isHTMLMimeType,l=t.isValidMimeType,u=t.MIME_TYPE,d=t.NAMESPACE,f=r.ParseError,p=a.XMLReader;function m(e){return e.replace(/\r[\n\u0085]/g,` +`).replace(/[\r\u0085\u2028\u2029]/g,` +`)}function h(e){if(e||={},e.locator===void 0&&(e.locator=!0),this.assign=e.assign||t.assign,this.domHandler=e.domHandler||g,this.onError=e.onError||e.errorHandler,e.errorHandler&&typeof e.errorHandler!=`function`)throw TypeError(`errorHandler object is no longer supported, switch to onError!`);e.errorHandler&&e.errorHandler(`warning`,"The `errorHandler` option has been deprecated, use `onError` instead!",this),this.normalizeLineEndings=e.normalizeLineEndings||m,this.locator=!!e.locator,this.xmlns=this.assign(Object.create(null),e.xmlns)}h.prototype.parseFromString=function(e,n){if(!l(n))throw TypeError(`DOMParser.parseFromString: the provided mimeType "`+n+`" is not valid.`);var r=this.assign(Object.create(null),this.xmlns),a=i.XML_ENTITIES,o=r[``]||null;s(n)?(a=i.HTML_ENTITIES,o=d.HTML):n===u.XML_SVG_IMAGE&&(o=d.SVG),r[``]=o,r.xml=r.xml||d.XML;var c=new this.domHandler({mimeType:n,defaultNamespace:o,onError:this.onError}),f=this.locator?{}:void 0;this.locator&&c.setDocumentLocator(f);var m=new p;return m.errorHandler=c,m.domBuilder=c,!t.isHTMLMimeType(n)&&typeof e!=`string`&&m.errorHandler.fatalError(`source is not a string`),m.parse(this.normalizeLineEndings(String(e)),r,a),c.doc.documentElement||m.errorHandler.fatalError(`missing root element`),c.doc};function g(e){var t=e||{};this.mimeType=t.mimeType||u.XML_APPLICATION,this.defaultNamespace=t.defaultNamespace||null,this.cdata=!1,this.currentElement=void 0,this.doc=void 0,this.locator=void 0,this.onError=t.onError}function _(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}g.prototype={startDocument:function(){var e=new o;this.doc=c(this.mimeType)?e.createHTMLDocument(!1):e.createDocument(this.defaultNamespace,``)},startElement:function(e,t,n,r){var i=this.doc,a=i.createElementNS(e,n||t),o=r.length;b(this,a),this.currentElement=a,this.locator&&_(this.locator,a);for(var s=0;s=t+n||t?new java.lang.String(e,t,n)+``:e}`endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl`.replace(/\w+/g,function(e){g.prototype[e]=function(){return null}});function b(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}function x(e){if(e===`error`)throw`onErrorStopParsing`}function S(){throw`onWarningStopParsing`}e.__DOMHandler=g,e.DOMParser=h,e.normalizeLineEndings=m,e.onErrorStopParsing=x,e.onWarningStopParsing=S}));o((e=>{var t=Cg();e.assign=t.assign,e.hasDefaultHTMLNamespace=t.hasDefaultHTMLNamespace,e.isHTMLMimeType=t.isHTMLMimeType,e.isValidMimeType=t.isValidMimeType,e.MIME_TYPE=t.MIME_TYPE,e.NAMESPACE=t.NAMESPACE;var n=wg();e.DOMException=n.DOMException,e.DOMExceptionName=n.DOMExceptionName,e.ExceptionCode=n.ExceptionCode,e.ParseError=n.ParseError;var r=Eg();e.Attr=r.Attr,e.CDATASection=r.CDATASection,e.CharacterData=r.CharacterData,e.Comment=r.Comment,e.Document=r.Document,e.DocumentFragment=r.DocumentFragment,e.DocumentType=r.DocumentType,e.DOMImplementation=r.DOMImplementation,e.Element=r.Element,e.Entity=r.Entity,e.EntityReference=r.EntityReference,e.LiveNodeList=r.LiveNodeList,e.NamedNodeMap=r.NamedNodeMap,e.Node=r.Node,e.NodeList=r.NodeList,e.Notation=r.Notation,e.ProcessingInstruction=r.ProcessingInstruction,e.Text=r.Text,e.XMLSerializer=r.XMLSerializer;var i=kg();e.DOMParser=i.DOMParser,e.normalizeLineEndings=i.normalizeLineEndings,e.onErrorStopParsing=i.onErrorStopParsing,e.onWarningStopParsing=i.onWarningStopParsing}))();var Ag=e=>typeof e==`string`?e:(e??[]).filter(e=>e.type===`text`).map(e=>e.text).join(` +`),jg=8192;function Mg(e){let t=e.findLast(e=>e.role===`assistant`&&e.usage?.input>0);return t?{inputTokens:t.usage.input,outputTokens:t.usage.output??0}:e.length?null:{inputTokens:0,outputTokens:0}}function Ng(e){if(!e)return`—/${jg.toLocaleString(`en-US`)} context`;let t=e.inputTokens+e.outputTokens,n=Math.max(0,jg-t);return`${t.toLocaleString(`en-US`)}/${jg.toLocaleString(`en-US`)} context · ${n.toLocaleString(`en-US`)} free`}var Pg=new Audio(new URL(``+new URL(`../cat-meow-v1.mp3`,import.meta.url).href,``+import.meta.url).href);Pg.preload=`auto`,Pg.volume=.65;function Fg(){try{Pg.currentTime=0,Pg.play().catch(()=>{})}catch{}}function Ig(e,t){let n=document.createElement(`canvas`).getContext(`2d`),r=document.createElement(`span`);r.style.cssText=`display:inline-block;width:0;height:0;padding:0;border:0;vertical-align:baseline`;let i=document.createElement(`div`);i.className=`empty-mascot`,i.hidden=!0,i.style.visibility=`hidden`;let a=document.createElement(`button`);a.type=`button`,a.className=`mascot-suggestion`;let o=document.createElement(`div`);o.className=`mascot-cat`,o.setAttribute(`aria-hidden`,`true`);let s=document.createElement(`img`);s.width=s.height=104,s.alt=``,s.draggable=!1;let c=document.createElement(`span`);c.className=`mascot-eyelids`,c.setAttribute(`aria-hidden`,`true`),o.append(s,c),i.append(a,o),e.append(i);let l=``,u=!1,d=!1,f=0,p=0,m=new Set,h=matchMedia(`(prefers-reduced-motion: reduce)`);function g(e,t,n){for(let e of m)e.id===n.id&&(e.cancel(),m.delete(e));let r=e.animate(t,n);m.add(r),r.onfinish=()=>m.delete(r)}function _(){clearTimeout(f),f=0,!(i.hidden||document.hidden||h.matches||!u)&&(d=!0,g(o,[{transform:`translate3d(0, 0, 0)`,easing:`ease-out`},{transform:`translate3d(0, -4px, 0)`,offset:.4,easing:`ease-in`},{transform:`translate3d(0, 0, 0)`}],{id:`mascot-bump`,duration:420}))}o.onclick=()=>{Fg(),_()},o.onpointerdown=e=>e.preventDefault(),o.onmousedown=e=>e.preventDefault();function v(){clearTimeout(f),clearTimeout(p),f=p=0;for(let e of m)e.cancel();m.clear()}function y(){if(i.hidden||document.hidden||h.matches||!u){v();return}!d&&!f&&(f=setTimeout(_,1800)),p||=setTimeout(()=>{p=0,g(c,[{opacity:0,easing:`steps(1, end)`},{opacity:1,offset:.15},{opacity:1,offset:.8,easing:`steps(1, end)`},{opacity:0}],{id:`mascot-blink`,duration:180}),y()},5e3+Math.random()*4e3)}function b(){i.hidden=!0,v()}async function x(){try{await s.decode()}catch{return}i.isConnected&&(u=!0,i.style.visibility=``,y())}return s.addEventListener(`load`,x),document.addEventListener(`visibilitychange`,y),h.addEventListener(`change`,y),a.onclick=()=>t(l),{hide:b,get statusInset(){return i.hidden?0:o.offsetWidth+20},update({screen:t,rows:c,viewportRows:u,contentRows:d,draft:f,hasSales:p,hasProducts:m}){if(!t||!c){b();return}let h=t.getBoundingClientRect(),g=e.getBoundingClientRect(),_=h.height/c,v=(u-d)*_-16;if(v<48){b();return}s.hasAttribute(`src`)||(s.src=new URL(``+new URL(`../empty-cat-v1.png`,import.meta.url).href,``+import.meta.url).href);let x=!f.trim()&&v>=180;a.hidden=!x,a.textContent=p&&m?`Ask me to calculate our total sales.`:`Ask me to explore your files.`,l=p&&m?`What's our total sales revenue?`:`Explore the workspace files and summarize what is here.`,a.setAttribute(`aria-label`,`Use suggested prompt: ${l}`);let S=Math.min(104,Math.floor(x?v-76:v));o.style.width=o.style.height=`${S}px`,i.hidden=!1;let C=h.top+(u+1.5)*_,w=t.querySelector(`.xterm-rows`)?.children[u+1]?.firstElementChild,T=devicePixelRatio||1;if(w&&n){let e=getComputedStyle(w);w.parentElement.append(r);let t=r.getBoundingClientRect().top;r.remove(),n.font=`${e.fontWeight} ${parseFloat(e.fontSize)*T}px ${e.fontFamily}`;let i=n.measureText(`─`);C=t-(i.actualBoundingBoxAscent-i.actualBoundingBoxDescent)/2/T}C=Math.floor(C*T+1e-4)/T;let E=Math.round(S*1156/1250*T)/T;i.style.top=`${C-g.top+S-E-i.getBoundingClientRect().height}px`,y()},dispose(){b(),s.removeEventListener(`load`,x),document.removeEventListener(`visibilitychange`,y),h.removeEventListener(`change`,y),i.remove()}}}var Lg=7e3,Rg=6500;function zg(e,t){let n=document.createElement(`div`);n.className=`terminal-paws`,n.hidden=!0,n.setAttribute(`aria-hidden`,`true`);for(let e=0;e<6;e++)n.append(document.createElement(`i`));e.append(n);let r=matchMedia(`(prefers-reduced-motion: reduce)`),i=new AbortController,a=!1,o=!1,s=!1,c=0,l=0,u=0,d=0;function f(){return a&&o&&!s&&!document.hidden&&document.hasFocus()&&!r.matches&&!document.querySelector(`dialog[open]`)}function p(){clearTimeout(l),l=0,n.hidden||=!0}function m(){if(!f()){clearTimeout(c),c=0;return}c&&u<=d||(clearTimeout(c),u=d,c=setTimeout(g,Math.max(0,d-Date.now())))}function h(){p(),d=Date.now()+Lg,m()}function g(){if(c=0,!f())return;if(Date.now()=220&&e.height>=180&&(Object.assign(n.style,{left:`${e.left}px`,top:`${e.top}px`,width:`${e.width}px`,height:`${e.height}px`}),n.style.setProperty(`--trail-shift`,`${Math.random()*10}%`),n.hidden=!1,l=setTimeout(p,Rg)),d=Date.now()+Rg+45e3+Math.random()*15e3,m()}let _={passive:!0,capture:!0,signal:i.signal};for(let e of[`pointerdown`,`keydown`,`input`,`wheel`,`scroll`,`touchstart`,`touchmove`,`focusin`])document.addEventListener(e,h,_);document.addEventListener(`visibilitychange`,h,_),window.addEventListener(`blur`,h,_),window.addEventListener(`focus`,h,_),r.addEventListener(`change`,h,_);let v=new MutationObserver(h);for(let e of document.querySelectorAll(`dialog`))v.observe(e,{attributes:!0,attributeFilter:[`open`]});let y=new IntersectionObserver(([e])=>{o=e.isIntersecting,h()});return y.observe(e),{reset:h,setEnabled(e){e!==a&&(a=e,h())},dispose(){s=!0,p(),clearTimeout(c),i.abort(),v.disconnect(),y.disconnect(),n.remove()}}}var Bg=e=>nd(String(e??``)).replace(/\r\n?/g,` +`).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,``),Vg=[{value:`/help`,label:`/help`,description:`Browser terminal commands`},{value:`/load`,label:`/load`,description:`Load MiniCPM on this device`},{value:`/new`,label:`/new`,description:`Start a new conversation; keep files`},{value:`/clear`,label:`/clear`,description:`Same as /new`}];function Hg(e,t){let n=new _s({fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13,lineHeight:1.3,theme:pg,cursorBlink:!1,scrollback:0,screenReaderMode:!0,allowProposedApi:!0});n.loadAddon(new yl);let r=document.createElement(`div`);r.className=`pi-terminal-mount`,e.append(r);let i=new bs;n.loadAddon(i),n.open(r);let a=new Sg(n),o=new Zf(a,!0,void 0,{copyOnSelect:!1,copySelection:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}},openUrl:e=>{/^https?:\/\//i.test(e)&&window.open(e,`_blank`,`noopener,noreferrer`)},scrollToEndIndicator:()=>Q.fg(`accent`,` ↓ Latest `),searchMatchStyle:e=>Q.bg(`selectedBg`,Q.fg(`text`,e)),searchCurrentMatchStyle:e=>Q.bg(`accent`,Q.fg(`userMessageBg`,Q.bold(e)))}),s=new nu({...eu,"app.interrupt":{defaultKeys:[`escape`,`ctrl+c`]},"app.exit":{defaultKeys:`ctrl+d`},"app.tools.expand":{defaultKeys:`ctrl+o`},"tui.editor.historyPrevious":{defaultKeys:`ctrl+p`},"tui.editor.historyNext":{defaultKeys:`ctrl+n`}});iu(s);let c=new lg(o,hg(),s,{paddingX:0}),l=new Nd,u=new rf(l,{follow:`end`,primary:!0,scrollbar:`auto`,scrollbarTrackStyle:e=>Q.fg(`borderMuted`,e),scrollbarThumbStyle:e=>Q.fg(`muted`,e)}),d=new bp(``,0,0),f=0,p=d.render.bind(d);d.render=e=>{let t=Math.min(f,Math.max(0,e-1)),n=p(e-t).map(e=>e+` `.repeat(t));return m.busy?[``,...n]:n},o.setLayoutRoot(new Jh([{component:u,basis:0,grow:1,minSize:0},{component:new Jh([d,c,{invalidate(){},render(e){let t=`/workspace · MiniCPM5-2B`,n=Ng(m.contextUsage),r=`${t} · ${n}`;return(r.length<=e-2?[r]:[t,n]).flatMap(t=>new bp(Q.fg(`dim`,t),1,0).render(e))}}]),basis:`auto`,shrink:0}])),o.setFocus(c);let m={loaded:!1,busy:!1,activity:``,contextUsage:Mg([])},h=[],g=[],_=!1,v=!1,y,b=!1,x=zg(e,()=>{let t=r.querySelector(`.xterm-screen`)?.getBoundingClientRect();if(!t||!n.rows)return;let i=e.getBoundingClientRect();return{left:t.left-i.left,top:t.top-i.top,width:t.width,height:t.height*u.viewportHeight/n.rows}}),S=Ig(e,e=>{m.busy||v||c.getText().trim()||(c.setText(e),n.focus(),o.requestRender())});function C(){x.setEnabled(b&&!m.busy&&!v&&!y);let e=r.querySelector(`.xterm-screen`);!b||g.some(e=>e.role===`user`)||m.busy||v?S.hide():S.update({screen:e,rows:n.rows,viewportRows:u.viewportHeight,contentRows:l.render(n.cols).length,draft:c.getText(),hasSales:h.includes(`sales.csv`),hasProducts:h.includes(`products.json`)||h.includes(`products.csv`)});let t=e?.getBoundingClientRect().width/n.cols,i=t>0?Math.ceil(S.statusInset/t):0;i!==f&&(f=i,o.requestRender())}let w=n.onRender(C),T=new Map,E=[],D=new Set,O=new Nd;O.addChild(new yp(Q.fg(`accent`,Q.bold(`π Pi`))+Q.fg(`muted`,` browser workspace`),1,1)),O.addChild(new yp(`Ask Pi to work with your files. + +/load load MiniCPM +/help show commands +!ls run a workspace command`,1,0)),O.addChild(new Kh(1));let k=new yp(Q.fg(`accent`,Q.bold(`π Pi`))+Q.fg(`muted`,` browser workspace`)+` +Ask Pi to work with your files.`,1,0),ee=O.render.bind(O);O.render=e=>n.rows<30?k.render(e):ee(e);function te(e,t=!1){E.push({at:g.length,component:new yp(Q.fg(t?`error`:`muted`,Bg(e)),1,1)}),re(),o.scrollToBottom()}function ne(e){e&&!D.has(e)&&(D.add(e),c.addToHistory(e))}function A(e,t){let n=new Nd;n.addChild(new Kh(1));let r=new Gh(1,1,e=>Q.bg(t?t.isError?`toolErrorBg`:`toolSuccessBg`:`toolPendingBg`,e)),i=Q.fg(`toolTitle`,Q.bold(Bg(e.name)))+` `+Q.fg(`accent`,Bg(e.arguments?.path??e.arguments?.command??``));r.addChild(new yp(i,0,0));let a=Bg(JSON.stringify(e.arguments,null,2)),o=Bg(t?Ag(t.content):`Running…`).replace(/\n+$/,``),s=o.split(` +`);return r.addChild(new yp(Q.fg(`toolOutput`,_?a+` + +`+o:s.slice(0,10).join(` +`)),0,0)),!_&&s.length>10&&r.addChild(new yp(Q.fg(`dim`,`… ${s.length-10} more lines · Ctrl+O to expand`),0,0)),n.addChild(r),n}function re(){l.clear(),l.addChild(O);let e=new Map(g.filter(e=>e.role===`toolResult`).map(e=>[e.toolCallId,e])),t=new Set;for(let n=0;n<=g.length;n++){for(let e of E)e.at===n&&l.addChild(e.component);let r=g[n];if(!r||r.role===`toolResult`)continue;let i=r.role+`:`+r.timestamp+`:`+n;t.add(i);let a=T.get(i);if(a||(a={component:r.role===`user`?new yg(Bg(Ag(r.content))):new xg(void 0,!0)},T.set(i,a)),r.role===`user`&&ne(Ag(r.content)),r.role===`assistant`&&a.message!==r){let e={...r,content:r.content.map(e=>e.type===`text`?{...e,text:Bg(e.text)}:e.type===`thinking`?{...e,thinking:Bg(e.thinking)}:e),errorMessage:r.errorMessage?Bg(r.errorMessage):void 0};a.component.setHiddenThinkingLabel(r.stopReason?`Thoughts · click to expand`:`Thinking…`),a.component.updateContent(e,!r.stopReason)}r.role===`user`&&(n>0||E.length)&&l.addChild(new Kh(1)),a.message=r,l.addChild(a.component);for(let n of Array.isArray(r.content)?r.content:[]){if(n.type!==`toolCall`)continue;let r=e.get(n.id),i=`tool:`+n.id;t.add(i);let a=JSON.stringify([n,r,_]),o=T.get(i);o?.signature!==a&&(o={signature:a,component:A(n,r)},T.set(i,o)),l.addChild(o.component)}}for(let e of T.keys())t.has(e)||T.delete(e);y&&(l.addChild(new Kh(1)),l.addChild(y),l.addChild(new yp(Q.fg(`muted`,`Queued · sends when the model is ready`),1,0))),C(),o.requestRender()}function j(){d.text=Q.fg(m.busy?`accent`:`muted`,Bg(m.activity||(m.busy?``:m.loaded?`Ready`:`Send a message to get started · /help`))),c.disableSubmit=m.busy||v,c.borderColor=e=>Q.fg(m.busy?`accent`:`borderMuted`,e),t.onInput?.(c.getText()),o.requestRender(),C()}async function M(e){if(!(!e.trim()||m.busy||v)){v=!0,j(),ne(e),o.scrollToBottom();try{let n=e.trim();if(n===`/help`)te(`/load Load MiniCPM on this device +/new Clear the conversation; keep workspace files +!cmd Run cmd with just-bash + +Enter: send · Shift+Enter: newline +↑/↓: edit/history · Ctrl+P/N: history +Esc or Ctrl+C: stop · Ctrl+O: expand tools +Ctrl+Shift+F: search transcript + +Pi’s original terminal UI and agent core run here. +Node CLI extensions, npm, Python and native binaries are unavailable.`);else if(n===`/load`)await t.load();else if(n===`/new`||n===`/clear`)await t.newChat(),E.length=0,re();else if(n.startsWith(`/`))throw Error(`Unknown browser command. Type /help for available commands.`);else if(n.startsWith(`!`)){let e=n.slice(1).trim();if(!e)throw Error(`Enter a shell command after !.`);let r=await t.shell(e);te(`$ ${e}\n${r.stdout}${r.stderr}\n[exit ${r.exitCode}]`,r.exitCode!==0)}else await t.prompt(e)}catch(t){t.name!==`AbortError`&&te(t.message,!0),c.getText()||c.setText(e)}finally{v=!1,j()}}}c.onSubmit=e=>{M(e)},c.onChange=()=>{t.onInput?.(c.getText()),o.requestRender()},c.onEscape=()=>{m.busy&&t.stop().catch(e=>te(e.message,!0))},c.onCtrlD=()=>te(`This terminal lives in your browser. Close the tab to leave.`),c.onAction(`app.tools.expand`,()=>{_=!_,re()}),c.setAutocompleteProvider({getSuggestions(e,t,n){let r=e[t].slice(0,n),i=r.match(/\S*$/)?.[0]??``;if(!i)return null;let a=(r.startsWith(`/`)?Vg:h.map(e=>({value:e,label:e,description:`workspace file`}))).filter(e=>e.value.startsWith(i)&&e.value!==i);return a.length?{items:a,prefix:i}:null},applyCompletion(e,t,n,r,i){let a=[...e];return a[t]=e[t].slice(0,n-i.length)+r.value+` `+e[t].slice(n),{lines:a,cursorLine:t,cursorCol:n-i.length+r.value.length+1}}}),n.attachCustomKeyEventHandler(e=>e.type!==`keydown`||e.isComposing?!0:(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`v`?!1:e.ctrlKey&&e.shiftKey&&e.code===`KeyF`?(e.preventDefault(),a.inputData(`\x1B[102;6u`),!1):e.key===`Enter`&&e.shiftKey?(e.preventDefault(),a.inputData(`\x1B\r`),!1):(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`c`&&(n.hasSelection()||o.hasActiveSelection())?(o.hasActiveSelection()&&(e.preventDefault(),o.copyActiveSelectionToClipboard()),!1):!0);let N;e.addEventListener(`touchstart`,e=>{e.touches.length===1&&(N=e.touches[0].clientY)},{passive:!0}),e.addEventListener(`touchmove`,e=>{if(N===void 0||e.touches.length!==1)return;let t=e.touches[0].clientY,n=Math.trunc((N-t)/18);n&&(o.scrollBy(n),N=t,e.preventDefault())},{passive:!1}),e.addEventListener(`touchend`,()=>{N=void 0},{passive:!0});function P(){x.reset(),e.clientWidth>0&&e.clientHeight>0&&(i.fit(),o.requestRender())}let ie=new ResizeObserver(P);return ie.observe(e),P(),o.start(),re(),j(),document.fonts.ready.then(P),n.textarea.setAttribute(`aria-label`,`Message Pi`),n.textarea.setAttribute(`autocapitalize`,`off`),n.textarea.setAttribute(`spellcheck`,`false`),{setMessages(e,{reset:t=!1}={}){b=!0,g=e,t&&(E.length=0,T.clear()),re()},setFiles(e){h=Object.keys(e).map(e=>e.replace(/^\/workspace\//,``)),C()},setState(e){m={...m,...e},j()},setQueuedPrompt(e){(e||y)&&(y=e?new yg(Bg(e)):void 0,re(),o.scrollToBottom())},submit(){let e=c.getExpandedText();if(!c.disableSubmit&&e.trim())return c.setText(``),M(e)},focus(){n.focus()},newline(){a.inputData(`\x1B\r`),n.focus()},get text(){return c.getExpandedText()},get cols(){return n.cols},get rows(){return n.rows},get viewportTop(){return o.viewportTop},readScreen(){return Array.from({length:n.buffer.active.length},(e,t)=>n.buffer.active.getLine(t)?.translateToString(!0)??``).join(` +`)},readDocument(){return u.render(n.cols).map(e=>nd(e).trimEnd())},readCells(){return Array.from({length:n.rows},(e,t)=>Array.from({length:n.cols},(e,r)=>{let i=n.buffer.active.getLine(t)?.getCell(r);return i?{text:i.getChars(),width:i.getWidth(),fg:i.isFgDefault()?pg.foreground:i.getFgColor(),bg:i.isBgDefault()?pg.background:i.getBgColor()}:null}))},dispose(){ie.disconnect(),w.dispose(),S.dispose(),x.dispose(),o.stop({preserveScreen:!0}),n.dispose()}}}function Ug(e,{onClose:t}){let n=t=>e.querySelector(t),r=n(`#model-confirm`),i=n(`#model-cancel`),a=n(`#model-error`),o=n(`.setup-cat img`),s=o.parentElement,c=n(`.setup-cat-tail`),l=matchMedia(`(prefers-reduced-motion: reduce)`),u;function d(){u?.cancel(),u=void 0}s.onpointerdown=e=>e.preventDefault(),s.onmousedown=e=>e.preventDefault(),s.onclick=()=>{if(Fg(),!e.open||document.hidden||l.matches||!s.classList.contains(`is-ready`))return;let t=getComputedStyle(c).transform;d();let n=c.getAnimations().find(e=>e.animationName===`setup-tail-swish`);n&&(n.currentTime=0),u=c.animate([{transform:t},{transform:`rotate(-7deg)`,offset:.3},{transform:`rotate(4deg)`,offset:.6},{transform:`rotate(-1deg)`,offset:.82},{transform:`rotate(0deg)`}],{id:`cat-tail-reaction`,duration:1200,easing:`ease-in-out`}),u.onfinish=()=>{u=void 0}},e.addEventListener(`close`,d),o.decode().then(()=>{o.parentElement.style.setProperty(`--cat-sprite`,`url("${o.currentSrc||o.src}")`),o.parentElement.classList.add(`is-ready`)}).catch(()=>{});let f=()=>{e.style.setProperty(`--cat-play-state`,document.hidden?`paused`:`running`),(document.hidden||l.matches)&&d()};document.addEventListener(`visibilitychange`,f),l.addEventListener(`change`,f),f();let p;function m(n){if(!p)return;d();let r=p;p=void 0,e.close(),t(),r(n)}return i.onclick=()=>m(!1),e.addEventListener(`cancel`,e=>{e.preventDefault(),m(!1)}),r.onclick=()=>m(!0),{request(t,{errorMessage:i}={}){if(p)throw Error(`Finish the current model setup before sending another message.`);r.textContent=i?`Try again`:`Load model & send`,n(`#model-title`).textContent=i?`Load model`:`Download model weights`,n(`#model-preview`).textContent=t,a.textContent=i??``,a.hidden=!i;let o=document.querySelector(`#open-tab`);n(`#model-open-tab`).hidden=!i||o.hidden,n(`#model-open-tab`).href=o.href;let s=new Promise(e=>{p=e});return e.showModal(),n(`.setup-body`).scrollTop=0,r.focus(),s}}}var Wg=c(o(((e,t)=>{var n=function(e){var t=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,n=0,r={},i={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(t){return t instanceof a?new a(t.type,e(t.content),t.alias):Array.isArray(t)?t.map(e):t.replace(/&/g,`&`).replace(/`u`)return null;if(document.currentScript&&document.currentScript.tagName===`SCRIPT`)return document.currentScript;try{throw Error()}catch(r){var e=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack)||[])[1];if(e){var t=document.getElementsByTagName(`script`);for(var n in t)if(t[n].src==e)return t[n]}return null}},isActive:function(e,t,n){for(var r=`no-`+t;e;){var i=e.classList;if(i.contains(t))return!0;if(i.contains(r))return!1;e=e.parentElement}return!!n}},languages:{plain:r,plaintext:r,text:r,txt:r,extend:function(e,t){var n=i.util.clone(i.languages[e]);for(var r in t)n[r]=t[r];return n},insertBefore:function(e,t,n,r){r||=i.languages;var a=r[e],o={};for(var s in a)if(a.hasOwnProperty(s)){if(s==t)for(var c in n)n.hasOwnProperty(c)&&(o[c]=n[c]);n.hasOwnProperty(s)||(o[s]=a[s])}var l=r[e];return r[e]=o,i.languages.DFS(i.languages,function(t,n){n===l&&t!=e&&(this[t]=o)}),o},DFS:function e(t,n,r,a){a||={};var o=i.util.objId;for(var s in t)if(t.hasOwnProperty(s)){n.call(t,s,t[s],r||s);var c=t[s],l=i.util.type(c);l===`Object`&&!a[o(c)]?(a[o(c)]=!0,e(c,n,null,a)):l===`Array`&&!a[o(c)]&&(a[o(c)]=!0,e(c,n,s,a))}}},plugins:{},highlightAll:function(e,t){i.highlightAllUnder(document,e,t)},highlightAllUnder:function(e,t,n){var r={callback:n,container:e,selector:`code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code`};i.hooks.run(`before-highlightall`,r),r.elements=Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)),i.hooks.run(`before-all-elements-highlight`,r);for(var a=0,o;o=r.elements[a++];)i.highlightElement(o,t===!0,r.callback)},highlightElement:function(t,n,r){var a=i.util.getLanguage(t),o=i.languages[a];i.util.setLanguage(t,a);var s=t.parentElement;s&&s.nodeName.toLowerCase()===`pre`&&i.util.setLanguage(s,a);var c={element:t,language:a,grammar:o,code:t.textContent};function l(e){c.highlightedCode=e,i.hooks.run(`before-insert`,c),c.element.innerHTML=c.highlightedCode,i.hooks.run(`after-highlight`,c),i.hooks.run(`complete`,c),r&&r.call(c.element)}if(i.hooks.run(`before-sanity-check`,c),s=c.element.parentElement,s&&s.nodeName.toLowerCase()===`pre`&&!s.hasAttribute(`tabindex`)&&s.setAttribute(`tabindex`,`0`),!c.code){i.hooks.run(`complete`,c),r&&r.call(c.element);return}if(i.hooks.run(`before-highlight`,c),!c.grammar){l(i.util.encode(c.code));return}if(n&&e.Worker){var u=new Worker(i.filename);u.onmessage=function(e){l(e.data)},u.postMessage(JSON.stringify({language:c.language,code:c.code,immediateClose:!0}))}else l(i.highlight(c.code,c.grammar,c.language))},highlight:function(e,t,n){var r={code:e,grammar:t,language:n};if(i.hooks.run(`before-tokenize`,r),!r.grammar)throw Error(`The language "`+r.language+`" has no grammar.`);return r.tokens=i.tokenize(r.code,r.grammar),i.hooks.run(`after-tokenize`,r),a.stringify(i.util.encode(r.tokens),r.language)},tokenize:function(e,t){var n=t.rest;if(n){for(var r in n)t[r]=n[r];delete t.rest}var i=new c;return l(i,i.head,e),s(e,i,t,i.head,0),d(i)},hooks:{all:{},add:function(e,t){var n=i.hooks.all;n[e]=n[e]||[],n[e].push(t)},run:function(e,t){var n=i.hooks.all[e];if(n&&n.length)for(var r=0,a;a=n[r++];)a(t)}},Token:a};e.Prism=i;function a(e,t,n,r){this.type=e,this.content=t,this.alias=n,this.length=(r||``).length|0}a.stringify=function e(t,n){if(typeof t==`string`)return t;if(Array.isArray(t)){var r=``;return t.forEach(function(t){r+=e(t,n)}),r}var a={type:t.type,content:e(t.content,n),tag:`span`,classes:[`token`,t.type],attributes:{},language:n},o=t.alias;o&&(Array.isArray(o)?Array.prototype.push.apply(a.classes,o):a.classes.push(o)),i.hooks.run(`wrap`,a);var s=``;for(var c in a.attributes)s+=` `+c+`="`+(a.attributes[c]||``).replace(/"/g,`"`)+`"`;return`<`+a.tag+` class="`+a.classes.join(` `)+`"`+s+`>`+a.content+``};function o(e,t,n,r){e.lastIndex=t;var i=e.exec(n);if(i&&r&&i[1]){var a=i[1].length;i.index+=a,i[0]=i[0].slice(a)}return i}function s(e,t,n,r,c,d){for(var f in n)if(n.hasOwnProperty(f)&&n[f]){var p=n[f];p=Array.isArray(p)?p:[p];for(var m=0;m=d.reach);C+=S.value.length,S=S.next){var w=S.value;if(t.length>e.length)return;if(!(w instanceof a)){var T=1,E;if(v){if(E=o(x,C,e,_),!E||E.index>=e.length)break;var D=E.index,O=E.index+E[0].length,k=C;for(k+=S.value.length;D>=k;)S=S.next,k+=S.value.length;if(k-=S.value.length,C=k,S.value instanceof a)continue;for(var ee=S;ee!==t.tail&&(kd.reach&&(d.reach=re);var j=S.prev;ne&&(j=l(t,j,ne),C+=ne.length),u(t,j,T);var M=new a(f,g?i.tokenize(te,g):te,y,te);if(S=l(t,j,M),A&&l(t,S,A),T>1){var N={cause:f+`,`+m,reach:re};s(e,t,n,S.prev,C,N),d&&N.reach>d.reach&&(d.reach=N.reach)}}}}}}function c(){var e={value:null,prev:null,next:null},t={value:null,prev:e,next:null};e.next=t,this.head=e,this.tail=t,this.length=0}function l(e,t,n){var r=t.next,i={value:n,prev:t,next:r};return t.next=i,r.prev=i,e.length++,i}function u(e,t,n){for(var r=t.next,i=0;i>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp(`(\\{)`+t),lookbehind:!0,alias:`constant`}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};e.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:`important`},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:`function`},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:`function`}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:`variable`,lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp(`(^|[\\s;|&]|[<>]\\()`+t),lookbehind:!0,alias:`constant`}},alias:`variable`,lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:`variable`,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:r},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:n}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:r},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:r.entity}}],environment:{pattern:RegExp(`\\$?`+t),alias:`constant`},variable:r.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:`class-name`},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:`important`},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:`important`}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},n.inside=e.languages.bash;for(var i=[`comment`,`function-name`,`for-or-select`,`assign-left`,`parameter`,`string`,`environment`,`function`,`keyword`,`builtin`,`boolean`,`file-descriptor`,`operator`,`punctuation`,`number`],a=r.variable[1].inside,o=0;ond(String(e??``)).replace(/\r\n?/g,` +`).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,``),Kg=24e3;function qg(e){return e=Gg(e),e.length>Kg?e.slice(0,Kg)+` +… output truncated; use head or grep to narrow it down.`:e}function Jg(e){let t=document.createDocumentFragment();function n(e,t){if(typeof t==`string`){e.append(document.createTextNode(t));return}if(Array.isArray(t)){t.forEach(t=>n(e,t));return}let r=document.createElement(`span`);r.className=[`token`,t.type,...[t.alias??[]].flat()].join(` `),n(r,t.content),e.append(r)}return n(t,e.length>8192?e:Wg.default.tokenize(e,Wg.default.languages.bash)),t}function Yg(e,{run:t}){let n=t=>e.querySelector(t),r=n(`#command`),i=n(`#command-highlight`),a=n(`#terminal-output`),o=n(`#shell-form`),s=n(`#shell-run`),c=n(`#shell-clear`),l=a.firstElementChild.cloneNode(!0),u=[],d=[],f=0,p=``,m=!1,h=!1,g=()=>a.scrollHeight-a.scrollTop-a.clientHeight<24,_=()=>{a.scrollTop=a.scrollHeight};function v(){s.disabled=m||h||!r.value.trim(),s.textContent=m?`Running…`:`Run`,c.disabled=m||d.length===0}function y(){i.replaceChildren(Jg(r.value),document.createTextNode(` +`)),r.style.height=`auto`,r.style.height=Math.min(104,Math.max(32,r.scrollHeight))+`px`,i.scrollTop=r.scrollTop,i.scrollLeft=r.scrollLeft,v()}function b(e){r.value=e,y(),r.setSelectionRange(e.length,e.length)}function x(){m||(d.length=0,a.replaceChildren(l.cloneNode(!0)),v())}function S(e,t,n){if(!t)return;let r=document.createElement(`pre`);r.className=n,r.textContent=qg(t),e.append(r)}o.onsubmit=async e=>{e.preventDefault();let n=r.value;if(m||h||!n.trim())return;m=!0,u.at(-1)!==n&&u.push(n),u.length>50&&u.shift(),f=u.length,p=``,b(``),r.focus(),d.length||a.replaceChildren();let i=document.createElement(`section`);i.className=`shell-entry`;let o=document.createElement(`div`);o.className=`shell-entry-heading`;let s=document.createElement(`span`);s.className=`shell-prompt`,s.textContent=`$`;let c=document.createElement(`pre`);c.className=`shell-code`,c.append(Jg(qg(n)));let l=document.createElement(`span`);l.className=`shell-status`,l.textContent=`Running…`,o.append(s,c,l),i.append(o),a.append(i),d.push(i),_();try{let e=await t(n),r=g();S(i,e.stdout,`shell-stdout`),S(i,e.stderr,`shell-stderr`),l.classList.add(e.exitCode===0?`success`:`error`),l.textContent=`[exit ${e.exitCode}]`,r&&_()}catch(e){let t=g();S(i,e.message,`shell-stderr`),l.classList.add(`error`),l.textContent=`[error]`,r.value||b(n),t&&_()}finally{for(;d.length>1&&(d.length>40||a.textContent.length>48e3);)d.shift().remove();m=!1,v()}},r.addEventListener(`input`,()=>{f=u.length,p=r.value,y()}),r.addEventListener(`scroll`,()=>{i.scrollTop=r.scrollTop,i.scrollLeft=r.scrollLeft}),r.addEventListener(`keydown`,e=>{if(e.isComposing||e.keyCode===229)return;if(e.key===`Enter`&&!e.shiftKey){e.preventDefault(),o.requestSubmit();return}if(e.ctrlKey&&e.key.toLowerCase()===`l`){e.preventDefault(),x();return}if(e.ctrlKey||e.altKey||e.metaKey||e.shiftKey||r.selectionStart!==r.selectionEnd)return;let t=!r.value.slice(0,r.selectionStart).includes(` +`),n=!r.value.slice(r.selectionEnd).includes(` +`);e.key===`ArrowUp`&&t&&f>0?(e.preventDefault(),f===u.length&&(p=r.value),b(u[--f])):e.key===`ArrowDown`&&n&&f{x(),r.focus()};let C=0;return new ResizeObserver(([e])=>{e.contentRect.width!==C&&(C=e.contentRect.width,y())}).observe(r.parentElement),y(),{setBusy(e){h=e,v()}}}function Xg(e){let t=e.querySelector(`.runtime-value`),n=e.querySelector(`.runtime-sparkline`),r=e.querySelector(`.runtime-bars`),i=e.querySelector(`[role="status"]`),a=e.querySelector(`.runtime-engine`),o=e.querySelector(`.runtime-content`);new ResizeObserver(([t])=>{e.style.width=`calc(${Math.ceil(t.contentRect.width)}px + 2 * var(--runtime-padding))`}).observe(o);let s=!1,c,l=[],u;function d(o,s,d){clearTimeout(u),o!==c&&(i.textContent=d??`${s} in this browser.`),c=o,a.textContent=c===`tool`?`JavaScript`:`WebGPU`,e.dataset.state=c,t.textContent=s,n.setAttribute(`hidden`,``),e.title=d??`${s} in this browser.`,c!==`generating`&&(l=[],r.replaceChildren())}function f(){d(`idle`,s?`Ready`:`Idle`,s?`Model ready. Inference and tools run in this browser.`:`Model loads when you send a message. Inference and tools run in this browser.`)}function p(e){if(!Number.isFinite(e)||e<0){d(`generating`,`Generating…`);return}d(`generating`,`${e<10?e.toFixed(1):Math.round(e)} tok/s`,`Live token generation speed, including thinking tokens. Prompt-processing time is excluded.`),l.push(e),l.length>12&&l.shift();let t=Math.max(40,...l),i=[...Array(12-l.length).fill(null),...l];r.replaceChildren(...i.map((e,n)=>{if(e===null||e===0){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);return t.setAttribute(`cx`,String(n*4+1)),t.setAttribute(`cy`,`17`),t.setAttribute(`r`,`1`),t.setAttribute(`opacity`,e===null?`.35`:`.6`),t}let r=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`),i=Math.max(2,Math.min(16,e/t*16));return r.setAttribute(`x`,String(n*4)),r.setAttribute(`y`,(18-i).toFixed(2)),r.setAttribute(`width`,`2`),r.setAttribute(`height`,i.toFixed(2)),r.setAttribute(`rx`,`1`),r})),n.removeAttribute(`hidden`),u=setTimeout(()=>{d(`generating`,`Generating…`),l=[],r.replaceChildren()},2e3)}return f(),{update(e){e.type===`loaded`?(s=!0,f()):e.type===`idle`||e.type===`initialized`?f():e.type===`fatal`?(s=!1,d(`error`,`Unavailable`)):e.type===`busy`?e.action===`load`?d(`loading`,`Loading…`,e.cachedOnly?`Loading local model…`:void 0):e.action===`prompt`?d(`prefill`,`Reading prompt…`):e.action===`shell`?d(`tool`,`Running bash…`):e.action===`read`?d(`tool`,`Reading file…`):e.action===`write`?d(`tool`,`Writing file…`):d(`working`,`Working…`):e.type===`load_progress`?d(`loading`,e.phase===`download`&&e.loaded2e5)return!1;let t=1;for(let n=0;n5e3)return!1;return!0}function i_(e){let t=e.querySelector(`#editor`),n=e.querySelector(`#editor-highlight`),r=``,i=0,a,o,s,c=!1,l=!1,u;function d(){n.style.width=t.clientWidth+`px`,n.style.height=t.clientHeight+`px`,n.scrollTop=t.scrollTop,n.scrollLeft=t.scrollLeft}function f(){e.classList.remove(`is-highlighted`)}function p(){clearTimeout(o),s?.terminate(),s=void 0,c=!1}function m(){if(c||!u)return;let t=u;u=void 0;try{s||(s=new Worker(new URL(new URL(`editor-highlight.worker-oPpFVFqT.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),s.onmessage=({data:t})=>{clearTimeout(o),c=!1,t.id===i&&t.html!==null&&(n.innerHTML=t.html+` +`,d(),e.classList.add(`is-highlighted`)),m()},s.onerror=()=>{p(),u=void 0}),c=!0,s.postMessage(t),o=setTimeout(()=>{p(),m()},1500)}catch{p()}}function h(n=0){i++,clearTimeout(a),u=void 0,f();let o=n_(r),s=t.value;if(e.dataset.language=o??`plain`,l||!s||!o||!r_(s))return;let c=i;a=setTimeout(()=>{u={id:c,text:s,language:o},m()},n)}t.addEventListener(`input`,()=>h(80)),t.addEventListener(`compositionstart`,()=>{l=!0,h()}),t.addEventListener(`compositionend`,()=>{l=!1,h(80)}),t.addEventListener(`scroll`,d,{passive:!0});let g=new ResizeObserver(d);return g.observe(t),{setFile(e,n){if(r===e&&t.value===n)return;let i=r!==e;r=e,t.value!==n&&(t.value=n),i&&(t.scrollTop=0,t.scrollLeft=0),h()},dispose(){clearTimeout(a),p(),g.disconnect()}}}var a_=`pi-column-ratio`,o_=1/1.83;function s_(e,t){let n=matchMedia(`(min-width: 851px)`),r=getComputedStyle(e),i=parseFloat(r.getPropertyValue(`--conversation-min`)),a=parseFloat(r.getPropertyValue(`--workspace-min`)),o=o_,s,c=0;try{let e=Number(localStorage.getItem(a_));Number.isFinite(e)&&e>0&&e<1&&(o=e)}catch{}function l(){if(!n.matches)return;let r=e.getBoundingClientRect().width;if(!r)return;let s=Math.max(i,Math.min(r-a,r*o));e.style.setProperty(`--conversation-width`,`${s}px`);let c=Math.round(s/r*100);t.setAttribute(`aria-valuemin`,String(Math.round(i/r*100))),t.setAttribute(`aria-valuemax`,String(Math.round((r-a)/r*100))),t.setAttribute(`aria-valuenow`,String(c)),t.setAttribute(`aria-valuetext`,`Chat ${c}%, workspace ${100-c}%`)}function u(){try{localStorage.setItem(a_,String(o))}catch{}}function d(t){let n=e.getBoundingClientRect().width;o=Math.max(i,Math.min(n-a,t))/n,l()}function f(){cancelAnimationFrame(c),c=0,s&&d(s.x-e.getBoundingClientRect().left-s.offset)}function p(e){if(!s)return;e?f():(cancelAnimationFrame(c),c=0,o=s.initialRatio);let n=s.pointer;s=void 0,t.hasPointerCapture(n)&&t.releasePointerCapture(n),document.documentElement.classList.remove(`is-resizing-columns`),l(),e&&u()}function m(){p(!1),o=o_,l(),u()}t.addEventListener(`pointerdown`,r=>{if(!n.matches||r.button!==0||!r.isPrimary||s)return;r.preventDefault(),t.focus({preventScroll:!0});let i=e.querySelector(`.conversation`).getBoundingClientRect().right;s={pointer:r.pointerId,initialRatio:o,x:r.clientX,offset:r.clientX-i},t.setPointerCapture(r.pointerId),document.documentElement.classList.add(`is-resizing-columns`)}),t.addEventListener(`pointermove`,e=>{s&&e.pointerId===s.pointer&&(s.x=e.clientX,c||=requestAnimationFrame(f))}),t.addEventListener(`pointerup`,e=>{s&&e.pointerId===s.pointer&&(s.x=e.clientX,p(!0))}),t.addEventListener(`pointercancel`,()=>p(!1)),t.addEventListener(`lostpointercapture`,()=>p(!1)),t.addEventListener(`dblclick`,m),t.addEventListener(`keydown`,t=>{if(!n.matches)return;if(t.key===`Escape`&&s){t.preventDefault(),p(!1);return}if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`,`Enter`].includes(t.key))return;if(t.preventDefault(),t.key===`Enter`){m();return}p(!1);let r=e.querySelector(`.conversation`).getBoundingClientRect().width,i=t.shiftKey?48:16;d(t.key===`Home`?0:t.key===`End`?1/0:r+(t.key===`ArrowLeft`?-i:i)),u()}),window.addEventListener(`blur`,()=>p(!1)),n.addEventListener(`change`,()=>{p(!1),l()}),new ResizeObserver(l).observe(e),l()}var $=e=>document.querySelector(e);s_($(`main`),$(`#column-resizer`));var c_=new Worker(new URL(new URL(`agent.worker-DAy1yjYb.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),l_=new Map,u_=1,d_=!1,f_=!1,p_,m_=!1,h_={},g_=[],__,v_,y_=new Promise(e=>{__=e}),b_={events:[],generations:[],runtimeSamples:[],device:null,contextUsage:Mg([])},x_=Xg($(`#runtime-meter`)),S_=i_($(`.editor-input`)),C_=Hg($(`#pi-terminal`),{onInput:e=>$(`#send`).classList.toggle(`has-input`,!!e.trim()),load:()=>y_.then(I_),prompt:e=>y_.then(()=>L_(e)),newChat:()=>y_.then(R_),stop:()=>E_(`stop`),shell:e=>{if(m_)throw Error(`Save your file edits before running commands.`);return E_(`shell`,{command:e})}}),w_=Ug($(`#model-dialog`),{onClose:()=>C_.focus()}),T_=Yg($(`.workspace > .terminal`),{run:async e=>{if(await y_,m_)throw Error(`Save your file edits before running commands.`);if(d_)throw Error(`Wait for Pi to finish or stop the current task first.`);return E_(`shell`,{command:e})}});function E_(e,t){return new Promise((n,r)=>{let i=u_++;l_.set(i,{resolve:n,reject:r}),c_.postMessage({id:i,action:e,args:t})})}function D_(e){$(`#notice`).textContent=e,$(`#notice`).hidden=!e}function O_(e){return window.self===window.top||!/denied|storage directory access/i.test(e)?e:($(`#open-tab`).href=location.href,$(`#open-tab`).hidden=!1,`Your browser blocked storage in this embedded app. Open the workspace in a new tab to load the model and save files.`)}function k_(){$(`#load`).disabled=d_||f_,$(`#load`).classList.toggle(`is-loaded`,f_),f_?$(`#load`).textContent=`Loaded`:d_||($(`#load`).textContent=`Load model`),$(`#load`).title=$(`#load-status`).textContent+` `+$(`#load-detail`).textContent,$(`#send`).disabled=d_,$(`#newline`).disabled=d_,C_.setState({busy:d_,loaded:f_,activity:$(`#activity`).textContent}),$(`#stop`).hidden=!d_;for(let e of[`#new-chat`,`#add-file`,`#upload`])$(e).disabled=d_;T_.setBusy(d_),$(`#save`).disabled=d_||!p_||!m_,$(`#editor`).disabled=d_||!p_}function A_(){C_.setFiles(h_),$(`#files`).replaceChildren();for(let e of Object.keys(h_).sort()){let t=document.createElement(`button`),n=document.createElement(`span`);n.className=`file-name`,n.textContent=e.replace(/^\/workspace\//,``),t.append(e_(e),n),t.title=e,t.classList.toggle(`selected`,e===p_),t.onclick=()=>j_(e),$(`#files`).append(t)}p_&&!m_&&S_.setFile(p_,h_[p_]??``)}function j_(e){if(v_=void 0,m_){D_(`Save the open file before selecting another file.`);return}p_=e,$(`#filename`).textContent=e,$(`#filetype`).replaceChildren(e_(e)),A_(),k_()}function M_(){if(m_){v_=void 0;return}if(!v_||!Object.hasOwn(h_,v_))return;let e=v_,t=e!==p_;j_(e),t&&($(`#editor`).scrollTop=0,$(`#editor`).scrollLeft=0);let n=[...$(`#files`).children].find(t=>t.title===e);if(n){let e=n.getBoundingClientRect(),t=$(`#files`).getBoundingClientRect();e.topt.bottom&&($(`#files`).scrollTop+=e.bottom-t.bottom)}}function N_(){C_.setMessages(g_)}function P_(e){b_.contextUsage=e,C_.setState({contextUsage:e})}c_.onmessage=({data:e})=>{if(x_.update(e),e.type===`inference_activity`&&(b_.runtimeSamples.push(e),b_.runtimeSamples.length>160&&b_.runtimeSamples.shift()),e.type===`reply`){let t=l_.get(e.id);l_.delete(e.id),e.error?t?.reject(Object.assign(Error(e.error),{name:e.errorName||`Error`,code:e.errorCode})):t?.resolve(e.value)}else if(e.type===`initialized`)h_=e.files,g_=e.messages,A_(),N_(),P_(Mg(g_)),h_[`/workspace/README.md`]&&j_(`/workspace/README.md`),document.activeElement===document.body&&C_.focus(),__();else if(e.type===`busy`)e.action===`load`&&($(`#load`).textContent=`Loading…`),d_=!0,$(`#activity`).textContent=e.action===`prompt`?`Pi is working…`:e.action===`load`?e.cachedOnly?`Loading local model…`:`Loading model…`:`Working…`,k_();else if(e.type===`idle`)d_=!1,$(`#progress`).hidden=!0,$(`#activity`).textContent=f_?`Ready · running on your device`:`Files and chat are saved on this device.`,k_();else if(e.type===`workspace`)h_=e.files,A_(),M_();else if(e.type===`device`)b_.device=e.device;else if(e.type===`load_progress`)$(`#progress`).hidden=!1,e.phase===`download`?($(`#progress`).hidden=!1,$(`#progress`).value=e.loaded/e.total*100,$(`#load-status`).textContent=e.loaded===e.total?`Download verified. Preparing model…`:`Downloading model weights from Hugging Face…`,$(`#load-detail`).textContent=`${(e.loaded/1e9).toFixed(2)} / ${(e.total/1e9).toFixed(2)} GB · ${Math.round(e.loaded/e.total*100)}%${e.cached?` · ${(e.cached/1e9).toFixed(2)} GB cached`:``}`,$(`#load`).textContent=`Loading ${Math.round(e.loaded/e.total*100)}%`):($(`#load-status`).textContent=e.phase===`compile`?`Preparing WebGPU session…`:`Warming up GPU shaders…`,$(`#load-detail`).textContent=``,$(`#progress`).removeAttribute(`value`),$(`#load`).textContent=e.phase===`compile`?`Preparing…`:`Almost ready…`),$(`#load`).title=$(`#load-status`).textContent+` `+$(`#load-detail`).textContent;else if(e.type===`loaded`)f_=!0,b_.device=e.device,$(`#progress`).hidden=!0,$(`#load`).textContent=`Loaded`,$(`#load-status`).textContent=`Ready. Model inference and tools run entirely in this browser.`,$(`#load-detail`).textContent=e.cachedBytes?`Verified model restored from browser storage.`:`SHA-256 verified · model cached for next time.`,k_();else if(e.type===`agent_event`){let t=e.event;if(b_.events.push(t.type),b_.events.length>500&&b_.events.shift(),t.message){let e=g_.findIndex(e=>e.timestamp===t.message.timestamp&&e.role===t.message.role&&e.toolCallId===t.message.toolCallId);e<0?g_.push(t.message):g_[e]=t.message,N_()}t.type===`tool_execution_start`&&($(`#activity`).textContent=`Running ${t.toolName}…`),t.type===`tool_execution_end`&&t.toolName===`read`&&!t.isError&&typeof t.result?.details?.path==`string`&&(v_=t.result.details.path,M_()),t.type===`turn_start`&&($(`#activity`).textContent=`Pi is thinking…`),C_.setState({activity:$(`#activity`).textContent})}else e.type===`context_usage`?P_({inputTokens:e.inputTokens,outputTokens:e.outputTokens}):e.type===`generation`?(b_.generations.push(e),b_.generations.length>100&&b_.generations.shift()):e.type===`context_trim`?D_(`Older turns were left out of the model context. Your full chat remains saved.`):e.type===`notice`?D_(e.text):e.type===`persistence_error`?D_(O_(e.error)):e.type===`fatal`&&(f_=!1,D_(e.error),k_())},c_.onerror=e=>{x_.update({type:`fatal`});let t=Error(e.message||`The worker stopped. Reload to restore your saved workspace.`);D_(t.message);for(let e of l_.values())e.reject(t);l_.clear(),d_=!1,f_=!1,$(`#progress`).hidden=!0,k_()};var F_=e=>async t=>{t?.preventDefault();try{await y_,await e(t)}catch(e){D_(e.message)}};async function I_({cachedOnly:e=!1}={}){if(d_)throw Error(`Wait for the current operation or stop it first.`);D_(``);let t=new URLSearchParams(location.search);d_=!0,$(`#load`).textContent=`Loading…`,$(`#activity`).textContent=e?`Loading local model…`:`Loading model…`,$(`#load-status`).textContent=e?`Loading local model…`:`Checking your browser and saved model…`,$(`#load-detail`).textContent=``,$(`#progress`).hidden=!1,$(`#progress`).removeAttribute(`value`),x_.update({type:`busy`,action:`load`,cachedOnly:e}),k_();try{return await E_(`load`,{runtimeURL:new URL(`./runtime/`,location.href).href,local:t.get(`source`)===`local`,origin:location.origin,limit128:t.has(`limit128`),cachedOnly:e})}catch(e){throw e.message=O_(e.message),$(`#load-status`).textContent=e.message,$(`#progress`).hidden=!0,e}}async function L_(e){if(e.trim()){if(m_)throw Error(`Save your file edits before asking Pi to work on them.`);try{if(!f_){let t;if(await E_(`cache_status`))try{C_.setQueuedPrompt(e),await I_({cachedOnly:!0})}catch(e){if(e.name===`AbortError`)throw e;e.code!==`MODEL_CACHE_MISS`&&(t=e.message)}for(;!f_;){if(C_.setQueuedPrompt(``),!await w_.request(e,{errorMessage:t}))throw new DOMException(`Message kept for later.`,`AbortError`);C_.setQueuedPrompt(e);try{await I_()}catch(e){if(e.name===`AbortError`)throw e;t=e.message}}}C_.setQueuedPrompt(``),D_(``);let t=await E_(`prompt`,{text:e});return g_=t.messages,N_(),t}finally{C_.setQueuedPrompt(``)}}}$(`#load`).onclick=F_(I_),$(`#send`).onclick=()=>{C_.submit(),C_.focus()},$(`#newline`).onclick=()=>C_.newline(),$(`#stop`).onclick=F_(()=>E_(`stop`)),$(`.terminal-panel`).addEventListener(`click`,e=>{!e.defaultPrevented&&e.button===0&&e.target instanceof Element&&(e.target.closest(`#pi-terminal, button, a, input, textarea, select, label, summary, [role="button"], [contenteditable]`)||window.getSelection()?.isCollapsed!==!1&&C_.focus())});async function R_(){v_=void 0,g_=(await E_(`new_chat`)).messages,P_(Mg(g_)),C_.setMessages(g_,{reset:!0}),D_(``),C_.focus()}$(`#new-chat`).onclick=F_(R_),$(`#editor`).oninput=()=>{m_=!0,k_()},$(`#save`).onclick=F_(async()=>{await E_(`write`,{path:p_,content:$(`#editor`).value}),m_=!1,A_(),k_(),D_(``)}),$(`#add-file`).onclick=F_(async()=>{if(m_)throw Error(`Save the open file first.`);let e=window.prompt(`File path, relative to /workspace:`);if(!e?.trim())return;let t=e.startsWith(`/`)?e:`/workspace/`+e;if(Object.hasOwn(h_,t))throw Error(`That file already exists.`);await E_(`write`,{path:t,content:``}),j_(t)}),$(`#upload`).onchange=F_(async()=>{if(m_)throw Error(`Save the open file first.`);for(let e of $(`#upload`).files){if(e.size>1024**2)throw Error(`Import text files of 1 MiB or less.`);let t=await e.text();if(t.includes(`\0`))throw Error(`Import supports text files only.`);let n=`/workspace/`+e.name;if(Object.hasOwn(h_,n))throw Error(e.name+` already exists. Rename it before importing.`);await E_(`write`,{path:n,content:t}),j_(n)}$(`#upload`).value=``}),$(`#export`).onclick=F_(async()=>{let e=await E_(`snapshot`),t=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:`application/json`})),n=document.createElement(`a`);n.href=t,n.download=`pi-workspace.json`,n.click(),setTimeout(()=>URL.revokeObjectURL(t),1e3)}),window.browserPi={ready:y_,load:I_,prompt:L_,rpc:E_,diagnostics:b_,terminal:C_,runtimeMeter:x_,get loaded(){return f_},get busy(){return d_}},k_(); \ No newline at end of file diff --git a/http-help.html b/http-help.html new file mode 100644 index 0000000000000000000000000000000000000000..479c68a98523501acd2cb95bddc38b96abfbc61f --- /dev/null +++ b/http-help.html @@ -0,0 +1,17 @@ + + +Browser HTTP experiment + +

    HTTP from the browser shell

    +

    This experimental copy enables real curl and wget requests. The model and shell run on your device. Requests go directly from your browser to the destination; there is no proxy. Request URLs, headers, and bodies are sent to that service.

    +

    Allowed HTTPS hosts: api.github.com, raw.githubusercontent.com, huggingface.co, jsonplaceholder.typicode.com, and httpbin.org. GET, HEAD, and POST are enabled. Cookies are omitted. Requests have an 8-second deadline and a 1 MiB response limit.

    +

    Try in Shell

    +
    curl -fsS https://jsonplaceholder.typicode.com/todos/1 -o todo.json
    +jq '{id, title, completed}' todo.json
    +
    set -o pipefail
    +curl -fsS https://api.github.com/repos/huggingface/transformers.js | jq '{full_name, stargazers_count}'
    +

    Ask Pi

    +

    “Fetch https://jsonplaceholder.typicode.com/todos/1, save it as todo.json, and tell me its title and whether it is completed.”

    +

    The destination must allow browser access with CORS. Redirects are reported as errors: use the final URL directly, with the exact capitalization. A plain curl pipeline can hide an error unless you enable set -o pipefail. Python, Node.js, npm, and native binaries remain unavailable.

    +

    Back to the workspace · Original Space

    + diff --git a/index.html b/index.html index 238b39535a65f5c443499dc2c4510950d07728dc..db594fa5064e6dbcad668bae6d3a5feb3c738db0 100644 --- a/index.html +++ b/index.html @@ -10,18 +10,18 @@ - - + + - + Pi · Coding agent in your browser - + @@ -67,7 +67,7 @@
    Enter to run · Shift+Enter for newline↑↓ history
    -

    Bash, text tools, and a virtual filesystem. Node.js, Python, and network commands are unavailable.

    +

    HTTP experiment: curl / wget can reach selected APIs. Browser CORS applies. Hosts & examples ↗

    @@ -78,7 +78,7 @@
    -

    Everything happens in your browser. Your prompts and files stay on this device.

    +

    The model and shell run in your browser. HTTP commands can send requests and data to external services.

    Inference
    On your GPU
    diff --git a/licenses/dependencies.txt b/licenses/dependencies.txt index 7ecdc8dc48bf5b119fda8b9b12799bbe02e57415..d089ace102a352037739dd2376e7b663960927d4 100644 --- a/licenses/dependencies.txt +++ b/licenses/dependencies.txt @@ -12765,202 +12765,6 @@ SOFTWARE. ----------------------------------------- - -node-gyp-build@4.8.4 (MIT) -The MIT License (MIT) - -Copyright (c) 2017 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - ----------------------------------------- - -node-liblzma@2.2.0 (LGPL-3.0) -GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. - - ---------------------------------------- object-keys@1.1.1 (MIT) diff --git a/scripts/stage.py b/scripts/stage.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3290dce370e86a1d3a71f58792d445eece63a5 --- /dev/null +++ b/scripts/stage.py @@ -0,0 +1,17 @@ +from pathlib import Path +import shutil, hashlib, json +root = Path(__file__).resolve().parent.parent +out = root / '.space-http' +if out.exists(): shutil.rmtree(out) +shutil.copytree(root / 'app/dist', out) +for name in ['README.md', 'LICENSE', 'NOTICE', '.gitattributes']: + source = root / name if (root / name).exists() else root / 'source-space' / name + shutil.copyfile(source, out / name) +shutil.copytree(root / 'app', out / 'app', ignore=shutil.ignore_patterns('node_modules', 'dist', '.env', '.env.*')) +shutil.copytree(root / 'scripts', out / 'scripts') +(out / 'validation').mkdir() +for path in (root / 'validation').glob('*'): + if path.is_file() and path.suffix in ['.json', '.md', '.png']: shutil.copyfile(path, out / 'validation' / path.name) +files = {str(p.relative_to(out)): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(out.rglob('*')) if p.is_file()} +(out / 'deployment-manifest.json').write_text(json.dumps({'source': 'victor/MiniCPM5-2B-WebGPU-Pi', 'sourceRevision': '959e272adeb7931e32d3eb2177dc1d5e96c3e967', 'files': files}, indent=2)+'\n') +print(f'Staged {len(files)+1} files for Mike0021/MiniCPM5-2B-WebGPU-Pi-HTTP') diff --git a/validation/source.json b/validation/source.json new file mode 100644 index 0000000000000000000000000000000000000000..48ea803691bdaace470f9d4b40fadb35552df1ae --- /dev/null +++ b/validation/source.json @@ -0,0 +1,11 @@ +{ + "source": "victor/MiniCPM5-2B-WebGPU-Pi", + "revision": "959e272adeb7931e32d3eb2177dc1d5e96c3e967", + "localAssetsMatch": { + "index-CLisF1Ml.css": true, + "editor-highlight.worker-oPpFVFqT.js": true, + "agent.worker-CS8jL-AS.js": true, + "index-DnXFGQ8z.js": true, + "ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm": true + } +}